content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using BookingsApi.DAL.Commands; using BookingsApi.DAL.Dtos; using BookingsApi.DAL.Helper; using BookingsApi.Domain; using BookingsApi.Domain.Enumerations; using BookingsApi.Domain.Participants; using BookingsApi.Domain.Validations; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BookingsApi.DAL.Services { public interface IHearingService { /// <summary> /// Add a participant to a hearing service and returns a list of all participants. /// This will re-use existing personnel entries before attempting to create a new one. /// </summary> /// <param name="hearing">Hearing to amend</param> /// <param name="participants">List of participants to add</param> /// <returns></returns> Task<List<Participant>> AddParticipantToService(VideoHearing hearing, List<NewParticipant> participants); /// <summary> /// Update the case name of a hearing directly /// </summary> /// <param name="hearingId">Id of hearing</param> /// <param name="caseName">New case name</param> /// <returns></returns> Task UpdateHearingCaseName(Guid hearingId, string caseName); /// <summary> /// Create links between participants if any exist /// </summary> /// <param name="participants">List of participants in the hearing</param> /// <param name="linkedParticipantDtos">List linked participants dtos containing the linking data</param> /// <returns></returns> Task CreateParticipantLinks(List<Participant> participants, List<LinkedParticipantDto> linkedParticipantDtos); /// <summary> /// Removes the link between participants /// </summary> /// <param name="participant"></param> /// <param name="linkedParticipantDtos"></param> /// <returns></returns> Task RemoveParticipantLinks(List<Participant> participants, Participant participant); /// <summary> /// Checks to see if a host is present /// </summary> /// <param name="participants">List of participants</param> /// <returns></returns> void ValidateHostCount(IList<Participant> participants); } public class HearingService : IHearingService { private readonly BookingsDbContext _context; public HearingService(BookingsDbContext context) { _context = context; } public async Task<List<Participant>> AddParticipantToService(VideoHearing hearing, List<NewParticipant> participants) { var participantList = new List<Participant>(); foreach (var participantToAdd in participants) { var existingPerson = await _context.Persons .Include("Organisation") .SingleOrDefaultAsync(x => x.Username == participantToAdd.Person.Username || x.ContactEmail == participantToAdd.Person.ContactEmail); if(existingPerson != null) { var person = participantToAdd.Person; existingPerson.UpdatePerson(person.FirstName, person.LastName, existingPerson.Username, person.Title, person.TelephoneNumber); } switch (participantToAdd.HearingRole.UserRole.Name) { case "Individual": var individual = hearing.AddIndividual(existingPerson ?? participantToAdd.Person, participantToAdd.HearingRole, participantToAdd.CaseRole, participantToAdd.DisplayName); UpdateOrganisationDetails(participantToAdd.Person, individual); participantList.Add(individual); break; case "Representative": { var representative = hearing.AddRepresentative(existingPerson ?? participantToAdd.Person, participantToAdd.HearingRole, participantToAdd.CaseRole, participantToAdd.DisplayName, participantToAdd.Representee); UpdateOrganisationDetails(participantToAdd.Person, representative); participantList.Add(representative); break; } case "Judicial Office Holder": { var joh = hearing.AddJudicialOfficeHolder(existingPerson ?? participantToAdd.Person, participantToAdd.HearingRole, participantToAdd.CaseRole, participantToAdd.DisplayName); participantList.Add(joh); break; } case "Judge": { var judge = hearing.AddJudge(existingPerson ?? participantToAdd.Person, participantToAdd.HearingRole, participantToAdd.CaseRole, participantToAdd.DisplayName); participantList.Add(judge); break; } case "Staff Member": { var staffMember = hearing.AddStaffMember(existingPerson ?? participantToAdd.Person, participantToAdd.HearingRole, participantToAdd.CaseRole, participantToAdd.DisplayName); participantList.Add(staffMember); break; } default: throw new DomainRuleException(nameof(participantToAdd.HearingRole.UserRole.Name), $"Role {participantToAdd.HearingRole.UserRole.Name} not recognised"); } } return participantList; } public async Task UpdateHearingCaseName(Guid hearingId, string caseName) { var hearing = await _context.VideoHearings.Include(x => x.HearingCases).ThenInclude(h => h.Case) .FirstAsync(x => x.Id == hearingId); var existingCase = hearing.GetCases().First(); hearing.UpdateCase(new Case(existingCase.Number, caseName) { IsLeadCase = existingCase.IsLeadCase }); await _context.SaveChangesAsync(); } public Task CreateParticipantLinks(List<Participant> participants, List<LinkedParticipantDto> linkedParticipantDtos) { var linkedParticipants = new List<LinkedParticipant>(); foreach (var linkedParticipantDto in linkedParticipantDtos) { var interpretee = participants.Single(x => x.Person.ContactEmail.Equals(linkedParticipantDto.ParticipantContactEmail, StringComparison.CurrentCultureIgnoreCase)); var interpreter = participants.Single(x => x.Person.ContactEmail.Equals(linkedParticipantDto.LinkedParticipantContactEmail, StringComparison.CurrentCultureIgnoreCase)); var linkedParticipant = new LinkedParticipant(interpretee.Id, interpreter.Id, linkedParticipantDto.Type); linkedParticipants.Add(linkedParticipant); UpdateParticipantsWithLinks(interpretee, interpreter, linkedParticipantDto.Type); } return Task.FromResult(linkedParticipants); } public Task RemoveParticipantLinks(List<Participant> participants, Participant participant) { var linkedParticipants = participant.LinkedParticipants.Select(l => new LinkedParticipant(l.ParticipantId, l.LinkedId, l.Type)).ToList(); foreach (var lp in linkedParticipants) { var interpreter = participants.Single(x => x.Id == lp.ParticipantId); var interpretee = participants.Single(x => x.Id == lp.LinkedId); var lp1 = interpreter.LinkedParticipants.Single(x => x.LinkedId == interpretee.Id); var lp2 = interpretee.LinkedParticipants.Single(x => x.LinkedId == interpreter.Id); interpretee.RemoveLink(lp2); interpreter.RemoveLink(lp1); } return Task.CompletedTask; } public void ValidateHostCount(IList<Participant> participants) { var hostHearingRoleIds = _context.HearingRoles.Where(x => x.Name == HearingRoles.Judge || x.Name == HearingRoles.StaffMember).Select(x => x.Id); var hasHost = participants.Any(x => hostHearingRoleIds.Contains(x.HearingRoleId)); if (!hasHost) { throw new DomainRuleException("Host", "A hearing must have at least one host"); } } private void UpdateParticipantsWithLinks(Participant participant1, Participant participant2, LinkedParticipantType linkType) { participant1.AddLink(participant2.Id, linkType); participant2.AddLink(participant1.Id, linkType); } private void UpdateOrganisationDetails(Person newPersonDetails, Participant participantToUpdate) { var newOrganisation = newPersonDetails.Organisation; var existingPerson = participantToUpdate.Person; participantToUpdate.UpdateParticipantDetails(existingPerson.Title, participantToUpdate.DisplayName, newPersonDetails.TelephoneNumber, newOrganisation?.Name); } } }
45.722222
169
0.594168
[ "MIT" ]
hmcts/vh-bookings-api
BookingsApi/BookingsApi.DAL/Services/HearingService.cs
9,876
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Panosen.CodeDom.Tag.Html { /// <summary> /// pre /// </summary> public class PreComponent : HtmlComponent { /// <summary> /// pre /// </summary> public override string Name { get; set; } = "pre"; } }
19.2
58
0.59375
[ "MIT" ]
panosen/panosen-codedom-tag
Panosen.CodeDom.Tag.Html/PreComponent.cs
386
C#
// File generated from our OpenAPI spec namespace Stripe { using Newtonsoft.Json; public class PaymentMethodFpxOptions : INestedOptions { /// <summary> /// Account holder type for FPX transaction. /// One of: <c>company</c>, or <c>individual</c>. /// </summary> [JsonProperty("account_holder_type")] public string AccountHolderType { get; set; } /// <summary> /// The customer's bank. /// One of: <c>affin_bank</c>, <c>agrobank</c>, <c>alliance_bank</c>, <c>ambank</c>, /// <c>bank_islam</c>, <c>bank_muamalat</c>, <c>bank_rakyat</c>, <c>bsn</c>, <c>cimb</c>, /// <c>deutsche_bank</c>, <c>hong_leong_bank</c>, <c>hsbc</c>, <c>kfh</c>, <c>maybank2e</c>, /// <c>maybank2u</c>, <c>ocbc</c>, <c>pb_enterprise</c>, <c>public_bank</c>, <c>rhb</c>, /// <c>standard_chartered</c>, or <c>uob</c>. /// </summary> [JsonProperty("bank")] public string Bank { get; set; } } }
37.37037
100
0.55005
[ "Apache-2.0" ]
Gofundraise/stripe-dotnet
src/Stripe.net/Services/PaymentMethods/PaymentMethodFpxOptions.cs
1,009
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PhotonNetwork.cs" company="Exit Games GmbH"> // Part of: Photon Unity Networking // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Diagnostics; using UnityEngine; using System; using System.Collections.Generic; using ExitGames.Client.Photon; using UnityEngine.SceneManagement; using Debug = UnityEngine.Debug; using Hashtable = ExitGames.Client.Photon.Hashtable; #if UNITY_EDITOR using UnityEditor; using System.IO; #endif /// <summary> /// The main class to use the PhotonNetwork plugin. /// This class is static. /// </summary> /// \ingroup publicApi public static class PhotonNetwork { /// <summary>Version number of PUN. Also used in GameVersion to separate client version from each other.</summary> public const string versionPUN = "1.72"; /// <summary>Version string for your this build. Can be used to separate incompatible clients. Sent during connect.</summary> /// <remarks>This is only sent when you connect so that is also the place you set it usually (e.g. in ConnectUsingSettings).</remarks> public static string gameVersion { get; set; } /// <summary> /// This Monobehaviour allows Photon to run an Update loop. /// </summary> internal static readonly PhotonHandler photonMono; /// <summary> /// Photon peer class that implements LoadBalancing in PUN. /// Primary use is internal (by PUN itself). /// </summary> internal static NetworkingPeer networkingPeer; /// <summary> /// The maximum number of assigned PhotonViews <i>per player</i> (or scene). See the [General Documentation](@ref general) topic "Limitations" on how to raise this limitation. /// </summary> public static readonly int MAX_VIEW_IDS = 1000; // VIEW & PLAYER LIMIT CAN BE EASILY CHANGED, SEE DOCS /// <summary>Name of the PhotonServerSettings file (used to load and by PhotonEditor to save new files).</summary> internal const string serverSettingsAssetFile = "PhotonServerSettings"; /// <summary>Path to the PhotonServerSettings file (used by PhotonEditor).</summary> internal const string serverSettingsAssetPath = "Assets/Photon Unity Networking/Resources/" + PhotonNetwork.serverSettingsAssetFile + ".asset"; /// <summary>Serialized server settings, written by the Setup Wizard for use in ConnectUsingSettings.</summary> public static ServerSettings PhotonServerSettings = (ServerSettings)Resources.Load(PhotonNetwork.serverSettingsAssetFile, typeof(ServerSettings)); /// <summary>Currently used server address (no matter if master or game server).</summary> public static string ServerAddress { get { return (networkingPeer != null) ? networkingPeer.ServerAddress : "<not connected>"; } } /// <summary> /// False until you connected to Photon initially. True in offline mode, while connected to any server and even while switching servers. /// </summary> public static bool connected { get { if (offlineMode) { return true; } if (networkingPeer == null) { return false; } return !networkingPeer.IsInitialConnect && networkingPeer.State != PeerState.PeerCreated && networkingPeer.State != PeerState.Disconnected && networkingPeer.State != PeerState.Disconnecting && networkingPeer.State != PeerState.ConnectingToNameServer; } } /// <summary> /// True when you called ConnectUsingSettings (or similar) until the low level connection to Photon gets established. /// </summary> public static bool connecting { get { return networkingPeer.IsInitialConnect && !offlineMode; } } /// <summary> /// A refined version of connected which is true only if your connection to the server is ready to accept operations like join, leave, etc. /// </summary> public static bool connectedAndReady { get { // connected property will check offlineMode and networkingPeer being null if (!connected) { return false; } if (offlineMode) { return true; } switch (connectionStateDetailed) { case PeerState.PeerCreated: case PeerState.Disconnected: case PeerState.Disconnecting: case PeerState.Authenticating: case PeerState.ConnectingToGameserver: case PeerState.ConnectingToMasterserver: case PeerState.ConnectingToNameServer: case PeerState.Joining: return false; // we are not ready to execute any operations } return true; } } /// <summary> /// Simplified connection state /// </summary> public static ConnectionState connectionState { get { if (offlineMode) { return ConnectionState.Connected; } if (networkingPeer == null) { return ConnectionState.Disconnected; } switch (networkingPeer.PeerState) { case PeerStateValue.Disconnected: return ConnectionState.Disconnected; case PeerStateValue.Connecting: return ConnectionState.Connecting; case PeerStateValue.Connected: return ConnectionState.Connected; case PeerStateValue.Disconnecting: return ConnectionState.Disconnecting; case PeerStateValue.InitializingApplication: return ConnectionState.InitializingApplication; } return ConnectionState.Disconnected; } } /// <summary> /// Detailed connection state (ignorant of PUN, so it can be "disconnected" while switching servers). /// </summary> /// <remarks> /// In OfflineMode, this is PeerState.Joined (after create/join) or it is ConnectedToMaster in all other cases. /// </remarks> public static PeerState connectionStateDetailed { get { if (offlineMode) { return (offlineModeRoom != null) ? PeerState.Joined : PeerState.ConnectedToMaster; } if (networkingPeer == null) { return PeerState.Disconnected; } return networkingPeer.State; } } /// <summary>The server (type) this client is currently connected or connecting to.</summary> /// <remarks>Photon uses 3 different roles of servers: Name Server, Master Server and Game Server.</remarks> public static ServerConnection Server { get { return (PhotonNetwork.networkingPeer != null) ? PhotonNetwork.networkingPeer.server : ServerConnection.NameServer; } } /// <summary> /// A user's authentication values used during connect for Custom Authentication with Photon (and a custom service/community). /// Set these before calling Connect if you want custom authentication. /// </summary> /// <remarks> /// If authentication fails for any values, PUN will call your implementation of OnCustomAuthenticationFailed(string debugMsg). /// See: PhotonNetworkingMessage.OnCustomAuthenticationFailed /// </remarks> public static AuthenticationValues AuthValues { get { return (networkingPeer != null) ? networkingPeer.CustomAuthenticationValues : null; } set { if (networkingPeer != null) networkingPeer.CustomAuthenticationValues = value; } } /// <summary> /// Get the room we're currently in. Null if we aren't in any room. /// </summary> public static Room room { get { if (isOfflineMode) { return offlineModeRoom; } return networkingPeer.CurrentGame; } } /// <summary>If true, Instantiate methods will check if you are in a room and fail if you are not.</summary> /// <remarks> /// Instantiating anything outside of a specific room is very likely to break things. /// Turn this off only if you know what you do.</remarks> public static bool InstantiateInRoomOnly = true; /// <summary> /// Network log level. Controls how verbose PUN is. /// </summary> public static PhotonLogLevel logLevel = PhotonLogLevel.ErrorsOnly; /// <summary> /// The local PhotonPlayer. Always available and represents this player. /// CustomProperties can be set before entering a room and will be synced as well. /// </summary> public static PhotonPlayer player { get { if (networkingPeer == null) { return null; // Surpress ExitApplication errors } return networkingPeer.mLocalActor; } } /// <summary> /// The Master Client of the current room or null (outside of rooms). /// </summary> /// <remarks> /// Can be used as "authoritative" client/player to make descisions, run AI or other. /// /// If the current Master Client leaves the room (leave/disconnect), the server will quickly assign someone else. /// If the current Master Client times out (closed app, lost connection, etc), messages sent to this client are /// effectively lost for the others! A timeout can take 10 seconds in which no Master Client is active. /// /// Implement the method IPunCallbacks.OnMasterClientSwitched to be called when the Master Client switched. /// /// Use PhotonNetwork.SetMasterClient, to switch manually to some other player / client. /// /// With offlineMode == true, this always returns the PhotonNetwork.player. /// </remarks> public static PhotonPlayer masterClient { get { if (offlineMode) { return PhotonNetwork.player; } if (networkingPeer == null) { return null; } return networkingPeer.GetPlayerWithId(networkingPeer.mMasterClientId); } } /// <summary> /// Set to synchronize the player's nickname with everyone in the room(s) you enter. This sets PhotonPlayer.name. /// </summary> /// <remarks> /// The playerName is just a nickname and does not have to be unique or backed up with some account.<br/> /// Set the value any time (e.g. before you connect) and it will be available to everyone you play with.<br/> /// Access the names of players by: PhotonPlayer.name. <br/> /// PhotonNetwork.otherPlayers is a list of other players - each contains the playerName the remote player set. /// </remarks> public static string playerName { get { return networkingPeer.PlayerName; } set { networkingPeer.PlayerName = value; } } /// <summary>The list of players in the current room, including the local player.</summary> /// <remarks> /// This list is only valid, while the client is in a room. /// It automatically gets updated when someone joins or leaves. /// /// This can be used to list all players in a room. /// Each player's PhotonPlayer.customProperties are accessible (set and synchronized via /// PhotonPlayer.SetCustomProperties). /// /// You can use a PhotonPlayer.TagObject to store an arbitrary object for reference. /// That is not synchronized via the network. /// </remarks> public static PhotonPlayer[] playerList { get { if (networkingPeer == null) return new PhotonPlayer[0]; return networkingPeer.mPlayerListCopy; } } /// <summary>The list of players in the current room, excluding the local player.</summary> /// <remarks> /// This list is only valid, while the client is in a room. /// It automatically gets updated when someone joins or leaves. /// /// This can be used to list all other players in a room. /// Each player's PhotonPlayer.customProperties are accessible (set and synchronized via /// PhotonPlayer.SetCustomProperties). /// /// You can use a PhotonPlayer.TagObject to store an arbitrary object for reference. /// That is not synchronized via the network. /// </remarks> public static PhotonPlayer[] otherPlayers { get { if (networkingPeer == null) return new PhotonPlayer[0]; return networkingPeer.mOtherPlayerListCopy; } } /// <summary> /// Read-only list of friends, their online status and the room they are in. Null until initialized by a FindFriends call. /// </summary> /// <remarks> /// Do not modify this list! /// It is internally handled by FindFriends and only available to read the values. /// The value of FriendsListAge tells you how old the data is in milliseconds. /// /// Don't get this list more often than useful (> 10 seconds). In best case, keep the list you fetch really short. /// You could (e.g.) get the full list only once, then request a few updates only for friends who are online. /// After a while (e.g. 1 minute), you can get the full list again (to update online states). /// </remarks> public static List<FriendInfo> Friends { get; internal set; } /// <summary> /// Age of friend list info (in milliseconds). It's 0 until a friend list is fetched. /// </summary> public static int FriendsListAge { get { return (networkingPeer != null) ? networkingPeer.FriendsListAge : 0; } } /// <summary> /// The minimum difference that a Vector2 or Vector3(e.g. a transforms rotation) needs to change before we send it via a PhotonView's OnSerialize/ObservingComponent. /// </summary> /// <remarks> /// Note that this is the sqrMagnitude. E.g. to send only after a 0.01 change on the Y-axix, we use 0.01f*0.01f=0.0001f. As a remedy against float inaccuracy we use 0.000099f instead of 0.0001f. /// </remarks> public static float precisionForVectorSynchronization = 0.000099f; /// <summary> /// The minimum angle that a rotation needs to change before we send it via a PhotonView's OnSerialize/ObservingComponent. /// </summary> public static float precisionForQuaternionSynchronization = 1.0f; /// <summary> /// The minimum difference between floats before we send it via a PhotonView's OnSerialize/ObservingComponent. /// </summary> public static float precisionForFloatSynchronization = 0.01f; /// <summary> /// While enabled, the MonoBehaviours on which we call RPCs are cached, avoiding costly GetComponents<MonoBehaviour>() calls. /// </summary> /// <remarks> /// RPCs are called on the MonoBehaviours of a target PhotonView. Those have to be found via GetComponents. /// /// When set this to true, the list of MonoBehaviours gets cached in each PhotonView. /// You can use photonView.RefreshRpcMonoBehaviourCache() to manually refresh a PhotonView's /// list of MonoBehaviours on demand (when a new MonoBehaviour gets added to a networked GameObject, e.g.). /// </remarks> public static bool UseRpcMonoBehaviourCache; /// <summary> /// While enabled (true), Instantiate uses PhotonNetwork.PrefabCache to keep game objects in memory (improving instantiation of the same prefab). /// </summary> /// <remarks> /// Setting UsePrefabCache to false during runtime will not clear PrefabCache but will ignore it right away. /// You could clean and modify the cache yourself. Read its comments. /// </remarks> public static bool UsePrefabCache = true; /// <summary> /// An Object Pool can be used to keep and reuse instantiated object instances. It replaced Unity's default Instantiate and Destroy methods. /// </summary> /// <remarks> /// To use a GameObject pool, implement IPunPrefabPool and assign it here. /// Prefabs are identified by name. /// </remarks> public static IPunPrefabPool PrefabPool { get { return networkingPeer.ObjectPool; } set { networkingPeer.ObjectPool = value; }} /// <summary> /// Keeps references to GameObjects for frequent instantiation (out of memory instead of loading the Resources). /// </summary> /// <remarks> /// You should be able to modify the cache anytime you like, except while Instantiate is used. Best do it only in the main-Thread. /// </remarks> public static Dictionary<string, GameObject> PrefabCache = new Dictionary<string, GameObject>(); /// <summary> /// If not null, this is the (exclusive) list of GameObjects that get called by PUN SendMonoMessage(). /// </summary> /// <remarks> /// For all callbacks defined in PhotonNetworkingMessage, PUN will use SendMonoMessage and /// call FindObjectsOfType() to find all scripts and GameObjects that might want a callback by PUN. /// /// PUN callbacks are not very frequent (in-game, property updates are most frequent) but /// FindObjectsOfType is time consuming and with a large number of GameObjects, performance might /// suffer. /// /// Optionally, SendMonoMessageTargets can be used to supply a list of target GameObjects. This /// skips the FindObjectsOfType() but any GameObject that needs callbacks will have to Add itself /// to this list. /// /// If null, the default behaviour is to do a SendMessage on each GameObject with a MonoBehaviour. /// </remarks> public static HashSet<GameObject> SendMonoMessageTargets; /// <summary> /// Defines which classes can contain PUN Callback implementations. /// </summary> /// <remarks> /// This provides the option to optimize your runtime for speed.<br/> /// The more specific this Type is, the fewer classes will be checked with reflection for callback methods. /// </remarks> public static Type SendMonoMessageTargetType = typeof(MonoBehaviour); /// <summary> /// Can be used to skip starting RPCs as Coroutine, which can be a performance issue. /// </summary> public static bool StartRpcsAsCoroutine = true; /// <summary> /// Offline mode can be set to re-use your multiplayer code in singleplayer game modes. /// When this is on PhotonNetwork will not create any connections and there is near to /// no overhead. Mostly usefull for reusing RPC's and PhotonNetwork.Instantiate /// </summary> public static bool offlineMode { get { return isOfflineMode; } set { if (value == isOfflineMode) { return; } if (value && connected) { Debug.LogError("Can't start OFFLINE mode while connected!"); return; } if (networkingPeer.PeerState != PeerStateValue.Disconnected) { networkingPeer.Disconnect(); // Cleanup (also calls OnLeftRoom to reset stuff) } isOfflineMode = value; if (isOfflineMode) { networkingPeer.ChangeLocalID(-1); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnConnectedToMaster); } else { offlineModeRoom = null; networkingPeer.ChangeLocalID(-1); } } } private static bool isOfflineMode = false; private static Room offlineModeRoom = null; /// <summary>Only used in Unity Networking. In PUN, set the number of players in PhotonNetwork.CreateRoom.</summary> [Obsolete("Used for compatibility with Unity networking only.")] public static int maxConnections; /// <summary>Defines if all clients in a room should load the same level as the Master Client (if that used PhotonNetwork.LoadLevel).</summary> /// <remarks> /// To synchronize the loaded level, the Master Client should use PhotonNetwork.LoadLevel. /// All clients will load the new scene when they get the update or when they join. /// /// Internally, a Custom Room Property is set for the loaded scene. When a client reads that /// and is not in the same scene yet, it will immediately pause the Message Queue /// (PhotonNetwork.isMessageQueueRunning = false) and load. When the scene finished loading, /// PUN will automatically re-enable the Message Queue. /// </remarks> public static bool automaticallySyncScene { get { return _mAutomaticallySyncScene; } set { _mAutomaticallySyncScene = value; if (_mAutomaticallySyncScene && room != null) { networkingPeer.LoadLevelIfSynced(); } } } private static bool _mAutomaticallySyncScene = false; /// <summary> /// This setting defines per room, if network-instantiated GameObjects (with PhotonView) get cleaned up when the creator of it leaves. /// </summary> /// <remarks> /// This setting is done per room. It can't be changed in the room and it will override the settings of individual clients. /// /// If room.AutoCleanUp is enabled in a room, the PUN clients will destroy a player's GameObjects on leave. /// This includes GameObjects manually instantiated (via RPCs, e.g.). /// When enabled, the server will clean RPCs, instantiated GameObjects and PhotonViews of the leaving player, too. and /// Players who join after someone left, won't get the events of that player anymore. /// /// Under the hood, this setting is stored as a Custom Room Property. /// Enabled by default. /// </remarks> public static bool autoCleanUpPlayerObjects { get { return m_autoCleanUpPlayerObjects; } set { if (room != null) Debug.LogError("Setting autoCleanUpPlayerObjects while in a room is not supported."); else m_autoCleanUpPlayerObjects = value; } } private static bool m_autoCleanUpPlayerObjects = true; /// <summary> /// Set in PhotonServerSettings asset. Defines if the PhotonNetwork should join the "lobby" when connected to the Master server. /// </summary> /// <remarks> /// If this is false, OnConnectedToMaster() will be called when connection to the Master is available. /// OnJoinedLobby() will NOT be called if this is false. /// /// Enabled by default. /// /// The room listing will not become available. /// Rooms can be created and joined (randomly) without joining the lobby (and getting sent the room list). /// </remarks> public static bool autoJoinLobby { get { return PhotonNetwork.PhotonServerSettings.JoinLobby; } set { PhotonNetwork.PhotonServerSettings.JoinLobby = value; } } /// <summary> /// Set in PhotonServerSettings asset. Enable to get a list of active lobbies from the Master Server. /// </summary> /// <remarks> /// Lobby Statistics can be useful if a game uses multiple lobbies and you want /// to show activity of each to players. /// /// This value is stored in PhotonServerSettings. /// /// PhotonNetwork.LobbyStatistics is updated when you connect to the Master Server. /// There is also a callback PunBehaviour. /// </remarks> public static bool EnableLobbyStatistics { get { return PhotonNetwork.PhotonServerSettings.EnableLobbyStatistics; } set { PhotonNetwork.PhotonServerSettings.EnableLobbyStatistics = value; } } /// <summary> /// If turned on, the Master Server will provide information about active lobbies for this application. /// </summary> /// <remarks> /// Lobby Statistics can be useful if a game uses multiple lobbies and you want /// to show activity of each to players. Per lobby, you get: name, type, room- and player-count. /// /// PhotonNetwork.LobbyStatistics is updated when you connect to the Master Server. /// There is also a callback PunBehaviour.OnLobbyStatisticsUpdate, which you should implement /// to update your UI (e.g.). /// /// Lobby Statistics are not turned on by default. /// Enable them in the PhotonServerSettings file of the project. /// </remarks> public static List<TypedLobbyInfo> LobbyStatistics { get { return PhotonNetwork.networkingPeer.LobbyStatistics; } // only available to reset the state conveniently. done by state updates of PUN private set { PhotonNetwork.networkingPeer.LobbyStatistics = value; } } /// <summary>True while this client is in a lobby.</summary> /// <remarks> /// Implement IPunCallbacks.OnReceivedRoomListUpdate() for a notification when the list of rooms /// becomes available or updated. /// /// You are automatically leaving any lobby when you join a room! /// Lobbies only exist on the Master Server (whereas rooms are handled by Game Servers). /// </remarks> public static bool insideLobby { get { return networkingPeer.insideLobby; } } /// <summary> /// The lobby that will be used when PUN joins a lobby or creates a game. /// </summary> /// <remarks> /// The default lobby uses an empty string as name. /// PUN will enter a lobby on the Master Server if autoJoinLobby is set to true. /// So when you connect or leave a room, PUN automatically gets you into a lobby again. /// /// Check PhotonNetwork.insideLobby if the client is in a lobby. /// (@ref masterServerAndLobby) /// </remarks> public static TypedLobby lobby { get { return networkingPeer.lobby; } set { networkingPeer.lobby = value; } } /// <summary> /// Defines how many times per second PhotonNetwork should send a package. If you change /// this, do not forget to also change 'sendRateOnSerialize'. /// </summary> /// <remarks> /// Less packages are less overhead but more delay. /// Setting the sendRate to 50 will create up to 50 packages per second (which is a lot!). /// Keep your target platform in mind: mobile networks are slower and less reliable. /// </remarks> public static int sendRate { get { return 1000 / sendInterval; } set { sendInterval = 1000 / value; if (photonMono != null) { photonMono.updateInterval = sendInterval; } if (value < sendRateOnSerialize) { // sendRateOnSerialize needs to be <= sendRate sendRateOnSerialize = value; } } } /// <summary> /// Defines how many times per second OnPhotonSerialize should be called on PhotonViews. /// </summary> /// <remarks> /// Choose this value in relation to PhotonNetwork.sendRate. OnPhotonSerialize will create updates and messages to be sent.<br/> /// A lower rate takes up less performance but will cause more lag. /// </remarks> public static int sendRateOnSerialize { get { return 1000 / sendIntervalOnSerialize; } set { if (value > sendRate) { Debug.LogError("Error, can not set the OnSerialize SendRate more often then the overall SendRate"); value = sendRate; } sendIntervalOnSerialize = 1000 / value; if (photonMono != null) { photonMono.updateIntervalOnSerialize = sendIntervalOnSerialize; } } } private static int sendInterval = 50; // in miliseconds. private static int sendIntervalOnSerialize = 100; // in miliseconds. I.e. 100 = 100ms which makes 10 times/second /// <summary> /// Can be used to pause dispatching of incoming evtents (RPCs, Instantiates and anything else incoming). /// </summary> /// <remarks> /// While IsMessageQueueRunning == false, the OnPhotonSerializeView calls are not done and nothing is sent by /// a client. Also, incoming messages will be queued until you re-activate the message queue. /// /// This can be useful if you first want to load a level, then go on receiving data of PhotonViews and RPCs. /// The client will go on receiving and sending acknowledgements for incoming packages and your RPCs/Events. /// This adds "lag" and can cause issues when the pause is longer, as all incoming messages are just queued. /// </remarks> public static bool isMessageQueueRunning { get { return m_isMessageQueueRunning; } set { if (value) PhotonHandler.StartFallbackSendAckThread(); networkingPeer.IsSendingOnlyAcks = !value; m_isMessageQueueRunning = value; } } /// <summary>Backup for property isMessageQueueRunning.</summary> private static bool m_isMessageQueueRunning = true; /// <summary> /// Used once per dispatch to limit unreliable commands per channel (so after a pause, many channels can still cause a lot of unreliable commands) /// </summary> public static int unreliableCommandsLimit { get { return networkingPeer.LimitOfUnreliableCommands; } set { networkingPeer.LimitOfUnreliableCommands = value; } } /// <summary> /// Photon network time, synched with the server. /// </summary> /// <remarks> /// v1.55<br/> /// This time value depends on the server's Environment.TickCount. It is different per server /// but inside a Room, all clients should have the same value (Rooms are on one server only).<br/> /// This is not a DateTime!<br/> /// /// Use this value with care: <br/> /// It can start with any positive value.<br/> /// It will "wrap around" from 4294967.295 to 0! /// </remarks> public static double time { get { uint u = (uint)ServerTimestamp; double t = u; return t / 1000; } } /// <summary> /// The current server's millisecond timestamp. /// </summary> /// <remarks> /// This can be useful to sync actions and events on all clients in one room. /// The timestamp is based on the server's Environment.TickCount. /// /// It will overflow from a positive to a negative value every so often, so /// be careful to use only time-differences to check the time delta when things /// happen. /// /// This is the basis for PhotonNetwork.time. /// </remarks> public static int ServerTimestamp { get { if (offlineMode) { if (UsePreciseTimer && startupStopwatch != null && startupStopwatch.IsRunning) { return (int)startupStopwatch.ElapsedMilliseconds; } return Environment.TickCount; } return networkingPeer.ServerTimeInMilliSeconds; } } /// <summary>If true, PUN will use a Stopwatch to measure time since start/connect. This is more precise than the Environment.TickCount used by default.</summary> private static bool UsePreciseTimer = false; static Stopwatch startupStopwatch; /// <summary> /// Defines how long PUN keeps running a "fallback thread" to keep the connection after Unity's OnApplicationPause(true) call. /// </summary> /// <remarks> /// If you set BackgroundTimeout PUN will stop keeping the connection, BackgroundTimeout seconds after OnApplicationPause(true) got called. /// That means: After the set time, a regular timeout can happen. /// Your application will notice that timeout when it becomes active again. /// /// /// To handle the timeout, implement: OnConnectionFail() (this case will use the cause: DisconnectByServerTimeout). /// /// /// It's best practice to let inactive apps/connections time out after a while but allow taking calls, etc. /// So a reasonable value should be found. /// We think it could be 60 seconds. /// /// Set a value greater than 0.001f, if you want to limit how long an app can keep the connection in background. /// /// /// Info: /// PUN is running a "fallback thread" to send ACKs to the server, even when Unity is not calling Update() regularly. /// This helps keeping the connection while loading scenes and assets and when the app is in the background. /// /// Note: /// Some platforms (e.g. iOS) don't allow to keep a connection while the app is in background. /// In those cases, this value does not change anything, the app immediately loses connection in background. /// /// Unity's OnApplicationPause() callback is broken in some exports (Android) of some Unity versions. /// Make sure OnApplicationPause() gets the callbacks you'd expect on the platform you target! /// Check PhotonHandler.OnApplicationPause(bool pause), to see the implementation. /// /// </remarks> public static float BackgroundTimeout = 60.0f; /// <summary> /// Are we the master client? /// </summary> public static bool isMasterClient { get { if (offlineMode) { return true; } else { return networkingPeer.mMasterClientId == player.ID; } } } /// <summary>Is true while being in a room (connectionStateDetailed == PeerState.Joined).</summary> /// <remarks> /// Many actions can only be executed in a room, like Instantiate or Leave, etc. /// You can join a room in offline mode, too. /// </remarks> public static bool inRoom { get { // in offline mode, you can be in a room too and connectionStateDetailed then returns Joined like on online mode! return connectionStateDetailed == PeerState.Joined; } } /// <summary> /// True if we are in a room (client) and NOT the room's masterclient /// </summary> public static bool isNonMasterClientInRoom { get { return !isMasterClient && room != null; } } /// <summary> /// The count of players currently looking for a room (available on MasterServer in 5sec intervals). /// </summary> public static int countOfPlayersOnMaster { get { return networkingPeer.mPlayersOnMasterCount; } } /// <summary> /// Count of users currently playing your app in some room (sent every 5sec by Master Server). Use playerList.Count to get the count of players in the room you're in! /// </summary> public static int countOfPlayersInRooms { get { return networkingPeer.mPlayersInRoomsCount; } } /// <summary> /// The count of players currently using this application (available on MasterServer in 5sec intervals). /// </summary> public static int countOfPlayers { get { return networkingPeer.mPlayersInRoomsCount + networkingPeer.mPlayersOnMasterCount; } } /// <summary> /// The count of rooms currently in use (available on MasterServer in 5sec intervals). /// </summary> /// <remarks> /// While inside the lobby you can also check the count of listed rooms as: PhotonNetwork.GetRoomList().Length. /// Since PUN v1.25 this is only based on the statistic event Photon sends (counting all rooms). /// </remarks> public static int countOfRooms { get { return networkingPeer.mGameCount; } } /// <summary> /// Enables or disables the collection of statistics about this client's traffic. /// </summary> /// <remarks> /// If you encounter issues with clients, the traffic stats are a good starting point to find solutions. /// Only with enabled stats, you can use GetVitalStats /// </remarks> public static bool NetworkStatisticsEnabled { get { return networkingPeer.TrafficStatsEnabled; } set { networkingPeer.TrafficStatsEnabled = value; } } /// <summary> /// Count of commands that got repeated (due to local repeat-timing before an ACK was received). /// </summary> /// <remarks> /// If this value increases a lot, there is a good chance that a timeout disconnect will happen due to bad conditions. /// </remarks> public static int ResentReliableCommands { get { return networkingPeer.ResentReliableCommands; } } /// <summary>Crc checks can be useful to detect and avoid issues with broken datagrams. Can be enabled while not connected.</summary> public static bool CrcCheckEnabled { get { return networkingPeer.CrcEnabled; } set { if (!connected && !connecting) { networkingPeer.CrcEnabled = value; } else { Debug.Log("Can't change CrcCheckEnabled while being connected. CrcCheckEnabled stays " + networkingPeer.CrcEnabled); } } } /// <summary>If CrcCheckEnabled, this counts the incoming packages that don't have a valid CRC checksum and got rejected.</summary> public static int PacketLossByCrcCheck { get { return networkingPeer.PacketLossByCrc; } } /// <summary>Defines the number of times a reliable message can be resent before not getting an ACK for it will trigger a disconnect. Default: 5.</summary> /// <remarks>Less resends mean quicker disconnects, while more can lead to much more lag without helping. Min: 3. Max: 10.</remarks> public static int MaxResendsBeforeDisconnect { get { return networkingPeer.SentCountAllowance; } set { if (value < 3) value = 3; if (value > 10) value = 10; networkingPeer.SentCountAllowance = value; } } /// <summary>In case of network loss, reliable messages can be repeated quickly up to 3 times.</summary> /// <remarks> /// When reliable messages get lost more than once, subsequent repeats are delayed a bit /// to allow the network to recover.<br/> /// With this option, the repeats 2 and 3 can be sped up. This can help avoid timeouts but /// also it increases the speed in which gaps are closed.<br/> /// When you set this, increase PhotonNetwork.MaxResendsBeforeDisconnect to 6 or 7. /// </remarks> public static int QuickResends { get { return networkingPeer.QuickResendAttempts; } set { if (value < 0) value = 0; if (value > 3) value = 3; networkingPeer.QuickResendAttempts = (byte)value; } } /// <summary> /// Defines the delegate usable in OnEventCall. /// </summary> /// <remarks>Any eventCode &lt; 200 will be forwarded to your delegate(s).</remarks> /// <param name="eventCode">The code assigend to the incoming event.</param> /// <param name="content">The content the sender put into the event.</param> /// <param name="senderId">The ID of the player who sent the event. It might be 0, if the "room" sent the event.</param> public delegate void EventCallback(byte eventCode, object content, int senderId); /// <summary>Register your RaiseEvent handling methods here by using "+=".</summary> /// <remarks>Any eventCode &lt; 200 will be forwarded to your delegate(s).</remarks> /// <see cref="RaiseEvent"/> public static EventCallback OnEventCall; internal static int lastUsedViewSubId = 0; // each player only needs to remember it's own (!) last used subId to speed up assignment internal static int lastUsedViewSubIdStatic = 0; // per room, the master is able to instantiate GOs. the subId for this must be unique too internal static List<int> manuallyAllocatedViewIds = new List<int>(); /// <summary> /// Static constructor used for basic setup. /// </summary> static PhotonNetwork() { #if UNITY_EDITOR if (PhotonServerSettings == null) { // create pss CreateSettings(); } if (!EditorApplication.isPlaying && !EditorApplication.isPlayingOrWillChangePlaymode) { //Debug.Log(string.Format("PhotonNetwork.ctor() Not playing {0} {1}", UnityEditor.EditorApplication.isPlaying, UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)); return; } // This can happen when you recompile a script IN play made // This helps to surpress some errors, but will not fix breaking PhotonHandler[] photonHandlers = GameObject.FindObjectsOfType(typeof(PhotonHandler)) as PhotonHandler[]; if (photonHandlers != null && photonHandlers.Length > 0) { Debug.LogWarning("Unity recompiled. Connection gets closed and replaced. You can connect as 'new' client."); foreach (PhotonHandler photonHandler in photonHandlers) { //Debug.Log("Handler: " + photonHandler + " photonHandler.gameObject: " + photonHandler.gameObject); photonHandler.gameObject.hideFlags = 0; GameObject.DestroyImmediate(photonHandler.gameObject); Component.DestroyImmediate(photonHandler); } } #endif Application.runInBackground = true; // Set up a MonoBehaviour to run Photon, and hide it GameObject photonGO = new GameObject(); photonMono = (PhotonHandler)photonGO.AddComponent<PhotonHandler>(); photonGO.name = "PhotonMono"; photonGO.hideFlags = HideFlags.HideInHierarchy; // Set up the NetworkingPeer and use protocol of PhotonServerSettings ConnectionProtocol protocol = PhotonNetwork.PhotonServerSettings.Protocol; #if UNITY_WEBGL if (protocol != ConnectionProtocol.WebSocket && protocol != ConnectionProtocol.WebSocketSecure) { Debug.Log("WebGL only supports WebSocket protocol. Overriding PhotonServerSettings."); protocol = ConnectionProtocol.WebSocketSecure; } #endif networkingPeer = new NetworkingPeer(string.Empty, protocol); networkingPeer.QuickResendAttempts = 2; networkingPeer.SentCountAllowance = 7; if (UsePreciseTimer) { Debug.Log("Using Stopwatch as precision timer for PUN."); startupStopwatch = new Stopwatch(); startupStopwatch.Start(); networkingPeer.LocalMsTimestampDelegate = () => (int)startupStopwatch.ElapsedMilliseconds; } // Local player CustomTypes.Register(); } /// <summary> /// While offline, the network protocol can be switched (which affects the ports you can use to connect). /// </summary> /// <remarks> /// When you switch the protocol, make sure to also switch the port for the master server. Default ports are: /// TCP: 4530 /// UDP: 5055 /// /// This could look like this:<br/> /// Connect(serverAddress, <udpport|tcpport>, appID, gameVersion) /// /// Or when you use ConnectUsingSettings(), the PORT in the settings can be switched like so:<br/> /// PhotonNetwork.PhotonServerSettings.ServerPort = 4530; /// /// The current protocol can be read this way:<br/> /// PhotonNetwork.networkingPeer.UsedProtocol /// /// This does not work with the native socket plugin of PUN+ on mobile! /// </remarks> /// <param name="cp">Network protocol to use as low level connection. UDP is default. TCP is not available on all platforms (see remarks).</param> public static void SwitchToProtocol(ConnectionProtocol cp) { #if UNITY_WEBGL if (cp != ConnectionProtocol.WebSocket && cp != ConnectionProtocol.WebSocketSecure) { Debug.Log("WebGL only supports WebSocket protocol. Overriding PhotonServerSettings."); cp = ConnectionProtocol.WebSocketSecure; } #endif if (networkingPeer.UsedProtocol == cp) { return; } try { networkingPeer.Disconnect(); networkingPeer.StopThread(); } catch { } // set up a new NetworkingPeer NetworkingPeer newPeer = new NetworkingPeer(String.Empty, cp); newPeer.CustomAuthenticationValues = networkingPeer.CustomAuthenticationValues; newPeer.PlayerName= networkingPeer.PlayerName; newPeer.mLocalActor = networkingPeer.mLocalActor; newPeer.DebugOut = networkingPeer.DebugOut; newPeer.CrcEnabled = networkingPeer.CrcEnabled; newPeer.QuickResendAttempts = networkingPeer.QuickResendAttempts; newPeer.DisconnectTimeout = networkingPeer.DisconnectTimeout; newPeer.lobby = networkingPeer.lobby; newPeer.LimitOfUnreliableCommands = networkingPeer.LimitOfUnreliableCommands; newPeer.SentCountAllowance = networkingPeer.SentCountAllowance; newPeer.TrafficStatsEnabled = networkingPeer.TrafficStatsEnabled; networkingPeer = newPeer; Debug.LogWarning("Protocol switched to: " + cp + "."); } /// <summary>Connect to Photon as configured in the editor (saved in PhotonServerSettings file).</summary> /// <remarks> /// This method will disable offlineMode (which won't destroy any instantiated GOs) and it /// will set isMessageQueueRunning to true. /// /// Your server configuration is created by the PUN Wizard and contains the AppId and /// region for Photon Cloud games and the server address if you host Photon yourself. /// These settings usually don't change often. /// /// To ignore the config file and connect anywhere call: PhotonNetwork.ConnectToMaster. /// /// To connect to the Photon Cloud, a valid AppId must be in the settings file (shown in the Photon Cloud Dashboard). /// https://www.photonengine.com/dashboard /// /// Connecting to the Photon Cloud might fail due to: /// - Invalid AppId (calls: OnFailedToConnectToPhoton(). check exact AppId value) /// - Network issues (calls: OnFailedToConnectToPhoton()) /// - Invalid region (calls: OnConnectionFail() with DisconnectCause.InvalidRegion) /// - Subscription CCU limit reached (calls: OnConnectionFail() with DisconnectCause.MaxCcuReached. also calls: OnPhotonMaxCccuReached()) /// /// More about the connection limitations: /// http://doc.exitgames.com/en/pun /// </remarks> /// <param name="gameVersion">This client's version number. Users are separated from each other by gameversion (which allows you to make breaking changes).</param> public static bool ConnectUsingSettings(string gameVersion) { if (networkingPeer.PeerState != PeerStateValue.Disconnected) { Debug.LogWarning("ConnectUsingSettings() failed. Can only connect while in state 'Disconnected'. Current state: " + networkingPeer.PeerState); return false; } if (PhotonServerSettings == null) { Debug.LogError("Can't connect: Loading settings failed. ServerSettings asset must be in any 'Resources' folder as: " + serverSettingsAssetFile); return false; } if (PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet) { Debug.LogError("You did not select a Hosting Type in your PhotonServerSettings. Please set it up or don't use ConnectUsingSettings()."); return false; } SwitchToProtocol(PhotonServerSettings.Protocol); networkingPeer.SetApp(PhotonServerSettings.AppID, gameVersion); if (PhotonServerSettings.HostType == ServerSettings.HostingOption.OfflineMode) { offlineMode = true; return true; } if (offlineMode) { // someone can set offlineMode in code and then call ConnectUsingSettings() with non-offline settings. Warning for that case: Debug.LogWarning("ConnectUsingSettings() disabled the offline mode. No longer offline."); } offlineMode = false; // Cleanup offline mode isMessageQueueRunning = true; networkingPeer.IsInitialConnect = true; if (PhotonServerSettings.HostType == ServerSettings.HostingOption.SelfHosted) { networkingPeer.IsUsingNameServer = false; networkingPeer.MasterServerAddress = (PhotonServerSettings.ServerPort == 0) ? PhotonServerSettings.ServerAddress : PhotonServerSettings.ServerAddress + ":" + PhotonServerSettings.ServerPort; return networkingPeer.Connect(networkingPeer.MasterServerAddress, ServerConnection.MasterServer); } if (PhotonServerSettings.HostType == ServerSettings.HostingOption.BestRegion) { return ConnectToBestCloudServer(gameVersion); } return networkingPeer.ConnectToRegionMaster(PhotonServerSettings.PreferredRegion); } /// <summary>Connect to a Photon Master Server by address, port, appID and game(client) version.</summary> /// <remarks> /// To connect to the Photon Cloud, a valid AppId must be in the settings file (shown in the Photon Cloud Dashboard). /// https://www.photonengine.com/dashboard /// /// Connecting to the Photon Cloud might fail due to: /// - Invalid AppId (calls: OnFailedToConnectToPhoton(). check exact AppId value) /// - Network issues (calls: OnFailedToConnectToPhoton()) /// - Invalid region (calls: OnConnectionFail() with DisconnectCause.InvalidRegion) /// - Subscription CCU limit reached (calls: OnConnectionFail() with DisconnectCause.MaxCcuReached. also calls: OnPhotonMaxCccuReached()) /// /// More about the connection limitations: /// http://doc.exitgames.com/en/pun /// </remarks> /// <param name="masterServerAddress">The server's address (either your own or Photon Cloud address).</param> /// <param name="port">The server's port to connect to.</param> /// <param name="appID">Your application ID (Photon Cloud provides you with a GUID for your game).</param> /// <param name="gameVersion">This client's version number. Users are separated by gameversion (which allows you to make breaking changes).</param> public static bool ConnectToMaster(string masterServerAddress, int port, string appID, string gameVersion) { if (networkingPeer.PeerState != PeerStateValue.Disconnected) { Debug.LogWarning("ConnectToMaster() failed. Can only connect while in state 'Disconnected'. Current state: " + networkingPeer.PeerState); return false; } if (offlineMode) { offlineMode = false; // Cleanup offline mode Debug.LogWarning("ConnectToMaster() disabled the offline mode. No longer offline."); } if (!isMessageQueueRunning) { isMessageQueueRunning = true; Debug.LogWarning("ConnectToMaster() enabled isMessageQueueRunning. Needs to be able to dispatch incoming messages."); } networkingPeer.SetApp(appID, gameVersion); networkingPeer.IsUsingNameServer = false; networkingPeer.IsInitialConnect = true; networkingPeer.MasterServerAddress = (port == 0) ? masterServerAddress : masterServerAddress + ":" + port; return networkingPeer.Connect(networkingPeer.MasterServerAddress, ServerConnection.MasterServer); } /// <summary>Can be used to reconnect to the master server after a disconnect.</summary> /// <remarks> /// After losing connection, you can use this to connect a client to the region Master Server again. /// Cache the room name you're in and use ReJoin(roomname) to return to a game. /// Common use case: Press the Lock Button on a iOS device and you get disconnected immediately. /// </remarks> public static bool Reconnect() { if (string.IsNullOrEmpty(networkingPeer.MasterServerAddress)) { Debug.LogWarning("Reconnect() failed. It seems the client wasn't connected before?! Current state: " + networkingPeer.PeerState); return false; } if (networkingPeer.PeerState != PeerStateValue.Disconnected) { Debug.LogWarning("Reconnect() failed. Can only connect while in state 'Disconnected'. Current state: " + networkingPeer.PeerState); return false; } if (offlineMode) { offlineMode = false; // Cleanup offline mode Debug.LogWarning("Reconnect() disabled the offline mode. No longer offline."); } if (!isMessageQueueRunning) { isMessageQueueRunning = true; Debug.LogWarning("Reconnect() enabled isMessageQueueRunning. Needs to be able to dispatch incoming messages."); } networkingPeer.IsUsingNameServer = false; networkingPeer.IsInitialConnect = false; return networkingPeer.ReconnectToMaster(); } /// <summary>When the client lost connection during gameplay, this method attempts to reconnect and rejoin the room.</summary> /// <remarks> /// This method re-connects directly to the game server which was hosting the room PUN was in before. /// If the room was shut down in the meantime, PUN will call OnPhotonJoinRoomFailed and return this client to the Master Server. /// /// Check the return value, if this client will attempt a reconnect and rejoin (if the conditions are met). /// If ReconnectAndRejoin returns false, you can still attempt a Reconnect and ReJoin. /// /// Similar to PhotonNetwork.ReJoin, this requires you to use unique IDs per player (the UserID). /// </remarks> /// <returns>False, if there is no known room or game server to return to. Then, this client does not attempt the ReconnectAndRejoin.</returns> public static bool ReconnectAndRejoin() { if (networkingPeer.PeerState != PeerStateValue.Disconnected) { Debug.LogWarning("ReconnectAndRejoin() failed. Can only connect while in state 'Disconnected'. Current state: " + networkingPeer.PeerState); return false; } if (offlineMode) { offlineMode = false; // Cleanup offline mode Debug.LogWarning("ReconnectAndRejoin() disabled the offline mode. No longer offline."); } if (string.IsNullOrEmpty(networkingPeer.mGameserver)) { Debug.LogWarning("ReconnectAndRejoin() failed. It seems the client wasn't connected to a game server before (no address)."); return false; } if (networkingPeer.enterRoomParamsCache == null) { Debug.LogWarning("ReconnectAndRejoin() failed. It seems the client doesn't have any previous room to re-join."); return false; } if (!isMessageQueueRunning) { isMessageQueueRunning = true; Debug.LogWarning("ReconnectAndRejoin() enabled isMessageQueueRunning. Needs to be able to dispatch incoming messages."); } networkingPeer.IsUsingNameServer = false; networkingPeer.IsInitialConnect = false; return networkingPeer.ReconnectAndRejoin(); } /// <summary> /// Connect to the Photon Cloud region with the lowest ping (on platforms that support Unity's Ping). /// </summary> /// <remarks> /// Will save the result of pinging all cloud servers in PlayerPrefs. Calling this the first time can take +-2 seconds. /// The ping result can be overridden via PhotonNetwork.OverrideBestCloudServer(..) /// This call can take up to 2 seconds if it is the first time you are using this, all cloud servers will be pinged to check for the best region. /// /// The PUN Setup Wizard stores your appID in a settings file and applies a server address/port. /// To connect to the Photon Cloud, a valid AppId must be in the settings file (shown in the Photon Cloud Dashboard). /// https://www.photonengine.com/dashboard /// /// Connecting to the Photon Cloud might fail due to: /// - Invalid AppId (calls: OnFailedToConnectToPhoton(). check exact AppId value) /// - Network issues (calls: OnFailedToConnectToPhoton()) /// - Invalid region (calls: OnConnectionFail() with DisconnectCause.InvalidRegion) /// - Subscription CCU limit reached (calls: OnConnectionFail() with DisconnectCause.MaxCcuReached. also calls: OnPhotonMaxCccuReached()) /// /// More about the connection limitations: /// http://doc.exitgames.com/en/pun /// </remarks> /// <param name="gameVersion">This client's version number. Users are separated from each other by gameversion (which allows you to make breaking changes).</param> /// <returns>If this client is going to connect to cloud server based on ping. Even if true, this does not guarantee a connection but the attempt is being made.</returns> public static bool ConnectToBestCloudServer(string gameVersion) { if (networkingPeer.PeerState != PeerStateValue.Disconnected) { Debug.LogWarning("ConnectToBestCloudServer() failed. Can only connect while in state 'Disconnected'. Current state: " + networkingPeer.PeerState); return false; } if (PhotonServerSettings == null) { Debug.LogError("Can't connect: Loading settings failed. ServerSettings asset must be in any 'Resources' folder as: " + PhotonNetwork.serverSettingsAssetFile); return false; } if (PhotonServerSettings.HostType == ServerSettings.HostingOption.OfflineMode) { return PhotonNetwork.ConnectUsingSettings(gameVersion); } networkingPeer.IsInitialConnect = true; networkingPeer.SetApp(PhotonServerSettings.AppID, gameVersion); CloudRegionCode bestFromPrefs = PhotonHandler.BestRegionCodeInPreferences; if (bestFromPrefs != CloudRegionCode.none) { Debug.Log("Best region found in PlayerPrefs. Connecting to: " + bestFromPrefs); return networkingPeer.ConnectToRegionMaster(bestFromPrefs); } bool couldConnect = PhotonNetwork.networkingPeer.ConnectToNameServer(); return couldConnect; } /// <summary> /// Connects to the Photon Cloud region of choice. /// </summary> public static bool ConnectToRegion(CloudRegionCode region, string gameVersion) { if (networkingPeer.PeerState != PeerStateValue.Disconnected) { Debug.LogWarning("ConnectToRegion() failed. Can only connect while in state 'Disconnected'. Current state: " + networkingPeer.PeerState); return false; } if (PhotonServerSettings == null) { Debug.LogError("Can't connect: ServerSettings asset must be in any 'Resources' folder as: " + PhotonNetwork.serverSettingsAssetFile); return false; } if (PhotonServerSettings.HostType == ServerSettings.HostingOption.OfflineMode) { return PhotonNetwork.ConnectUsingSettings(gameVersion); } networkingPeer.IsInitialConnect = true; networkingPeer.SetApp(PhotonServerSettings.AppID, gameVersion); if (region != CloudRegionCode.none) { Debug.Log("ConnectToRegion: " + region); return networkingPeer.ConnectToRegionMaster(region); } return false; } /// <summary>Overwrites the region that is used for ConnectToBestCloudServer(string gameVersion).</summary> /// <remarks> /// This will overwrite the result of pinging all cloud servers.<br/> /// Use this to allow your users to save a manually selected region in the player preferences.<br/> /// Note: You can also use PhotonNetwork.ConnectToRegion to (temporarily) connect to a specific region. /// </remarks> public static void OverrideBestCloudServer(CloudRegionCode region) { PhotonHandler.BestRegionCodeInPreferences = region; } /// <summary>Pings all cloud servers again to find the one with best ping (currently).</summary> public static void RefreshCloudServerRating() { throw new NotImplementedException("not available at the moment"); } /// <summary> /// Resets the traffic stats and re-enables them. /// </summary> public static void NetworkStatisticsReset() { networkingPeer.TrafficStatsReset(); } /// <summary> /// Only available when NetworkStatisticsEnabled was used to gather some stats. /// </summary> /// <returns>A string with vital networking statistics.</returns> public static string NetworkStatisticsToString() { if (networkingPeer == null || offlineMode) { return "Offline or in OfflineMode. No VitalStats available."; } return networkingPeer.VitalStatsToString(false); } /// <summary> /// Used for compatibility with Unity networking only. Encryption is automatically initialized while connecting. /// </summary> [Obsolete("Used for compatibility with Unity networking only. Encryption is automatically initialized while connecting.")] public static void InitializeSecurity() { return; } /// <summary> /// Helper function which is called inside this class to erify if certain functions can be used (e.g. RPC when not connected) /// </summary> /// <returns></returns> private static bool VerifyCanUseNetwork() { if (connected) { return true; } Debug.LogError("Cannot send messages when not connected. Either connect to Photon OR use offline mode!"); return false; } /// <summary> /// Makes this client disconnect from the photon server, a process that leaves any room and calls OnDisconnectedFromPhoton on completion. /// </summary> /// <remarks> /// When you disconnect, the client will send a "disconnecting" message to the server. This speeds up leave/disconnect /// messages for players in the same room as you (otherwise the server would timeout this client's connection). /// When used in offlineMode, the state-change and event-call OnDisconnectedFromPhoton are immediate. /// Offline mode is set to false as well. /// Once disconnected, the client can connect again. Use ConnectUsingSettings. /// </remarks> public static void Disconnect() { if (offlineMode) { offlineMode = false; offlineModeRoom = null; networkingPeer.State = PeerState.Disconnecting; networkingPeer.OnStatusChanged(StatusCode.Disconnect); return; } if (networkingPeer == null) { return; // Surpress error when quitting playmode in the editor } networkingPeer.Disconnect(); } /// <summary> /// Requests the rooms and online status for a list of friends and saves the result in PhotonNetwork.Friends. /// </summary> /// <remarks> /// Works only on Master Server to find the rooms played by a selected list of users. /// /// The result will be stored in PhotonNetwork.Friends when available. /// That list is initialized on first use of OpFindFriends (before that, it is null). /// To refresh the list, call FindFriends again (in 5 seconds or 10 or 20). /// /// Users identify themselves by setting a unique username via PhotonNetwork.playerName /// or by PhotonNetwork.AuthValues. The user id set in AuthValues overrides the playerName, /// so make sure you know the ID your friends use to authenticate. /// The AuthValues are sent in OpAuthenticate when you connect, so the AuthValues must be /// set before you connect! /// /// Note: Changing a player's name doesn't make sense when using a friend list. /// /// The list of friends must be fetched from some other source (not provided by Photon). /// /// /// Internal: /// The server response includes 2 arrays of info (each index matching a friend from the request): /// ParameterCode.FindFriendsResponseOnlineList = bool[] of online states /// ParameterCode.FindFriendsResponseRoomIdList = string[] of room names (empty string if not in a room) /// </remarks> /// <param name="friendsToFind">Array of friend (make sure to use unique playerName or AuthValues).</param> /// <returns>If the operation could be sent (requires connection, only one request is allowed at any time). Always false in offline mode.</returns> public static bool FindFriends(string[] friendsToFind) { if (networkingPeer == null || isOfflineMode) { return false; } return networkingPeer.OpFindFriends(friendsToFind); } /// <summary> /// Creates a room with given name but fails if this room(name) is existing already. Creates random name for roomName null. /// </summary> /// <remarks> /// If you don't want to create a unique room-name, pass null or "" as name and the server will assign a roomName (a GUID as string). /// /// The created room is automatically placed in the currently used lobby (if any) or the default-lobby if you didn't explicitly join one. /// /// Call this only on the master server. /// Internally, the master will respond with a server-address (and roomName, if needed). Both are used internally /// to switch to the assigned game server and roomName. /// /// PhotonNetwork.autoCleanUpPlayerObjects will become this room's AutoCleanUp property and that's used by all clients that join this room. /// </remarks> /// <param name="roomName">Unique name of the room to create.</param> /// <returns>If the operation got queued and will be sent.</returns> public static bool CreateRoom(string roomName) { return CreateRoom(roomName, null, null, null); } /// <summary> /// Creates a room but fails if this room is existing already. Can only be called on Master Server. /// </summary> /// <remarks> /// When successful, this calls the callbacks OnCreatedRoom and OnJoinedRoom (the latter, cause you join as first player). /// If the room can't be created (because it exists already), OnPhotonCreateRoomFailed gets called. /// /// If you don't want to create a unique room-name, pass null or "" as name and the server will assign a roomName (a GUID as string). /// /// Rooms can be created in any number of lobbies. Those don't have to exist before you create a room in them (they get /// auto-created on demand). Lobbies can be useful to split room lists on the server-side already. That can help keep the room /// lists short and manageable. /// If you set a typedLobby parameter, the room will be created in that lobby (no matter if you are active in any). /// If you don't set a typedLobby, the room is automatically placed in the currently active lobby (if any) or the /// default-lobby. /// /// Call this only on the master server. /// Internally, the master will respond with a server-address (and roomName, if needed). Both are used internally /// to switch to the assigned game server and roomName. /// /// PhotonNetwork.autoCleanUpPlayerObjects will become this room's autoCleanUp property and that's used by all clients that join this room. /// </remarks> /// <param name="roomName">Unique name of the room to create. Pass null or "" to make the server generate a name.</param> /// <param name="roomOptions">Common options for the room like maxPlayers, initial custom room properties and similar. See RoomOptions type..</param> /// <param name="typedLobby">If null, the room is automatically created in the currently used lobby (which is "default" when you didn't join one explicitly).</param> /// <returns>If the operation got queued and will be sent.</returns> public static bool CreateRoom(string roomName, RoomOptions roomOptions, TypedLobby typedLobby) { return CreateRoom(roomName, roomOptions, typedLobby, null); } /// <summary> /// Creates a room but fails if this room is existing already. Can only be called on Master Server. /// </summary> /// <remarks> /// When successful, this calls the callbacks OnCreatedRoom and OnJoinedRoom (the latter, cause you join as first player). /// If the room can't be created (because it exists already), OnPhotonCreateRoomFailed gets called. /// /// If you don't want to create a unique room-name, pass null or "" as name and the server will assign a roomName (a GUID as string). /// /// Rooms can be created in any number of lobbies. Those don't have to exist before you create a room in them (they get /// auto-created on demand). Lobbies can be useful to split room lists on the server-side already. That can help keep the room /// lists short and manageable. /// If you set a typedLobby parameter, the room will be created in that lobby (no matter if you are active in any). /// If you don't set a typedLobby, the room is automatically placed in the currently active lobby (if any) or the /// default-lobby. /// /// Call this only on the master server. /// Internally, the master will respond with a server-address (and roomName, if needed). Both are used internally /// to switch to the assigned game server and roomName. /// /// PhotonNetwork.autoCleanUpPlayerObjects will become this room's autoCleanUp property and that's used by all clients that join this room. /// /// You can define an array of expectedUsers, to block player slots in the room for these users. /// The corresponding feature in Photon is called "Slot Reservation" and can be found in the doc pages. /// </remarks> /// <param name="roomName">Unique name of the room to create. Pass null or "" to make the server generate a name.</param> /// <param name="roomOptions">Common options for the room like maxPlayers, initial custom room properties and similar. See RoomOptions type..</param> /// <param name="typedLobby">If null, the room is automatically created in the currently used lobby (which is "default" when you didn't join one explicitly).</param> /// <param name="expectedUsers">Optional list of users (by UserId) who are expected to join this game and who you want to block a slot for.</param> /// <returns>If the operation got queued and will be sent.</returns> public static bool CreateRoom(string roomName, RoomOptions roomOptions, TypedLobby typedLobby, string[] expectedUsers) { if (offlineMode) { if (offlineModeRoom != null) { Debug.LogError("CreateRoom failed. In offline mode you still have to leave a room to enter another."); return false; } EnterOfflineRoom(roomName, roomOptions, true); return true; } if (networkingPeer.server != ServerConnection.MasterServer || !connectedAndReady) { Debug.LogError("CreateRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster."); return false; } typedLobby = typedLobby ?? ((networkingPeer.insideLobby) ? networkingPeer.lobby : null); // use given lobby, or active lobby (if any active) or none EnterRoomParams opParams = new EnterRoomParams(); opParams.RoomName = roomName; opParams.RoomOptions = roomOptions; opParams.Lobby = typedLobby; opParams.ExpectedUsers = expectedUsers; return networkingPeer.OpCreateGame(opParams); } /// <summary>Join room by roomname and on success calls OnJoinedRoom(). This is not affected by lobbies.</summary> /// <remarks> /// On success, the method OnJoinedRoom() is called on any script. You can implement it to react to joining a room. /// /// JoinRoom fails if the room is either full or no longer available (it might become empty while you attempt to join). /// Implement OnPhotonJoinRoomFailed() to get a callback in error case. /// /// To join a room from the lobby's listing, use RoomInfo.name as roomName here. /// Despite using multiple lobbies, a roomName is always "global" for your application and so you don't /// have to specify which lobby it's in. The Master Server will find the room. /// In the Photon Cloud, an application is defined by AppId, Game- and PUN-version. /// </remarks> /// <see cref="PhotonNetworkingMessage.OnPhotonJoinRoomFailed"/> /// <see cref="PhotonNetworkingMessage.OnJoinedRoom"/> /// <param name="roomName">Unique name of the room to join.</param> /// <returns>If the operation got queued and will be sent.</returns> public static bool JoinRoom(string roomName) { return JoinRoom(roomName, null); } /// <summary>Join room by roomname and on success calls OnJoinedRoom(). This is not affected by lobbies.</summary> /// <remarks> /// On success, the method OnJoinedRoom() is called on any script. You can implement it to react to joining a room. /// /// JoinRoom fails if the room is either full or no longer available (it might become empty while you attempt to join). /// Implement OnPhotonJoinRoomFailed() to get a callback in error case. /// /// To join a room from the lobby's listing, use RoomInfo.name as roomName here. /// Despite using multiple lobbies, a roomName is always "global" for your application and so you don't /// have to specify which lobby it's in. The Master Server will find the room. /// In the Photon Cloud, an application is defined by AppId, Game- and PUN-version. /// /// You can define an array of expectedUsers, to block player slots in the room for these users. /// The corresponding feature in Photon is called "Slot Reservation" and can be found in the doc pages. /// </remarks> /// <see cref="PhotonNetworkingMessage.OnPhotonJoinRoomFailed"/> /// <see cref="PhotonNetworkingMessage.OnJoinedRoom"/> /// <param name="roomName">Unique name of the room to join.</param> /// <param name="expectedUsers">Optional list of users (by UserId) who are expected to join this game and who you want to block a slot for.</param> /// <returns>If the operation got queued and will be sent.</returns> public static bool JoinRoom(string roomName, string[] expectedUsers) { if (offlineMode) { if (offlineModeRoom != null) { Debug.LogError("JoinRoom failed. In offline mode you still have to leave a room to enter another."); return false; } EnterOfflineRoom(roomName, null, true); return true; } if (networkingPeer.server != ServerConnection.MasterServer || !connectedAndReady) { Debug.LogError("JoinRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster."); return false; } if (string.IsNullOrEmpty(roomName)) { Debug.LogError("JoinRoom failed. A roomname is required. If you don't know one, how will you join?"); return false; } EnterRoomParams opParams = new EnterRoomParams(); opParams.RoomName = roomName; opParams.ExpectedUsers = expectedUsers; return networkingPeer.OpJoinRoom(opParams); } /// <summary>Lets you either join a named room or create it on the fly - you don't have to know if someone created the room already.</summary> /// <remarks> /// This makes it easier for groups of players to get into the same room. Once the group /// exchanged a roomName, any player can call JoinOrCreateRoom and it doesn't matter who /// actually joins or creates the room. /// /// The parameters roomOptions and typedLobby are only used when the room actually gets created by this client. /// You know if this client created a room, if you get a callback OnCreatedRoom (before OnJoinedRoom gets called as well). /// </remarks> /// <param name="roomName">Name of the room to join. Must be non null.</param> /// <param name="roomOptions">Options for the room, in case it does not exist yet. Else these values are ignored.</param> /// <param name="typedLobby">Lobby you want a new room to be listed in. Ignored if the room was existing and got joined.</param> /// <returns>If the operation got queued and will be sent.</returns> public static bool JoinOrCreateRoom(string roomName, RoomOptions roomOptions, TypedLobby typedLobby) { return JoinOrCreateRoom(roomName, roomOptions, typedLobby, null); } /// <summary>Lets you either join a named room or create it on the fly - you don't have to know if someone created the room already.</summary> /// <remarks> /// This makes it easier for groups of players to get into the same room. Once the group /// exchanged a roomName, any player can call JoinOrCreateRoom and it doesn't matter who /// actually joins or creates the room. /// /// The parameters roomOptions and typedLobby are only used when the room actually gets created by this client. /// You know if this client created a room, if you get a callback OnCreatedRoom (before OnJoinedRoom gets called as well). /// /// You can define an array of expectedUsers, to block player slots in the room for these users. /// The corresponding feature in Photon is called "Slot Reservation" and can be found in the doc pages. /// </remarks> /// <param name="roomName">Name of the room to join. Must be non null.</param> /// <param name="roomOptions">Options for the room, in case it does not exist yet. Else these values are ignored.</param> /// <param name="typedLobby">Lobby you want a new room to be listed in. Ignored if the room was existing and got joined.</param> /// <param name="expectedUsers">Optional list of users (by UserId) who are expected to join this game and who you want to block a slot for.</param> /// <returns>If the operation got queued and will be sent.</returns> public static bool JoinOrCreateRoom(string roomName, RoomOptions roomOptions, TypedLobby typedLobby, string[] expectedUsers) { if (offlineMode) { if (offlineModeRoom != null) { Debug.LogError("JoinOrCreateRoom failed. In offline mode you still have to leave a room to enter another."); return false; } EnterOfflineRoom(roomName, roomOptions, true); // in offline mode, JoinOrCreateRoom assumes you create the room return true; } if (networkingPeer.server != ServerConnection.MasterServer || !connectedAndReady) { Debug.LogError("JoinOrCreateRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster."); return false; } if (string.IsNullOrEmpty(roomName)) { Debug.LogError("JoinOrCreateRoom failed. A roomname is required. If you don't know one, how will you join?"); return false; } typedLobby = typedLobby ?? ((networkingPeer.insideLobby) ? networkingPeer.lobby : null); // use given lobby, or active lobby (if any active) or none EnterRoomParams opParams = new EnterRoomParams(); opParams.RoomName = roomName; opParams.RoomOptions = roomOptions; opParams.Lobby = typedLobby; opParams.CreateIfNotExists = true; opParams.PlayerProperties = player.customProperties; opParams.ExpectedUsers = expectedUsers; return networkingPeer.OpJoinRoom(opParams); } /// <summary> /// Joins any available room of the currently used lobby and fails if none is available. /// </summary> /// <remarks> /// Rooms can be created in arbitrary lobbies which get created on demand. /// You can join rooms from any lobby without actually joining the lobby. /// Use the JoinRandomRoom overload with TypedLobby parameter. /// /// This method will only match rooms attached to one lobby! If you use many lobbies, you /// might have to repeat JoinRandomRoom, to find some fitting room. /// This method looks up a room in the currently active lobby or (if no lobby is joined) /// in the default lobby. /// /// If this fails, you can still create a room (and make this available for the next who uses JoinRandomRoom). /// Alternatively, try again in a moment. /// </remarks> public static bool JoinRandomRoom() { return JoinRandomRoom(null, 0, MatchmakingMode.FillRoom, null, null); } /// <summary> /// Attempts to join an open room with fitting, custom properties but fails if none is currently available. /// </summary> /// <remarks> /// Rooms can be created in arbitrary lobbies which get created on demand. /// You can join rooms from any lobby without actually joining the lobby. /// Use the JoinRandomRoom overload with TypedLobby parameter. /// /// This method will only match rooms attached to one lobby! If you use many lobbies, you /// might have to repeat JoinRandomRoom, to find some fitting room. /// This method looks up a room in the currently active lobby or (if no lobby is joined) /// in the default lobby. /// /// If this fails, you can still create a room (and make this available for the next who uses JoinRandomRoom). /// Alternatively, try again in a moment. /// </remarks> /// <param name="expectedCustomRoomProperties">Filters for rooms that match these custom properties (string keys and values). To ignore, pass null.</param> /// <param name="expectedMaxPlayers">Filters for a particular maxplayer setting. Use 0 to accept any maxPlayer value.</param> /// <returns>If the operation got queued and will be sent.</returns> public static bool JoinRandomRoom(Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers) { return JoinRandomRoom(expectedCustomRoomProperties, expectedMaxPlayers, MatchmakingMode.FillRoom, null, null); } /// <summary> /// Attempts to join an open room with fitting, custom properties but fails if none is currently available. /// </summary> /// <remarks> /// Rooms can be created in arbitrary lobbies which get created on demand. /// You can join rooms from any lobby without actually joining the lobby with this overload. /// /// This method will only match rooms attached to one lobby! If you use many lobbies, you /// might have to repeat JoinRandomRoom, to find some fitting room. /// This method looks up a room in the specified lobby or the currently active lobby (if none specified) /// or in the default lobby (if none active). /// /// If this fails, you can still create a room (and make this available for the next who uses JoinRandomRoom). /// Alternatively, try again in a moment. /// /// In offlineMode, a room will be created but no properties will be set and all parameters of this /// JoinRandomRoom call are ignored. The event/callback OnJoinedRoom gets called (see enum PhotonNetworkingMessage). /// /// You can define an array of expectedUsers, to block player slots in the room for these users. /// The corresponding feature in Photon is called "Slot Reservation" and can be found in the doc pages. /// </remarks> /// <param name="expectedCustomRoomProperties">Filters for rooms that match these custom properties (string keys and values). To ignore, pass null.</param> /// <param name="expectedMaxPlayers">Filters for a particular maxplayer setting. Use 0 to accept any maxPlayer value.</param> /// <param name="matchingType">Selects one of the available matchmaking algorithms. See MatchmakingMode enum for options.</param> /// <param name="typedLobby">The lobby in which you want to lookup a room. Pass null, to use the default lobby. This does not join that lobby and neither sets the lobby property.</param> /// <param name="sqlLobbyFilter">A filter-string for SQL-typed lobbies.</param> /// <param name="expectedUsers">Optional list of users (by UserId) who are expected to join this game and who you want to block a slot for.</param> /// <returns>If the operation got queued and will be sent.</returns> public static bool JoinRandomRoom(Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers, MatchmakingMode matchingType, TypedLobby typedLobby, string sqlLobbyFilter, string[] expectedUsers = null) { if (offlineMode) { if (offlineModeRoom != null) { Debug.LogError("JoinRandomRoom failed. In offline mode you still have to leave a room to enter another."); return false; } EnterOfflineRoom("offline room", null, true); return true; } if (networkingPeer.server != ServerConnection.MasterServer || !connectedAndReady) { Debug.LogError("JoinRandomRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster."); return false; } typedLobby = typedLobby ?? ((networkingPeer.insideLobby) ? networkingPeer.lobby : null); // use given lobby, or active lobby (if any active) or none OpJoinRandomRoomParams opParams = new OpJoinRandomRoomParams(); opParams.ExpectedCustomRoomProperties = expectedCustomRoomProperties; opParams.ExpectedMaxPlayers = expectedMaxPlayers; opParams.MatchingType = matchingType; opParams.TypedLobby = typedLobby; opParams.SqlLobbyFilter = sqlLobbyFilter; opParams.ExpectedUsers = expectedUsers; return networkingPeer.OpJoinRandomRoom(opParams); } /// <summary>Can be used to return to a room after a disconnect and reconnect.</summary> /// <remarks> /// After losing connection, you might be able to return to a room and continue playing, /// if the client is reconnecting fast enough. Use Reconnect() and this method. /// Cache the room name you're in and use ReJoin(roomname) to return to a game. /// /// Note: To be able to ReJoin any room, you need to use UserIDs! /// You also need to set RoomOptions.PlayerTtl. /// /// <b>Important: Instantiate() and use of RPCs is not yet supported.</b> /// The ownership rules of PhotonViews prevent a seamless return to a game. /// Use Custom Properties and RaiseEvent with event caching instead. /// /// Common use case: Press the Lock Button on a iOS device and you get disconnected immediately. /// </remarks> public static bool ReJoinRoom(string roomName) { if (offlineMode) { Debug.LogError("ReJoinRoom failed due to offline mode."); return false; } if (networkingPeer.server != ServerConnection.MasterServer || !connectedAndReady) { Debug.LogError("ReJoinRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster."); return false; } if (string.IsNullOrEmpty(roomName)) { Debug.LogError("ReJoinRoom failed. A roomname is required. If you don't know one, how will you join?"); return false; } EnterRoomParams opParams = new EnterRoomParams(); opParams.RoomName = roomName; opParams.RejoinOnly = true; opParams.PlayerProperties = player.customProperties; return networkingPeer.OpJoinRoom(opParams); } /// <summary> /// Internally used helper-method to setup an offline room, the numbers for actor and master-client and to do the callbacks. /// </summary> private static void EnterOfflineRoom(string roomName, RoomOptions roomOptions, bool createdRoom) { offlineModeRoom = new Room(roomName, roomOptions); networkingPeer.ChangeLocalID(1); offlineModeRoom.masterClientId = 1; if (createdRoom) { NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom); } NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); } /// <summary>On MasterServer this joins the default lobby which list rooms currently in use.</summary> /// <remarks> /// The room list is sent and refreshed by the server. You can access this cached list by /// PhotonNetwork.GetRoomList(). /// /// Per room you should check if it's full or not before joining. Photon also lists rooms that are /// full, unless you close and hide them (room.open = false and room.visible = false). /// /// In best case, you make your clients join random games, as described here: /// http://doc.exitgames.com/en/realtime/current/reference/matchmaking-and-lobby /// /// /// You can show your current players and room count without joining a lobby (but you must /// be on the master server). Use: countOfPlayers, countOfPlayersOnMaster, countOfPlayersInRooms and /// countOfRooms. /// /// You can use more than one lobby to keep the room lists shorter. See JoinLobby(TypedLobby lobby). /// When creating new rooms, they will be "attached" to the currently used lobby or the default lobby. /// /// You can use JoinRandomRoom without being in a lobby! /// Set autoJoinLobby = false before you connect, to not join a lobby. In that case, the /// connect-workflow will call OnConnectedToMaster (if you implement it) when it's done. /// </remarks> public static bool JoinLobby() { return JoinLobby(null); } /// <summary>On a Master Server you can join a lobby to get lists of available rooms.</summary> /// <remarks> /// The room list is sent and refreshed by the server. You can access this cached list by /// PhotonNetwork.GetRoomList(). /// /// Any client can "make up" any lobby on the fly. Splitting rooms into multiple lobbies will /// keep each list shorter. However, having too many lists might ruin the matchmaking experience. /// /// In best case, you create a limited number of lobbies. For example, create a lobby per /// game-mode: "koth" for king of the hill and "ffa" for free for all, etc. /// /// There is no listing of lobbies at the moment. /// /// Sql-typed lobbies offer a different filtering model for random matchmaking. This might be more /// suited for skillbased-games. However, you will also need to follow the conventions for naming /// filterable properties in sql-lobbies! Both is explained in the matchmaking doc linked below. /// /// In best case, you make your clients join random games, as described here: /// http://confluence.exitgames.com/display/PTN/Op+JoinRandomGame /// /// /// Per room you should check if it's full or not before joining. Photon does list rooms that are /// full, unless you close and hide them (room.open = false and room.visible = false). /// /// You can show your games current players and room count without joining a lobby (but you must /// be on the master server). Use: countOfPlayers, countOfPlayersOnMaster, countOfPlayersInRooms and /// countOfRooms. /// /// When creating new rooms, they will be "attached" to the currently used lobby or the default lobby. /// /// You can use JoinRandomRoom without being in a lobby! /// Set autoJoinLobby = false before you connect, to not join a lobby. In that case, the /// connect-workflow will call OnConnectedToMaster (if you implement it) when it's done. /// </remarks> /// <param name="typedLobby">A typed lobby to join (must have name and type).</param> public static bool JoinLobby(TypedLobby typedLobby) { if (PhotonNetwork.connected && PhotonNetwork.Server == ServerConnection.MasterServer) { if (typedLobby == null) { typedLobby = TypedLobby.Default; } bool sending = networkingPeer.OpJoinLobby(typedLobby); if (sending) { networkingPeer.lobby = typedLobby; } return sending; } return false; } /// <summary>Leave a lobby to stop getting updates about available rooms.</summary> /// <remarks> /// This does not reset PhotonNetwork.lobby! This allows you to join this particular lobby later /// easily. /// /// The values countOfPlayers, countOfPlayersOnMaster, countOfPlayersInRooms and countOfRooms /// are received even without being in a lobby. /// /// You can use JoinRandomRoom without being in a lobby. /// Use autoJoinLobby to not join a lobby when you connect. /// </remarks> public static bool LeaveLobby() { if (PhotonNetwork.connected && PhotonNetwork.Server == ServerConnection.MasterServer) { return networkingPeer.OpLeaveLobby(); } return false; } /// <summary>Leave the current room and return to the Master Server where you can join or create rooms (see remarks).</summary> /// <remarks> /// This will clean up all (network) GameObjects with a PhotonView, unless you changed autoCleanUp to false. /// Returns to the Master Server. /// /// In OfflineMode, the local "fake" room gets cleaned up and OnLeftRoom gets called immediately. /// </remarks> public static bool LeaveRoom() { if (offlineMode) { offlineModeRoom = null; NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnLeftRoom); } else { if (room == null) { Debug.LogWarning("PhotonNetwork.room is null. You don't have to call LeaveRoom() when you're not in one. State: " + PhotonNetwork.connectionStateDetailed); } return networkingPeer.OpLeave(); } return true; } /// <summary> /// Gets currently known rooms as RoomInfo array. This is available and updated while in a lobby (check insideLobby). /// </summary> /// <remarks> /// This list is a cached copy of the internal rooms list so it can be accessed each frame if needed. /// Per RoomInfo you can check if the room is full by comparing playerCount and maxPlayers before you allow a join. /// /// The name of a room must be used to join it (via JoinRoom). /// /// Closed rooms are also listed by lobbies but they can't be joined. While in a room, any player can set /// Room.visible and Room.open to hide rooms from matchmaking and close them. /// </remarks> /// <returns>RoomInfo[] of current rooms in lobby.</returns> public static RoomInfo[] GetRoomList() { if (offlineMode || networkingPeer == null) { return new RoomInfo[0]; } return networkingPeer.mGameListCopy; } /// <summary> /// Sets this (local) player's properties and synchronizes them to the other players (don't modify them directly). /// </summary> /// <remarks> /// While in a room, your properties are synced with the other players. /// CreateRoom, JoinRoom and JoinRandomRoom will all apply your player's custom properties when you enter the room. /// The whole Hashtable will get sent. Minimize the traffic by setting only updated key/values. /// /// If the Hashtable is null, the custom properties will be cleared. /// Custom properties are never cleared automatically, so they carry over to the next room, if you don't change them. /// /// Don't set properties by modifying PhotonNetwork.player.customProperties! /// </remarks> /// <param name="customProperties">Only string-typed keys will be used from this hashtable. If null, custom properties are all deleted.</param> public static void SetPlayerCustomProperties(Hashtable customProperties) { if (customProperties == null) { customProperties = new Hashtable(); foreach (object k in player.customProperties.Keys) { customProperties[(string)k] = null; } } if (room != null && room.isLocalClientInside) { player.SetCustomProperties(customProperties); } else { player.InternalCacheProperties(customProperties); } } /// <summary> /// Locally removes Custom Properties of "this" player. Important: This does not synchronize the change! Useful when you switch rooms. /// </summary> /// <remarks> /// Use this method with care. It can create inconsistencies of state between players! /// This only changes the player.customProperties locally. This can be useful to clear your /// Custom Properties between games (let's say they store which turn you made, kills, etc). /// /// SetPlayerCustomProperties() syncs and can be used to set values to null while in a room. /// That can be considered "removed" while in a room. /// /// If customPropertiesToDelete is null or has 0 entries, all Custom Properties are deleted (replaced with a new Hashtable). /// If you specify keys to remove, those will be removed from the Hashtable but other keys are unaffected. /// </remarks> /// <param name="customPropertiesToDelete">List of Custom Property keys to remove. See remarks.</param> public static void RemovePlayerCustomProperties(string[] customPropertiesToDelete) { if (customPropertiesToDelete == null || customPropertiesToDelete.Length == 0 || player.customProperties == null) { player.customProperties = new Hashtable(); return; } // if a specific list of props should be deleted, we do that here for (int i = 0; i < customPropertiesToDelete.Length; i++) { string key = customPropertiesToDelete[i]; if (player.customProperties.ContainsKey(key)) { player.customProperties.Remove(key); } } } /// <summary> /// Sends fully customizable events in a room. Events consist of at least an EventCode (0..199) and can have content. /// </summary> /// <remarks> /// To receive the events someone sends, register your handling method in PhotonNetwork.OnEventCall. /// /// Example: /// private void OnEventHandler(byte eventCode, object content, int senderId) /// { Debug.Log("OnEventHandler"); } /// /// PhotonNetwork.OnEventCall += this.OnEventHandler; /// /// With the senderId, you can look up the PhotonPlayer who sent the event. /// It is best practice to assign a eventCode for each different type of content and action. You have to cast the content. /// /// The eventContent is optional. To be able to send something, it must be a "serializable type", something that /// the client can turn into a byte[] basically. Most basic types and arrays of them are supported, including /// Unity's Vector2, Vector3, Quaternion. Transforms or classes some project defines are NOT supported! /// You can make your own class a "serializable type" by following the example in CustomTypes.cs. /// /// /// The RaiseEventOptions have some (less intuitive) combination rules: /// If you set targetActors (an array of PhotonPlayer.ID values), the receivers parameter gets ignored. /// When using event caching, the targetActors, receivers and interestGroup can't be used. Buffered events go to all. /// When using cachingOption removeFromRoomCache, the eventCode and content are actually not sent but used as filter. /// </remarks> /// <param name="eventCode">A byte identifying the type of event. You might want to use a code per action or to signal which content can be expected. Allowed: 0..199.</param> /// <param name="eventContent">Some serializable object like string, byte, integer, float (etc) and arrays of those. Hashtables with byte keys are good to send variable content.</param> /// <param name="sendReliable">Makes sure this event reaches all players. It gets acknowledged, which requires bandwidth and it can't be skipped (might add lag in case of loss).</param> /// <param name="options">Allows more complex usage of events. If null, RaiseEventOptions.Default will be used (which is fine).</param> /// <returns>False if event could not be sent</returns> public static bool RaiseEvent(byte eventCode, object eventContent, bool sendReliable, RaiseEventOptions options) { if (!inRoom || eventCode >= 200) { Debug.LogWarning("RaiseEvent() failed. Your event is not being sent! Check if your are in a Room and the eventCode must be less than 200 (0..199)."); return false; } return networkingPeer.OpRaiseEvent(eventCode, eventContent, sendReliable, options); } /// <summary> /// Allocates a viewID that's valid for the current/local player. /// </summary> /// <returns>A viewID that can be used for a new PhotonView.</returns> public static int AllocateViewID() { int manualId = AllocateViewID(player.ID); manuallyAllocatedViewIds.Add(manualId); return manualId; } /// <summary> /// Enables the Master Client to allocate a viewID that is valid for scene objects. /// </summary> /// <returns>A viewID that can be used for a new PhotonView or -1 in case of an error.</returns> public static int AllocateSceneViewID() { if (!PhotonNetwork.isMasterClient) { Debug.LogError("Only the Master Client can AllocateSceneViewID(). Check PhotonNetwork.isMasterClient!"); return -1; } int manualId = AllocateViewID(0); manuallyAllocatedViewIds.Add(manualId); return manualId; } // use 0 for scene-targetPhotonView-ids // returns viewID (combined owner and sub id) private static int AllocateViewID(int ownerId) { if (ownerId == 0) { // we look up a fresh subId for the owner "room" (mind the "sub" in subId) int newSubId = lastUsedViewSubIdStatic; int newViewId; int ownerIdOffset = ownerId * MAX_VIEW_IDS; for (int i = 1; i < MAX_VIEW_IDS; i++) { newSubId = (newSubId + 1) % MAX_VIEW_IDS; if (newSubId == 0) { continue; // avoid using subID 0 } newViewId = newSubId + ownerIdOffset; if (!networkingPeer.photonViewList.ContainsKey(newViewId)) { lastUsedViewSubIdStatic = newSubId; return newViewId; } } // this is the error case: we didn't find any (!) free subId for this user throw new Exception(string.Format("AllocateViewID() failed. Room (user {0}) is out of 'scene' viewIDs. It seems all available are in use.", ownerId)); } else { // we look up a fresh SUBid for the owner int newSubId = lastUsedViewSubId; int newViewId; int ownerIdOffset = ownerId * MAX_VIEW_IDS; for (int i = 1; i < MAX_VIEW_IDS; i++) { newSubId = (newSubId + 1) % MAX_VIEW_IDS; if (newSubId == 0) { continue; // avoid using subID 0 } newViewId = newSubId + ownerIdOffset; if (!networkingPeer.photonViewList.ContainsKey(newViewId) && !manuallyAllocatedViewIds.Contains(newViewId)) { lastUsedViewSubId = newSubId; return newViewId; } } throw new Exception(string.Format("AllocateViewID() failed. User {0} is out of subIds, as all viewIDs are used.", ownerId)); } } private static int[] AllocateSceneViewIDs(int countOfNewViews) { int[] viewIDs = new int[countOfNewViews]; for (int view = 0; view < countOfNewViews; view++) { viewIDs[view] = AllocateViewID(0); } return viewIDs; } /// <summary> /// Unregister a viewID (of manually instantiated and destroyed networked objects). /// </summary> /// <param name="viewID">A viewID manually allocated by this player.</param> public static void UnAllocateViewID(int viewID) { manuallyAllocatedViewIds.Remove(viewID); if (networkingPeer.photonViewList.ContainsKey(viewID)) { Debug.LogWarning(string.Format("UnAllocateViewID() should be called after the PhotonView was destroyed (GameObject.Destroy()). ViewID: {0} still found in: {1}", viewID, networkingPeer.photonViewList[viewID])); } } /// <summary> /// Instantiate a prefab over the network. This prefab needs to be located in the root of a "Resources" folder. /// </summary> /// <remarks> /// Instead of using prefabs in the Resources folder, you can manually Instantiate and assign PhotonViews. See doc. /// </remarks> /// <param name="prefabName">Name of the prefab to instantiate.</param> /// <param name="position">Position Vector3 to apply on instantiation.</param> /// <param name="rotation">Rotation Quaternion to apply on instantiation.</param> /// <param name="group">The group for this PhotonView.</param> /// <returns>The new instance of a GameObject with initialized PhotonView.</returns> public static GameObject Instantiate(string prefabName, Vector3 position, Quaternion rotation, int group) { return Instantiate(prefabName, position, rotation, group, null); } /// <summary> /// Instantiate a prefab over the network. This prefab needs to be located in the root of a "Resources" folder. /// </summary> /// <remarks>Instead of using prefabs in the Resources folder, you can manually Instantiate and assign PhotonViews. See doc.</remarks> /// <param name="prefabName">Name of the prefab to instantiate.</param> /// <param name="position">Position Vector3 to apply on instantiation.</param> /// <param name="rotation">Rotation Quaternion to apply on instantiation.</param> /// <param name="group">The group for this PhotonView.</param> /// <param name="data">Optional instantiation data. This will be saved to it's PhotonView.instantiationData.</param> /// <returns>The new instance of a GameObject with initialized PhotonView.</returns> public static GameObject Instantiate(string prefabName, Vector3 position, Quaternion rotation, int group, object[] data) { if (!connected || (InstantiateInRoomOnly && !inRoom)) { Debug.LogError("Failed to Instantiate prefab: " + prefabName + ". Client should be in a room. Current connectionStateDetailed: " + PhotonNetwork.connectionStateDetailed); return null; } GameObject prefabGo; if (!UsePrefabCache || !PrefabCache.TryGetValue(prefabName, out prefabGo)) { prefabGo = (GameObject)Resources.Load(prefabName, typeof(GameObject)); if (UsePrefabCache) { PrefabCache.Add(prefabName, prefabGo); } } if (prefabGo == null) { Debug.LogError("Failed to Instantiate prefab: " + prefabName + ". Verify the Prefab is in a Resources folder (and not in a subfolder)"); return null; } // a scene object instantiated with network visibility has to contain a PhotonView if (prefabGo.GetComponent<PhotonView>() == null) { Debug.LogError("Failed to Instantiate prefab:" + prefabName + ". Prefab must have a PhotonView component."); return null; } Component[] views = (Component[])prefabGo.GetPhotonViewsInChildren(); int[] viewIDs = new int[views.Length]; for (int i = 0; i < viewIDs.Length; i++) { //Debug.Log("Instantiate prefabName: " + prefabName + " player.ID: " + player.ID); viewIDs[i] = AllocateViewID(player.ID); } // Send to others, create info Hashtable instantiateEvent = networkingPeer.SendInstantiate(prefabName, position, rotation, group, viewIDs, data, false); // Instantiate the GO locally (but the same way as if it was done via event). This will also cache the instantiationId return networkingPeer.DoInstantiate(instantiateEvent, networkingPeer.mLocalActor, prefabGo); } /// <summary> /// Instantiate a scene-owned prefab over the network. The PhotonViews will be controllable by the MasterClient. This prefab needs to be located in the root of a "Resources" folder. /// </summary> /// <remarks> /// Only the master client can Instantiate scene objects. /// Instead of using prefabs in the Resources folder, you can manually Instantiate and assign PhotonViews. See doc. /// </remarks> /// <param name="prefabName">Name of the prefab to instantiate.</param> /// <param name="position">Position Vector3 to apply on instantiation.</param> /// <param name="rotation">Rotation Quaternion to apply on instantiation.</param> /// <param name="group">The group for this PhotonView.</param> /// <param name="data">Optional instantiation data. This will be saved to it's PhotonView.instantiationData.</param> /// <returns>The new instance of a GameObject with initialized PhotonView.</returns> public static GameObject InstantiateSceneObject(string prefabName, Vector3 position, Quaternion rotation, int group, object[] data) { if (!connected || (InstantiateInRoomOnly && !inRoom)) { Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". Client should be in a room. Current connectionStateDetailed: " + PhotonNetwork.connectionStateDetailed); return null; } if (!isMasterClient) { Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". Client is not the MasterClient in this room."); return null; } GameObject prefabGo; if (!UsePrefabCache || !PrefabCache.TryGetValue(prefabName, out prefabGo)) { prefabGo = (GameObject)Resources.Load(prefabName, typeof(GameObject)); if (UsePrefabCache) { PrefabCache.Add(prefabName, prefabGo); } } if (prefabGo == null) { Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". Verify the Prefab is in a Resources folder (and not in a subfolder)"); return null; } // a scene object instantiated with network visibility has to contain a PhotonView if (prefabGo.GetComponent<PhotonView>() == null) { Debug.LogError("Failed to InstantiateSceneObject prefab:" + prefabName + ". Prefab must have a PhotonView component."); return null; } Component[] views = (Component[])prefabGo.GetPhotonViewsInChildren(); int[] viewIDs = AllocateSceneViewIDs(views.Length); if (viewIDs == null) { Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". No ViewIDs are free to use. Max is: " + MAX_VIEW_IDS); return null; } // Send to others, create info Hashtable instantiateEvent = networkingPeer.SendInstantiate(prefabName, position, rotation, group, viewIDs, data, true); // Instantiate the GO locally (but the same way as if it was done via event). This will also cache the instantiationId return networkingPeer.DoInstantiate(instantiateEvent, networkingPeer.mLocalActor, prefabGo); } /// <summary> /// The current roundtrip time to the photon server. /// </summary> /// <returns>Roundtrip time (to server and back).</returns> public static int GetPing() { return networkingPeer.RoundTripTime; } /// <summary>Refreshes the server timestamp (async operation, takes a roundtrip).</summary> /// <remarks>Can be useful if a bad connection made the timestamp unusable or imprecise.</remarks> public static void FetchServerTimestamp() { if (networkingPeer != null) { networkingPeer.FetchServerTimestamp(); } } /// <summary> /// Can be used to immediately send the RPCs and Instantiates just called, so they are on their way to the other players. /// </summary> /// <remarks> /// This could be useful if you do a RPC to load a level and then load it yourself. /// While loading, no RPCs are sent to others, so this would delay the "load" RPC. /// You can send the RPC to "others", use this method, disable the message queue /// (by isMessageQueueRunning) and then load. /// </remarks> public static void SendOutgoingCommands() { if (!VerifyCanUseNetwork()) { return; } while (networkingPeer.SendOutgoingCommands()) { } } /// <summary>Request a client to disconnect (KICK). Only the master client can do this</summary> /// <remarks>Only the target player gets this event. That player will disconnect automatically, which is what the others will notice, too.</remarks> /// <param name="kickPlayer">The PhotonPlayer to kick.</param> public static bool CloseConnection(PhotonPlayer kickPlayer) { if (!VerifyCanUseNetwork()) { return false; } if (!player.isMasterClient) { Debug.LogError("CloseConnection: Only the masterclient can kick another player."); return false; } if (kickPlayer == null) { Debug.LogError("CloseConnection: No such player connected!"); return false; } RaiseEventOptions options = new RaiseEventOptions() { TargetActors = new int[] { kickPlayer.ID } }; return networkingPeer.OpRaiseEvent(PunEvent.CloseConnection, null, true, options); } /// <summary> /// Asks the server to assign another player as Master Client of your current room. /// </summary> /// <remarks> /// RPCs and RaiseEvent have the option to send messages only to the Master Client of a room. /// SetMasterClient affects which client gets those messages. /// /// This method calls an operation on the server to set a new Master Client, which takes a roundtrip. /// In case of success, this client and the others get the new Master Client from the server. /// /// SetMasterClient tells the server which current Master Client should be replaced with the new one. /// It will fail, if anything switches the Master Client moments earlier. There is no callback for this /// error. All clients should get the new Master Client assigned by the server anyways. /// /// See also: PhotonNetwork.masterClient /// /// On v3 servers: /// The ReceiverGroup.MasterClient (usable in RPCs) is not affected by this (still points to lowest player.ID in room). /// Avoid using this enum value (and send to a specific player instead). /// /// If the current Master Client leaves, PUN will detect a new one by "lowest player ID". Implement OnMasterClientSwitched /// to get a callback in this case. The PUN-selected Master Client might assign a new one. /// /// Make sure you don't create an endless loop of Master-assigning! When selecting a custom Master Client, all clients /// should point to the same player, no matter who actually assigns this player. /// /// Locally the Master Client is immediately switched, while remote clients get an event. This means the game /// is tempoarily without Master Client like when a current Master Client leaves. /// /// When switching the Master Client manually, keep in mind that this user might leave and not do it's work, just like /// any Master Client. /// /// </remarks> /// <param name="masterClientPlayer">The player to become the next Master Client.</param> /// <returns>False when this operation couldn't be done. Must be in a room (not in offlineMode).</returns> public static bool SetMasterClient(PhotonPlayer masterClientPlayer) { if (!inRoom || !VerifyCanUseNetwork() || offlineMode) { if (logLevel == PhotonLogLevel.Informational) Debug.Log("Can not SetMasterClient(). Not in room or in offlineMode."); return false; } if (room.serverSideMasterClient) { Hashtable newProps = new Hashtable() { { GamePropertyKey.MasterClientId, masterClientPlayer.ID } }; Hashtable prevProps = new Hashtable() { { GamePropertyKey.MasterClientId, networkingPeer.mMasterClientId } }; return networkingPeer.OpSetPropertiesOfRoom(newProps, expectedProperties: prevProps, webForward: false); } else { if (!isMasterClient) { return false; } return networkingPeer.SetMasterClient(masterClientPlayer.ID, true); } } /// <summary> /// Network-Destroy the GameObject associated with the PhotonView, unless the PhotonView is static or not under this client's control. /// </summary> /// <remarks> /// Destroying a networked GameObject while in a Room includes: /// - Removal of the Instantiate call from the server's room buffer. /// - Removing RPCs buffered for PhotonViews that got created indirectly with the PhotonNetwork.Instantiate call. /// - Sending a message to other clients to remove the GameObject also (affected by network lag). /// /// Usually, when you leave a room, the GOs get destroyed automatically. /// If you have to destroy a GO while not in a room, the Destroy is only done locally. /// /// Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). /// Objects loaded with a scene are ignored, no matter if they have PhotonView components. /// /// The GameObject must be under this client's control: /// - Instantiated and owned by this client. /// - Instantiated objects of players who left the room are controlled by the Master Client. /// - Scene-owned game objects are controlled by the Master Client. /// - GameObject can be destroyed while client is not in a room. /// </remarks> /// <returns>Nothing. Check error debug log for any issues.</returns> public static void Destroy(PhotonView targetView) { if (targetView != null) { networkingPeer.RemoveInstantiatedGO(targetView.gameObject, !inRoom); } else { Debug.LogError("Destroy(targetPhotonView) failed, cause targetPhotonView is null."); } } /// <summary> /// Network-Destroy the GameObject, unless it is static or not under this client's control. /// </summary> /// <remarks> /// Destroying a networked GameObject includes: /// - Removal of the Instantiate call from the server's room buffer. /// - Removing RPCs buffered for PhotonViews that got created indirectly with the PhotonNetwork.Instantiate call. /// - Sending a message to other clients to remove the GameObject also (affected by network lag). /// /// Usually, when you leave a room, the GOs get destroyed automatically. /// If you have to destroy a GO while not in a room, the Destroy is only done locally. /// /// Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). /// Objects loaded with a scene are ignored, no matter if they have PhotonView components. /// /// The GameObject must be under this client's control: /// - Instantiated and owned by this client. /// - Instantiated objects of players who left the room are controlled by the Master Client. /// - Scene-owned game objects are controlled by the Master Client. /// - GameObject can be destroyed while client is not in a room. /// </remarks> /// <returns>Nothing. Check error debug log for any issues.</returns> public static void Destroy(GameObject targetGo) { networkingPeer.RemoveInstantiatedGO(targetGo, !inRoom); } /// <summary> /// Network-Destroy all GameObjects, PhotonViews and their RPCs of targetPlayer. Can only be called on local player (for "self") or Master Client (for anyone). /// </summary> /// <remarks> /// Destroying a networked GameObject includes: /// - Removal of the Instantiate call from the server's room buffer. /// - Removing RPCs buffered for PhotonViews that got created indirectly with the PhotonNetwork.Instantiate call. /// - Sending a message to other clients to remove the GameObject also (affected by network lag). /// /// Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). /// Objects loaded with a scene are ignored, no matter if they have PhotonView components. /// </remarks> /// <returns>Nothing. Check error debug log for any issues.</returns> public static void DestroyPlayerObjects(PhotonPlayer targetPlayer) { if (player == null) { Debug.LogError("DestroyPlayerObjects() failed, cause parameter 'targetPlayer' was null."); } DestroyPlayerObjects(targetPlayer.ID); } /// <summary> /// Network-Destroy all GameObjects, PhotonViews and their RPCs of this player (by ID). Can only be called on local player (for "self") or Master Client (for anyone). /// </summary> /// <remarks> /// Destroying a networked GameObject includes: /// - Removal of the Instantiate call from the server's room buffer. /// - Removing RPCs buffered for PhotonViews that got created indirectly with the PhotonNetwork.Instantiate call. /// - Sending a message to other clients to remove the GameObject also (affected by network lag). /// /// Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). /// Objects loaded with a scene are ignored, no matter if they have PhotonView components. /// </remarks> /// <returns>Nothing. Check error debug log for any issues.</returns> public static void DestroyPlayerObjects(int targetPlayerId) { if (!VerifyCanUseNetwork()) { return; } if (player.isMasterClient || targetPlayerId == player.ID) { networkingPeer.DestroyPlayerObjects(targetPlayerId, false); } else { Debug.LogError("DestroyPlayerObjects() failed, cause players can only destroy their own GameObjects. A Master Client can destroy anyone's. This is master: " + PhotonNetwork.isMasterClient); } } /// <summary> /// Network-Destroy all GameObjects, PhotonViews and their RPCs in the room. Removes anything buffered from the server. Can only be called by Master Client (for anyone). /// </summary> /// <remarks> /// Can only be called by Master Client (for anyone). /// Unlike the Destroy methods, this will remove anything from the server's room buffer. If your game /// buffers anything beyond Instantiate and RPC calls, that will be cleaned as well from server. /// /// Destroying all includes: /// - Remove anything from the server's room buffer (Instantiate, RPCs, anything buffered). /// - Sending a message to other clients to destroy everything locally, too (affected by network lag). /// /// Destroying networked objects works only if they got created with PhotonNetwork.Instantiate(). /// Objects loaded with a scene are ignored, no matter if they have PhotonView components. /// </remarks> /// <returns>Nothing. Check error debug log for any issues.</returns> public static void DestroyAll() { if (isMasterClient) { networkingPeer.DestroyAll(false); } else { Debug.LogError("Couldn't call DestroyAll() as only the master client is allowed to call this."); } } /// <summary> /// Remove all buffered RPCs from server that were sent by targetPlayer. Can only be called on local player (for "self") or Master Client (for anyone). /// </summary> /// <remarks> /// This method requires either: /// - This is the targetPlayer's client. /// - This client is the Master Client (can remove any PhotonPlayer's RPCs). /// /// If the targetPlayer calls RPCs at the same time that this is called, /// network lag will determine if those get buffered or cleared like the rest. /// </remarks> /// <param name="targetPlayer">This player's buffered RPCs get removed from server buffer.</param> public static void RemoveRPCs(PhotonPlayer targetPlayer) { if (!VerifyCanUseNetwork()) { return; } if (!targetPlayer.isLocal && !isMasterClient) { Debug.LogError("Error; Only the MasterClient can call RemoveRPCs for other players."); return; } networkingPeer.OpCleanRpcBuffer(targetPlayer.ID); } /// <summary> /// Remove all buffered RPCs from server that were sent via targetPhotonView. The Master Client and the owner of the targetPhotonView may call this. /// </summary> /// <remarks> /// This method requires either: /// - The targetPhotonView is owned by this client (Instantiated by it). /// - This client is the Master Client (can remove any PhotonView's RPCs). /// </remarks> /// <param name="targetPhotonView">RPCs buffered for this PhotonView get removed from server buffer.</param> public static void RemoveRPCs(PhotonView targetPhotonView) { if (!VerifyCanUseNetwork()) { return; } networkingPeer.CleanRpcBufferIfMine(targetPhotonView); } /// <summary> /// Remove all buffered RPCs from server that were sent in the targetGroup, if this is the Master Client or if this controls the individual PhotonView. /// </summary> /// <remarks> /// This method requires either: /// - This client is the Master Client (can remove any RPCs per group). /// - Any other client: each PhotonView is checked if it is under this client's control. Only those RPCs are removed. /// </remarks> /// <param name="targetGroup">Interest group that gets all RPCs removed.</param> public static void RemoveRPCsInGroup(int targetGroup) { if (!VerifyCanUseNetwork()) { return; } networkingPeer.RemoveRPCsInGroup(targetGroup); } /// <summary> /// Internal to send an RPC on given PhotonView. Do not call this directly but use: PhotonView.RPC! /// </summary> internal static void RPC(PhotonView view, string methodName, PhotonTargets target, bool encrypt, params object[] parameters) { if (!VerifyCanUseNetwork()) { return; } if (room == null) { Debug.LogWarning("RPCs can only be sent in rooms. Call of \"" + methodName + "\" gets executed locally only, if at all."); return; } if (networkingPeer != null) { if (PhotonNetwork.room.serverSideMasterClient) { networkingPeer.RPC(view, methodName, target, null, encrypt, parameters); } else { if (PhotonNetwork.networkingPeer.hasSwitchedMC && target == PhotonTargets.MasterClient) { networkingPeer.RPC(view, methodName, PhotonTargets.Others, PhotonNetwork.masterClient, encrypt, parameters); } else { networkingPeer.RPC(view, methodName, target, null, encrypt, parameters); } } } else { Debug.LogWarning("Could not execute RPC " + methodName + ". Possible scene loading in progress?"); } } /// <summary> /// Internal to send an RPC on given PhotonView. Do not call this directly but use: PhotonView.RPC! /// </summary> internal static void RPC(PhotonView view, string methodName, PhotonPlayer targetPlayer, bool encrpyt, params object[] parameters) { if (!VerifyCanUseNetwork()) { return; } if (room == null) { Debug.LogWarning("RPCs can only be sent in rooms. Call of \"" + methodName + "\" gets executed locally only, if at all."); return; } if (player == null) { Debug.LogError("RPC can't be sent to target PhotonPlayer being null! Did not send \"" + methodName + "\" call."); } if (networkingPeer != null) { networkingPeer.RPC(view, methodName, PhotonTargets.Others, targetPlayer, encrpyt, parameters); } else { Debug.LogWarning("Could not execute RPC " + methodName + ". Possible scene loading in progress?"); } } /// <summary> /// Populates SendMonoMessageTargets with currently existing GameObjects that have a Component of type. /// </summary> /// <param name="type">If null, this will use SendMonoMessageTargets as component-type (MonoBehaviour by default).</param> public static void CacheSendMonoMessageTargets(Type type) { if (type == null) type = SendMonoMessageTargetType; PhotonNetwork.SendMonoMessageTargets = FindGameObjectsWithComponent(type); } /// <summary>Finds the GameObjects with Components of a specific type (using FindObjectsOfType).</summary> /// <param name="type">Type must be a Component</param> /// <returns>HashSet with GameObjects that have a specific type of Component.</returns> public static HashSet<GameObject> FindGameObjectsWithComponent(Type type) { HashSet<GameObject> objectsWithComponent = new HashSet<GameObject>(); Component[] targetComponents = (Component[]) GameObject.FindObjectsOfType(type); for (int index = 0; index < targetComponents.Length; index++) { objectsWithComponent.Add(targetComponents[index].gameObject); } return objectsWithComponent; } /// <summary> /// Enable/disable receiving on given group (applied to PhotonViews) /// </summary> /// <param name="group">The interest group to affect.</param> /// <param name="enabled">Sets if receiving from group to enabled (or not).</param> public static void SetReceivingEnabled(int group, bool enabled) { if (!VerifyCanUseNetwork()) { return; } networkingPeer.SetReceivingEnabled(group, enabled); } /// <summary> /// Enable/disable receiving on given groups (applied to PhotonViews) /// </summary> /// <param name="enableGroups">The interest groups to enable (or null).</param> /// <param name="disableGroups">The interest groups to disable (or null).</param> public static void SetReceivingEnabled(int[] enableGroups, int[] disableGroups) { if (!VerifyCanUseNetwork()) { return; } networkingPeer.SetReceivingEnabled(enableGroups, disableGroups); } /// <summary> /// Enable/disable sending on given group (applied to PhotonViews) /// </summary> /// <param name="group">The interest group to affect.</param> /// <param name="enabled">Sets if sending to group is enabled (or not).</param> public static void SetSendingEnabled(int group, bool enabled) { if (!VerifyCanUseNetwork()) { return; } networkingPeer.SetSendingEnabled(group, enabled); } /// <summary> /// Enable/disable sending on given groups (applied to PhotonViews) /// </summary> /// <param name="enableGroups">The interest groups to enable sending on (or null).</param> /// <param name="disableGroups">The interest groups to disable sending on (or null).</param> public static void SetSendingEnabled(int[] enableGroups, int[] disableGroups) { if (!VerifyCanUseNetwork()) { return; } networkingPeer.SetSendingEnabled(enableGroups, disableGroups); } /// <summary> /// Sets level prefix for PhotonViews instantiated later on. Don't set it if you need only one! /// </summary> /// <remarks> /// Important: If you don't use multiple level prefixes, simply don't set this value. The /// default value is optimized out of the traffic. /// /// This won't affect existing PhotonViews (they can't be changed yet for existing PhotonViews). /// /// Messages sent with a different level prefix will be received but not executed. This affects /// RPCs, Instantiates and synchronization. /// /// Be aware that PUN never resets this value, you'll have to do so yourself. /// </remarks> /// <param name="prefix">Max value is short.MaxValue = 32767</param> public static void SetLevelPrefix(short prefix) { if (!VerifyCanUseNetwork()) { return; } networkingPeer.SetLevelPrefix(prefix); } /// <summary>Wraps loading a level to pause the network mesage-queue. Optionally syncs the loaded level in a room.</summary> /// <remarks> /// To sync the loaded level in a room, set PhotonNetwork.automaticallySyncScene to true. /// The Master Client of a room will then sync the loaded level with every other player in the room. /// /// While loading levels, it makes sense to not dispatch messages received by other players. /// This method takes care of that by setting PhotonNetwork.isMessageQueueRunning = false and enabling /// the queue when the level was loaded. /// /// You should make sure you don't fire RPCs before you load another scene (which doesn't contain /// the same GameObjects and PhotonViews). You can call this in OnJoinedRoom. /// /// This uses Application.LoadLevel. /// </remarks> /// <param name='levelNumber'> /// Number of the level to load. When using level numbers, make sure they are identical on all clients. /// </param> public static void LoadLevel(int levelNumber) { networkingPeer.SetLevelInPropsIfSynced(levelNumber); PhotonNetwork.isMessageQueueRunning = false; networkingPeer.loadingLevelAndPausedNetwork = true; SceneManager.LoadScene(levelNumber); } /// <summary>Wraps loading a level to pause the network mesage-queue. Optionally syncs the loaded level in a room.</summary> /// <remarks> /// While loading levels, it makes sense to not dispatch messages received by other players. /// This method takes care of that by setting PhotonNetwork.isMessageQueueRunning = false and enabling /// the queue when the level was loaded. /// /// To sync the loaded level in a room, set PhotonNetwork.automaticallySyncScene to true. /// The Master Client of a room will then sync the loaded level with every other player in the room. /// /// You should make sure you don't fire RPCs before you load another scene (which doesn't contain /// the same GameObjects and PhotonViews). You can call this in OnJoinedRoom. /// /// This uses Application.LoadLevel. /// </remarks> /// <param name='levelName'> /// Name of the level to load. Make sure it's available to all clients in the same room. /// </param> public static void LoadLevel(string levelName) { networkingPeer.SetLevelInPropsIfSynced(levelName); PhotonNetwork.isMessageQueueRunning = false; networkingPeer.loadingLevelAndPausedNetwork = true; SceneManager.LoadScene(levelName); } /// <summary> /// This operation makes Photon call your custom web-service by name (path) with the given parameters. /// </summary> /// <remarks> /// This is a server-side feature which must be setup in the Photon Cloud Dashboard prior to use.<br/> /// See the Turnbased Feature Overview for a short intro.<br/> /// http://doc.photonengine.com/en/turnbased/current/getting-started/feature-overview ///<br/> /// The Parameters will be converted into JSon format, so make sure your parameters are compatible. /// /// See PhotonNetworkingMessage.OnWebRpcResponse on how to get a response. /// /// It's important to understand that the OperationResponse only tells if the WebRPC could be called. /// The content of the response contains any values your web-service sent and the error/success code. /// In case the web-service failed, an error code and a debug message are usually inside the /// OperationResponse. /// /// The class WebRpcResponse is a helper-class that extracts the most valuable content from the WebRPC /// response. /// </remarks> /// <example> /// Example callback implementation:<pre> /// /// public void OnWebRpcResponse(OperationResponse response) /// { /// WebRpcResponse webResponse = new WebRpcResponse(operationResponse); /// if (webResponse.ReturnCode != 0) { //... /// } /// /// switch (webResponse.Name) { //... /// } /// // and so on /// }</pre> /// </example> public static bool WebRpc(string name, object parameters) { return networkingPeer.WebRpc(name, parameters); } #if UNITY_EDITOR [Conditional("UNITY_EDITOR")] public static void CreateSettings() { PhotonNetwork.PhotonServerSettings = (ServerSettings)Resources.Load(PhotonNetwork.serverSettingsAssetFile, typeof(ServerSettings)); if (PhotonNetwork.PhotonServerSettings != null) { return; } // find out if ServerSettings can be instantiated (existing script check) ScriptableObject serverSettingTest = ScriptableObject.CreateInstance("ServerSettings"); if (serverSettingTest == null) { Debug.LogError("missing settings script"); return; } UnityEngine.Object.DestroyImmediate(serverSettingTest); // if still not loaded, create one if (PhotonNetwork.PhotonServerSettings == null) { string settingsPath = Path.GetDirectoryName(PhotonNetwork.serverSettingsAssetPath); if (!Directory.Exists(settingsPath)) { Directory.CreateDirectory(settingsPath); AssetDatabase.ImportAsset(settingsPath); } PhotonNetwork.PhotonServerSettings = (ServerSettings)ScriptableObject.CreateInstance("ServerSettings"); if (PhotonNetwork.PhotonServerSettings != null) { AssetDatabase.CreateAsset(PhotonNetwork.PhotonServerSettings, PhotonNetwork.serverSettingsAssetPath); } else { Debug.LogError("PUN failed creating a settings file. ScriptableObject.CreateInstance(\"ServerSettings\") returned null. Will try again later."); } } } /// <summary> /// Internally used by Editor scripts, called on Hierarchy change (includes scene save) to remove surplus hidden PhotonHandlers. /// </summary> public static void InternalCleanPhotonMonoFromSceneIfStuck() { PhotonHandler[] photonHandlers = GameObject.FindObjectsOfType(typeof(PhotonHandler)) as PhotonHandler[]; if (photonHandlers != null && photonHandlers.Length > 0) { Debug.Log("Cleaning up hidden PhotonHandler instances in scene. Please save it. This is not an issue."); foreach (PhotonHandler photonHandler in photonHandlers) { // Debug.Log("Removing Handler: " + photonHandler + " photonHandler.gameObject: " + photonHandler.gameObject); photonHandler.gameObject.hideFlags = 0; if (photonHandler.gameObject != null && photonHandler.gameObject.name == "PhotonMono") { GameObject.DestroyImmediate(photonHandler.gameObject); } Component.DestroyImmediate(photonHandler); } } } #endif }
43.784133
262
0.653793
[ "MIT" ]
skywolf829/Unity-FPS
Assets/Photon Unity Networking/Plugins/PhotonNetwork/PhotonNetwork.cs
142,386
C#
using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; namespace MISD.Cluster.Bright { static class Program { /// <summary> /// Der Haupteinstiegspunkt für die Anwendung. /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); } } }
20.92
55
0.560229
[ "BSD-3-Clause" ]
sebastianzillessen/MISD-OWL
Code/MISDCode/MISD.Cluster.Bright/Program.cs
526
C#
namespace DuelingTraditions { // Represents one of the different types of rooms in the game. public enum RoomType { Normal, Entrance, Fountain, OffTheMap } // Represents a location in the 2D game world, based on its row and column. public record Location(int Row, int Column); // Represents the map and what each room is made out of. public class Map { // Stores which room type each room in the world is. The default is `Normal` because that is the first // member in the enumeration list. private readonly RoomType[,] _rooms; // The total number of rows in this specific game world. public int Rows { get; } // The total number of columns in this specific game world. public int Columns { get; } // Creates a new map with a specific size. public Map(int rows, int columns) { Rows = rows; Columns = columns; _rooms = new RoomType[rows, columns]; } // Returns what type a room at a specific location is. public RoomType GetRoomTypeAtLocation(Location location) => IsOnMap(location) ? _rooms[location.Row, location.Column] : RoomType.OffTheMap; // Determines if a neighboring room is of the given type. public bool HasNeighborWithType(Location location, RoomType roomType) { if (GetRoomTypeAtLocation(new Location(location.Row - 1, location.Column - 1)) == roomType) return true; if (GetRoomTypeAtLocation(new Location(location.Row - 1, location.Column)) == roomType) return true; if (GetRoomTypeAtLocation(new Location(location.Row - 1, location.Column + 1)) == roomType) return true; if (GetRoomTypeAtLocation(new Location(location.Row, location.Column - 1)) == roomType) return true; if (GetRoomTypeAtLocation(new Location(location.Row, location.Column)) == roomType) return true; if (GetRoomTypeAtLocation(new Location(location.Row, location.Column + 1)) == roomType) return true; if (GetRoomTypeAtLocation(new Location(location.Row + 1, location.Column - 1)) == roomType) return true; if (GetRoomTypeAtLocation(new Location(location.Row + 1, location.Column)) == roomType) return true; if (GetRoomTypeAtLocation(new Location(location.Row + 1, location.Column + 1)) == roomType) return true; return false; } // Indicates whether a specific location is actually on the map or not. public bool IsOnMap(Location location) => location.Row >= 0 && location.Row < _rooms.GetLength(0) && location.Column >= 0 && location.Column < _rooms.GetLength(1); // Changes the type of room at a specific spot in the world to a new type. public void SetRoomTypeAtLocation(Location location, RoomType type) => _rooms[location.Row, location.Column] = type; } }
50.118644
147
0.653703
[ "MIT" ]
bofur24/TheCSharpPlayersGuide
Solutions/Level33-ManagingLargerPrograms/DuelingTraditions/Map.cs
2,959
C#
using Microsoft.AspNetCore.Authorization; namespace VotingSystem.Authorization { public class IsVoteOwnerRequirement : IAuthorizationRequirement { } }
18.333333
67
0.781818
[ "MIT" ]
sgalcheung/VotingSystem
src/VotingSystem/Authorization/IsVoteOwnerRequirement.cs
167
C#
// Copyright (c) Microsoft. All rights reserved. // Copyright (c) Denis Kuzmin <x-3F@outlook.com> github/3F // Copyright (c) IeXod contributors https://github.com/3F/IeXod/graphs/contributors // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Concurrent; using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace net.r_eg.IeXod.Shared { /// <summary> /// Class defining extension methods for awaitable objects. /// </summary> internal static class AwaitExtensions { /// <summary> /// Synchronizes access to the staScheduler field. /// </summary> private static Object s_staSchedulerSync = new Object(); /// <summary> /// The singleton STA scheduler object. /// </summary> private static TaskScheduler s_staScheduler; /// <summary> /// Gets the STA scheduler. /// </summary> internal static TaskScheduler OneSTAThreadPerTaskSchedulerInstance { get { if (s_staScheduler == null) { lock (s_staSchedulerSync) { if (s_staScheduler == null) { s_staScheduler = new OneSTAThreadPerTaskScheduler(); } } } return s_staScheduler; } } /// <summary> /// Provides await functionality for ordinary <see cref="WaitHandle"/>s. /// </summary> /// <param name="handle">The handle to wait on.</param> /// <returns>The awaiter.</returns> internal static TaskAwaiter GetAwaiter(this WaitHandle handle) { ErrorUtilities.VerifyThrowArgumentNull(handle, "handle"); return handle.ToTask().GetAwaiter(); } /// <summary> /// Provides await functionality for an array of ordinary <see cref="WaitHandle"/>s. /// </summary> /// <param name="handles">The handles to wait on.</param> /// <returns>The awaiter.</returns> internal static TaskAwaiter<int> GetAwaiter(this WaitHandle[] handles) { ErrorUtilities.VerifyThrowArgumentNull(handles, "handle"); return handles.ToTask().GetAwaiter(); } /// <summary> /// Creates a TPL Task that is marked as completed when a <see cref="WaitHandle"/> is signaled. /// </summary> /// <param name="handle">The handle whose signal triggers the task to be completed. Do not use a <see cref="Mutex"/> here.</param> /// <param name="timeout">The timeout (in milliseconds) after which the task will fault with a <see cref="TimeoutException"/> if the handle is not signaled by that time.</param> /// <returns>A Task that is completed after the handle is signaled.</returns> /// <remarks> /// There is a (brief) time delay between when the handle is signaled and when the task is marked as completed. /// </remarks> internal static Task ToTask(this WaitHandle handle, int timeout = Timeout.Infinite) { return ToTask(new WaitHandle[1] { handle }, timeout); } /// <summary> /// Creates a TPL Task that is marked as completed when any <see cref="WaitHandle"/> in the array is signaled. /// </summary> /// <param name="handles">The handles whose signals triggers the task to be completed. Do not use a <see cref="Mutex"/> here.</param> /// <param name="timeout">The timeout (in milliseconds) after which the task will return a value of WaitTimeout.</param> /// <returns>A Task that is completed after any handle is signaled.</returns> /// <remarks> /// There is a (brief) time delay between when the handles are signaled and when the task is marked as completed. /// </remarks> internal static Task<int> ToTask(this WaitHandle[] handles, int timeout = Timeout.Infinite) { ErrorUtilities.VerifyThrowArgumentNull(handles, "handle"); var tcs = new TaskCompletionSource<int>(); int signalledHandle = WaitHandle.WaitAny(handles, 0); if (signalledHandle != WaitHandle.WaitTimeout) { // An optimization for if the handle is already signaled // to return a completed task. tcs.SetResult(signalledHandle); } else { var localVariableInitLock = new object(); lock (localVariableInitLock) { RegisteredWaitHandle[] callbackHandles = new RegisteredWaitHandle[handles.Length]; for (int i = 0; i < handles.Length; i++) { callbackHandles[i] = ThreadPool.RegisterWaitForSingleObject( handles[i], (state, timedOut) => { int handleIndex = (int)state; if (timedOut) { tcs.TrySetResult(WaitHandle.WaitTimeout); } else { tcs.TrySetResult(handleIndex); } // We take a lock here to make sure the outer method has completed setting the local variable callbackHandles contents. lock (localVariableInitLock) { foreach (var handle in callbackHandles) { handle.Unregister(null); } } }, state: i, millisecondsTimeOutInterval: timeout, executeOnlyOnce: true); } } } return tcs.Task; } /// <summary> /// A class which acts as a task scheduler and ensures each scheduled task gets its /// own STA thread. /// </summary> private class OneSTAThreadPerTaskScheduler : TaskScheduler { /// <summary> /// The current queue of tasks. /// </summary> private ConcurrentQueue<Task> _queuedTasks = new ConcurrentQueue<Task>(); /// <summary> /// Returns the list of queued tasks. /// </summary> protected override System.Collections.Generic.IEnumerable<Task> GetScheduledTasks() { return _queuedTasks; } /// <summary> /// Queues a task to the scheduler. /// </summary> protected override void QueueTask(Task task) { _queuedTasks.Enqueue(task); ParameterizedThreadStart threadStart = new ParameterizedThreadStart((_) => { Task t; if (_queuedTasks.TryDequeue(out t)) { base.TryExecuteTask(t); } }); Thread thread = new Thread(threadStart); #if FEATURE_APARTMENT_STATE thread.SetApartmentState(ApartmentState.STA); #endif thread.Start(task); } /// <summary> /// Tries to execute the task immediately. This method will always return false for the STA scheduler. /// </summary> protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { // We don't get STA threads back here, so just deny the inline execution. return false; } } } }
40.655172
185
0.521992
[ "MIT" ]
3F/IeXod
src/Shared/AwaitExtensions.cs
8,255
C#
using System; using System.Collections.Generic; using Unity.Profiling; using UnityEngine; using UnityEngine.Perception.Randomization.Samplers; namespace UnityEngine.Perception.Randomization.Randomizers.Utilities { /// <summary> /// Facilitates object pooling for a pre-specified collection of prefabs with the caveat that objects can be fetched /// from the cache but not returned. Every frame, the cache needs to be reset, which will return all objects to the pool /// </summary> public class GameObjectOneWayCache { static ProfilerMarker s_ResetAllObjectsMarker = new ProfilerMarker("ResetAllObjects"); GameObject[] m_GameObjects; UniformSampler m_Sampler = new UniformSampler(); Transform m_CacheParent; Dictionary<int, int> m_InstanceIdToIndex; List<CachedObjectData>[] m_InstantiatedObjects; int[] m_NumObjectsActive; int NumObjectsInCache { get; set; } /// <summary> /// The number of active cache objects in the scene /// </summary> public int NumObjectsActive { get; private set; } /// <summary> /// Creates a new GameObjectOneWayCache /// </summary> /// <param name="parent">The parent object all cached instances will be parented under</param> /// <param name="gameObjects">The gameObjects to cache</param> public GameObjectOneWayCache(Transform parent, GameObject[] gameObjects) { if (gameObjects.Length == 0) throw new ArgumentException( "A non-empty array of GameObjects is required to initialize this GameObject cache"); m_GameObjects = gameObjects; m_CacheParent = parent; m_InstanceIdToIndex = new Dictionary<int, int>(); m_InstantiatedObjects = new List<CachedObjectData>[gameObjects.Length]; m_NumObjectsActive = new int[gameObjects.Length]; var index = 0; foreach (var obj in gameObjects) { if (!IsPrefab(obj)) { obj.transform.parent = parent; obj.SetActive(false); } var instanceId = obj.GetInstanceID(); m_InstanceIdToIndex.Add(instanceId, index); m_InstantiatedObjects[index] = new List<CachedObjectData>(); m_NumObjectsActive[index] = 0; ++index; } } /// <summary> /// Retrieves an existing instance of the given gameObject from the cache if available. /// Otherwise, instantiate a new instance of the given gameObject. /// </summary> /// <param name="gameObject"></param> /// <returns></returns> /// <exception cref="ArgumentException"></exception> public GameObject GetOrInstantiate(GameObject gameObject) { if (!m_InstanceIdToIndex.TryGetValue(gameObject.GetInstanceID(), out var index)) throw new ArgumentException($"GameObject {gameObject.name} (ID: {gameObject.GetInstanceID()}) is not in cache."); ++NumObjectsActive; if (m_NumObjectsActive[index] < m_InstantiatedObjects[index].Count) { var nextInCache = m_InstantiatedObjects[index][m_NumObjectsActive[index]]; ++m_NumObjectsActive[index]; foreach (var tag in nextInCache.randomizerTags) tag.Register(); return nextInCache.instance; } ++NumObjectsInCache; var newObject = Object.Instantiate(gameObject, m_CacheParent); newObject.SetActive(true); ++m_NumObjectsActive[index]; m_InstantiatedObjects[index].Add(new CachedObjectData(newObject)); return newObject; } /// <summary> /// Retrieves an existing instance of the given gameObject from the cache if available. /// Otherwise, instantiate a new instance of the given gameObject. /// </summary> /// <param name="index">The index of the gameObject to instantiate</param> /// <returns></returns> /// <exception cref="ArgumentException"></exception> public GameObject GetOrInstantiate(int index) { var gameObject = m_GameObjects[index]; return GetOrInstantiate(gameObject); } /// <summary> /// Retrieves an existing instance of a random gameObject from the cache if available. /// Otherwise, instantiate a new instance of the random gameObject. /// </summary> /// <returns>A random cached GameObject</returns> public GameObject GetOrInstantiateRandomCachedObject() { return GetOrInstantiate(m_GameObjects[(int)(m_Sampler.Sample() * m_GameObjects.Length)]); } /// <summary> /// Return all active cache objects back to an inactive state /// </summary> public void ResetAllObjects() { using (s_ResetAllObjectsMarker.Auto()) { NumObjectsActive = 0; for (var i = 0; i < m_InstantiatedObjects.Length; ++i) { m_NumObjectsActive[i] = 0; foreach (var cachedObjectData in m_InstantiatedObjects[i]) { ResetObjectState(cachedObjectData); } } } } /// <summary> /// Returns the given cache object back to an inactive state /// </summary> /// <param name="gameObject">The object to make inactive</param> /// <exception cref="ArgumentException">Thrown when gameObject is not an active cached object.</exception> public void ResetObject(GameObject gameObject) { for (var i = 0; i < m_InstantiatedObjects.Length; ++i) { var instantiatedObjectList = m_InstantiatedObjects[i]; int indexFound = -1; for (var j = 0; j < instantiatedObjectList.Count && indexFound < 0; j++) { if (instantiatedObjectList[j].instance == gameObject) indexFound = j; } if (indexFound >= 0) { ResetObjectState(instantiatedObjectList[indexFound]); m_NumObjectsActive[i]--; return; } } throw new ArgumentException("Passed GameObject is not an active object in the cache."); } private static void ResetObjectState(CachedObjectData cachedObjectData) { // Position outside the frame cachedObjectData.instance.transform.localPosition = new Vector3(10000, 0, 0); foreach (var tag in cachedObjectData.randomizerTags) tag.Unregister(); } static bool IsPrefab(GameObject obj) { return obj.scene.rootCount == 0; } struct CachedObjectData { public GameObject instance; public RandomizerTag[] randomizerTags; public CachedObjectData(GameObject instance) { this.instance = instance; randomizerTags = instance.GetComponents<RandomizerTag>(); } } } }
39.513228
129
0.581414
[ "Apache-2.0" ]
2dpodcast/com.unity.perception
com.unity.perception/Runtime/Randomization/Randomizers/RandomizerExamples/Utilities/GameObjectOneWayCache.cs
7,470
C#
#region Header // // CmdSlabSides.cs - determine vertical slab 'side' faces // // Copyright (C) 2008-2021 by Jeremy Tammik, // Autodesk Inc. All rights reserved. // // Keywords: The Building Coder Revit API C# .NET add-in. // #endregion // Header #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Selection; #endregion // Namespaces namespace BuildingCoder { [Transaction( TransactionMode.Manual )] class CmdSlabSides : IExternalCommand { /// <summary> /// Determine the vertical boundary faces /// of a given "horizontal" solid object /// such as a floor slab. Currently only /// supports planar and cylindrical faces. /// </summary> /// <param name="verticalFaces">Return solid vertical boundary faces, i.e. 'sides'</param> /// <param name="solid">Input solid</param> void GetSideFaces( List<Face> verticalFaces, Solid solid ) { FaceArray faces = solid.Faces; foreach( Face f in faces ) { if( f is PlanarFace ) { if( Util.IsVertical( f as PlanarFace ) ) { verticalFaces.Add( f ); } } if( f is CylindricalFace ) { if( Util.IsVertical( f as CylindricalFace ) ) { verticalFaces.Add( f ); } } } } public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; List<Element> floors = new List<Element>(); if( !Util.GetSelectedElementsOrAll( floors, uidoc, typeof( Floor ) ) ) { Selection sel = uidoc.Selection; message = ( 0 < sel.GetElementIds().Count ) ? "Please select some floor elements." : "No floor elements found."; return Result.Failed; } List<Face> faces = new List<Face>(); Options opt = app.Application.Create.NewGeometryOptions(); foreach( Floor floor in floors ) { GeometryElement geo = floor.get_Geometry( opt ); //GeometryObjectArray objects = geo.Objects; // 2012 //foreach( GeometryObject obj in objects ) // 2012 foreach( GeometryObject obj in geo ) // 2013 { Solid solid = obj as Solid; if( solid != null ) { GetSideFaces( faces, solid ); } } } int n = faces.Count; Debug.Print( "{0} side face{1} found.", n, Util.PluralSuffix( n ) ); using ( Transaction t = new Transaction( doc ) ) { t.Start( "Draw Face Triangle Normals" ); Creator creator = new Creator( doc ); foreach ( Face f in faces ) { creator.DrawFaceTriangleNormals( f ); } t.Commit(); } return Result.Succeeded; } } }
27.567797
95
0.569321
[ "MIT" ]
SoftBIM/the_building_coder_samples
BuildingCoder/BuildingCoder/CmdSlabSides.cs
3,253
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request the system's calling name retrieval attributes. /// The response is either a SystemCallingNameRetrievalGetResponse24 or an ErrorResponse. /// <see cref="SystemCallingNameRetrievalGetResponse24"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7abfb1e02a3465af832e0a8a8adfc741:46""}]")] public class SystemCallingNameRetrievalGetRequest24 : BroadWorksConnector.Ocip.Models.C.OCIRequest<BroadWorksConnector.Ocip.Models.SystemCallingNameRetrievalGetResponse24> { } }
36.5
175
0.753425
[ "MIT" ]
cwmiller/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemCallingNameRetrievalGetRequest24.cs
876
C#
using System; using System.Collections.Generic; using System.Linq; namespace MessageService.Domain.Model { [Serializable] public abstract class ValueObject : IEquatable<ValueObject> { public abstract IEnumerable<object> GetEqualityComponents(); public bool Equals(ValueObject other) { if (object.ReferenceEquals(this, other)) return true; if (object.ReferenceEquals(null, other)) return false; if (this.GetType() != other.GetType()) return false; var vo = other as ValueObject; return this.GetEqualityComponents().SequenceEqual(vo.GetEqualityComponents()); } public override bool Equals(object obj) { return Equals(obj as ValueObject); } public override int GetHashCode() { unchecked { return this.GetHashCode() * 123; } } } }
26
90
0.591476
[ "Apache-2.0" ]
casertano/DotNetCore.DDD.CQRS.AzureBUS
MessageService.Domain/Model/ObjectValue/ValueObject.cs
964
C#
using MediatR; using System; using System.Collections.Generic; using System.Text; namespace VoipProjectEntities.Application.Features.AgentCustomers.Commands.DeleteAgentCustomer { public class DeleteAgentCustomerCommand : IRequest { public string AgentCustomerID { get; set; } } }
23.230769
94
0.771523
[ "Apache-2.0" ]
Anagha1009/VoIPCustomerWebPortal-1
src/Core/VoipProjectEntities.Application/Features/AgentCustomers/Commands/DeleteAgentCustomer/DeleteAgentCustomerCommand.cs
304
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Stocker.Models { //Enum for AmendedReasonType??? public class StockAmendment { public int StockAmendmentID { get; set; } public int StockID { get; set; } public int UserID { get; set; } public DateTime AmendmentDate { get; set; } public string AmendedReasontype { get; set; } } }
22.35
53
0.655481
[ "MIT" ]
Chazz6000/Stocker
Stocker/Stocker/Models/StockAmendment.cs
449
C#
namespace StudentSystem.ConsoleClient { using System; using Data; using Data.UnitOfWork; using Models; public class Startup { public static void Main() { var db = new StudentSystemDbContext(); var studentData = new StudentSystemData(db); studentData.Courses.Add(new Course() { Name = "DSA" }); studentData.Courses.Add(new Course() { Name = "WebServices" }); studentData.Courses.Add(new Course() { Name = "HQC" }); studentData.Courses.Add(new Course() { Name = "Databases" }); studentData.SaveChanges(); var student1 = new Student() { FirstName = "Ivaylo", LastName = "Kenov", StudentNumber = "SN54353463" }; studentData.Students.Add(student1); studentData.Students.Add(new Student() { FirstName = "Niki", LastName = "Kostov", StudentNumber = "SN654654765" }); studentData.Students.Add(new Student() { FirstName = "Doncho", LastName = "Minkov", StudentNumber = "SN6575465" }); student1.Homeworks.Add(new Homework() { Content = "Homework content" }); studentData.SaveChanges(); Console.WriteLine("Successfully added!"); } } }
34.891892
127
0.58017
[ "MIT" ]
danisio/WebServicesAndCloud-Homeworks
01.ASP.NET Web API/1.StudentSystem/StudentSystem.ConsoleClient/Startup.cs
1,293
C#
/* * Copyright 2015 Google Inc * * Licensed under the Apache License, Version 2.0(the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using Google.Apis.Dfareporting.v2_5; using Google.Apis.Dfareporting.v2_5.Data; namespace DfaReporting.Samples { /// <summary> /// This example displays the name, ID and advertiser ID for every active ad /// your DFA user profile can see. /// </summary> class GetAds : SampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This example displays the name, ID and advertiser ID for" + " every active ad.\n"; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { SampleBase codeExample = new GetAds(); Console.WriteLine(codeExample.Description); codeExample.Run(DfaReportingFactory.getInstance()); } /// <summary> /// Run the code example. /// </summary> /// <param name="service">An initialized Dfa Reporting service object /// </param> public override void Run(DfareportingService service) { long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE")); // Limit the fields returned. String fields = "nextPageToken,ads(advertiserId,id,name)"; AdsListResponse result; String nextPageToken = null; do { // Create and execute the ad list request. AdsResource.ListRequest request = service.Ads.List(profileId); request.Active = true; request.Fields = fields; request.PageToken = nextPageToken; result = request.Execute(); foreach (Ad ad in result.Ads) { Console.WriteLine( "Ad with ID {0} and name \"{1}\" is associated with advertiser" + " ID {2}.", ad.Id, ad.Name, ad.AdvertiserId); } // Update the next page token. nextPageToken = result.NextPageToken; } while (result.Ads.Any() && !String.IsNullOrEmpty(nextPageToken)); } } }
32.780488
79
0.653274
[ "Apache-2.0" ]
byagihas/googleads-dfa-reporting-samples
dotnet/v2.5/Ads/GetAds.cs
2,690
C#
using System; namespace TestApplication.Services { public class WeatherTest : IWeatherTest { public string Do() { return "Ebrahimi"; } } }
14.538462
43
0.555556
[ "MIT" ]
h-ebrahimi/Scrutor
TestApplication/Services/WeatherTest.cs
191
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CodeSharp.ServiceFramework.Interfaces { /// <summary> /// 为服务节点提供相关远程通信处理功能 /// </summary> public interface IRemoteHandle { /// <summary> /// 对当前节点外观进行暴露 /// </summary> /// <param name="uri">暴露地址</param> void Expose(Uri uri); /// <summary> /// 尝试连接到指定服务节点 /// </summary> /// <param name="uri">服务节点地址</param> /// <param name="timeout">超时设置</param> /// <param name="e">返回异常</param> /// <returns></returns> bool TryConnect(Uri uri, int? timeout, out Exception e); /// <summary> /// 向服务节点注册服务 /// </summary> /// <param name="uri">服务节点地址</param> /// <param name="services">服务配置</param> void Register(Uri uri, ServiceConfig[] services); /// <summary> /// 获取服务节点的服务表版本 /// </summary> /// <param name="uri">服务节点地址</param> /// <returns></returns> string GetVersion(Uri uri); /// <summary> /// 获取服务节点中的服务配置表 /// </summary> /// <returns></returns> ServiceConfigTable GetServiceConfigs(Uri uri); /// <summary> /// 获取服务描述 /// </summary> /// <param name="service"></param> /// <returns></returns> string GetServiceDescription(ServiceConfig service); /// <summary> /// 执行服务调用 /// </summary> /// <param name="call"></param> string Invoke(ServiceCall call); /// <summary> /// 向指定服务节点发送异步调用请求 /// </summary> /// <param name="uri"></param> /// <param name="call"></param> void SendAnAsyncCall(Uri uri, ServiceCall call); } }
29.096774
64
0.517184
[ "Apache-2.0" ]
codesharp/infrastructure
dotnet/src/CodeSharp.Core/ServiceFramework/Interfaces/IRpcHandle.cs
2,074
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Monitor.V20180724.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeBasicAlarmListAlarms : AbstractModel { /// <summary> /// Alarm ID. /// </summary> [JsonProperty("Id")] public ulong? Id{ get; set; } /// <summary> /// Project ID. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("ProjectId")] public long? ProjectId{ get; set; } /// <summary> /// Project name. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("ProjectName")] public string ProjectName{ get; set; } /// <summary> /// Alarm status ID. Valid values: 0 (not resolved), 1 (resolved), 2/3/5 (insufficient data), 4 (expired) /// Note: this field may return null, indicating that no valid values can be obtained. /// </summary> [JsonProperty("Status")] public long? Status{ get; set; } /// <summary> /// Alarm status. Valid values: ALARM (not resolved), OK (resolved), NO_DATA (insufficient data), NO_CONF (expired) /// Note: this field may return null, indicating that no valid values can be obtained. /// </summary> [JsonProperty("AlarmStatus")] public string AlarmStatus{ get; set; } /// <summary> /// Policy group ID. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("GroupId")] public long? GroupId{ get; set; } /// <summary> /// Policy group name. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("GroupName")] public string GroupName{ get; set; } /// <summary> /// Occurrence time. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("FirstOccurTime")] public string FirstOccurTime{ get; set; } /// <summary> /// Duration in seconds. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("Duration")] public long? Duration{ get; set; } /// <summary> /// End time. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("LastOccurTime")] public string LastOccurTime{ get; set; } /// <summary> /// Alarm content. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("Content")] public string Content{ get; set; } /// <summary> /// Alarm object. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("ObjName")] public string ObjName{ get; set; } /// <summary> /// Alarm object ID. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("ObjId")] public string ObjId{ get; set; } /// <summary> /// Policy type. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("ViewName")] public string ViewName{ get; set; } /// <summary> /// VPC, which is unique to CVM. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("Vpc")] public string Vpc{ get; set; } /// <summary> /// Metric ID. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("MetricId")] public long? MetricId{ get; set; } /// <summary> /// Metric name. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("MetricName")] public string MetricName{ get; set; } /// <summary> /// Alarm type. The value 0 indicates metric alarms. The value 2 indicates product event alarms. The value 3 indicates platform event alarms. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("AlarmType")] public long? AlarmType{ get; set; } /// <summary> /// Region. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("Region")] public string Region{ get; set; } /// <summary> /// Dimensions of an alarm object. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("Dimensions")] public string Dimensions{ get; set; } /// <summary> /// Notification method. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("NotifyWay")] public string[] NotifyWay{ get; set; } /// <summary> /// Instance group information. /// Note: This field may return null, indicating that no valid value was found. /// </summary> [JsonProperty("InstanceGroup")] public InstanceGroup[] InstanceGroup{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Id", this.Id); this.SetParamSimple(map, prefix + "ProjectId", this.ProjectId); this.SetParamSimple(map, prefix + "ProjectName", this.ProjectName); this.SetParamSimple(map, prefix + "Status", this.Status); this.SetParamSimple(map, prefix + "AlarmStatus", this.AlarmStatus); this.SetParamSimple(map, prefix + "GroupId", this.GroupId); this.SetParamSimple(map, prefix + "GroupName", this.GroupName); this.SetParamSimple(map, prefix + "FirstOccurTime", this.FirstOccurTime); this.SetParamSimple(map, prefix + "Duration", this.Duration); this.SetParamSimple(map, prefix + "LastOccurTime", this.LastOccurTime); this.SetParamSimple(map, prefix + "Content", this.Content); this.SetParamSimple(map, prefix + "ObjName", this.ObjName); this.SetParamSimple(map, prefix + "ObjId", this.ObjId); this.SetParamSimple(map, prefix + "ViewName", this.ViewName); this.SetParamSimple(map, prefix + "Vpc", this.Vpc); this.SetParamSimple(map, prefix + "MetricId", this.MetricId); this.SetParamSimple(map, prefix + "MetricName", this.MetricName); this.SetParamSimple(map, prefix + "AlarmType", this.AlarmType); this.SetParamSimple(map, prefix + "Region", this.Region); this.SetParamSimple(map, prefix + "Dimensions", this.Dimensions); this.SetParamArraySimple(map, prefix + "NotifyWay.", this.NotifyWay); this.SetParamArrayObj(map, prefix + "InstanceGroup.", this.InstanceGroup); } } }
39.188679
149
0.593163
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Monitor/V20180724/Models/DescribeBasicAlarmListAlarms.cs
8,308
C#
using System; namespace PlayWith.Api { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18.3125
69
0.600683
[ "MIT" ]
sangeren/PlayWith
PlayWith.Api/WeatherForecast.cs
293
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Net.Security { internal enum TlsAlertType { Warning = 1, Fatal = 2, } }
24.692308
71
0.685358
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Net.Security/src/System/Net/Security/TlsAlertType.cs
321
C#
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System.Collections.Generic; using System.IO; namespace DMLibTest { public static class CloudBlockBlobExtensions { public static IEnumerable<ListBlockItem> DownloadBlockList(this CloudBlockBlob blob, BlockListingFilter blockListingFilter = BlockListingFilter.Committed, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { return blob.DownloadBlockListAsync(blockListingFilter, accessCondition, options, operationContext).GetAwaiter().GetResult(); } public static void PutBlock(this CloudBlockBlob blob, string blockId, Stream blockData, string contentMD5, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { blob.PutBlockAsync(blockId, blockData, contentMD5, accessCondition, options, operationContext).GetAwaiter().GetResult(); } public static void PutBlockList(this CloudBlockBlob blob, IEnumerable<string> blockList, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { blob.PutBlockListAsync(blockList, accessCondition, options, operationContext).GetAwaiter().GetResult(); } public static void UploadFromByteArray(this CloudBlockBlob blob, byte[] buffer, int index, int count, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { blob.UploadFromByteArrayAsync(buffer, index, count, accessCondition, options, operationContext).GetAwaiter().GetResult(); } public static void UploadFromFile(this CloudBlockBlob blob, string path, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { blob.UploadFromFileAsync(path, accessCondition, options, operationContext).GetAwaiter().GetResult(); } public static void UploadFromStream(this CloudBlockBlob blob, Stream source, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { blob.UploadFromStreamAsync(source, accessCondition, options, operationContext).GetAwaiter().GetResult(); } } }
59.682927
279
0.754802
[ "MIT" ]
derekbekoe/azure-storage-net-data-movement
netcore/DMLibTest/CloudBlockBlobExtensions.cs
2,449
C#
using Lattia; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { public static IServiceCollection AddLattiaExtensions(this IServiceCollection services) { services.AddSingleton<IInitializePropertyTypeNode, ReadOnlyInitializePropertyTypeNode>(); services.AddSingleton<IInitializePropertyTypeNode, WriteOnlyInitializePropertyTypeNode>(); return services; } } }
30.3125
102
0.738144
[ "MIT" ]
iotalambda/Lattia
Lattia.Extensions.DependencyInjection/ServiceCollectionExtensions.cs
487
C#
using System; using System.Collections; using System.Collections.Generic; namespace Collections.Extensions.ToPyString { static class PyStringConverterFactory { internal static IPyStringConverter Create<T>(T source, IEnumerable<object> sourceContainers = default, string prefix = "") { if (PyStringConverterFactory.TryCastToDictionaryEntry(source, out var dictionaryEntry)) { return new DictionaryEntryPyStringConverter(dictionaryEntry, sourceContainers, prefix); } switch (source) { case char ch: return new StringPyStringConverter(ch, sourceContainers, prefix); case string str: return new StringPyStringConverter(str, sourceContainers, prefix); case decimal dec: return new DecimalPyStringConverter(dec, sourceContainers, prefix); case float fl: return new DecimalPyStringConverter(fl, sourceContainers, prefix); case double doub: return new DecimalPyStringConverter(doub, sourceContainers, prefix); case DictionaryEntry dictEntry: return new DictionaryEntryPyStringConverter(dictEntry, sourceContainers, prefix); case IDictionary dictionary: return new DictionaryPyStringConverter(dictionary, sourceContainers, prefix); case Array array when array.Rank > 1: return new MultidimensionalArrayPyStringConverter(array, sourceContainers, prefix); case IEnumerable enumerable: return new EnumerablePyStringConverter(enumerable, sourceContainers, prefix); default: return new ObjectPyStringConverter(source, sourceContainers, prefix); } } private static bool TryCastToDictionaryEntry(object source, out DictionaryEntry dictionaryEntry) { if (source == null) { return false; } var sourceType = source.GetType(); if (sourceType.IsGenericType && sourceType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) { var key = sourceType.GetProperty(nameof(KeyValuePair<object, object>.Key)).GetValue(source, null); var value = sourceType.GetProperty(nameof(KeyValuePair<object, object>.Value)).GetValue(source, null); dictionaryEntry = new DictionaryEntry(key, value); return true; } return false; } } }
42.234375
130
0.606733
[ "MIT" ]
misicnenad/dotnet-collections-extensions-topystring
src/Collections.Extensions.ToPyString/PyStringConverterFactory.cs
2,705
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Services.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
42.308204
167
0.578953
[ "MIT" ]
gabriel2mm/IdeiaNoAr
Services/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs
19,081
C#
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.42000 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace mucomMD2vgm.Properties { using System; /// <summary> /// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。 /// </summary> // このクラスは StronglyTypedResourceBuilder クラスが ResGen // または Visual Studio のようなツールを使用して自動生成されました。 // メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に // ResGen を実行し直すか、または VS プロジェクトをビルドし直します。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("mucomMD2vgm.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// すべてについて、現在のスレッドの CurrentUICulture プロパティをオーバーライドします /// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// .vgm に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string ExtensionVGM { get { return ResourceManager.GetString("ExtensionVGM", resourceCulture); } } /// <summary> /// .vgz に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string ExtensionVGZ { get { return ResourceManager.GetString("ExtensionVGZ", resourceCulture); } } /// <summary> /// .xgm に類似しているローカライズされた文字列を検索します。 /// </summary> internal static string ExtensionXGM { get { return ResourceManager.GetString("ExtensionXGM", resourceCulture); } } /// <summary> /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Bitmap icon1 { get { object obj = ResourceManager.GetObject("icon1", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Bitmap icon2 { get { object obj = ResourceManager.GetObject("icon2", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Bitmap icon3 { get { object obj = ResourceManager.GetObject("icon3", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Bitmap icon4 { get { object obj = ResourceManager.GetObject("icon4", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Bitmap icon5 { get { object obj = ResourceManager.GetObject("icon5", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Bitmap icon6 { get { object obj = ResourceManager.GetObject("icon6", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// (アイコン) に類似した型 System.Drawing.Icon のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Icon mm2v48 { get { object obj = ResourceManager.GetObject("mm2v48", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// <summary> /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 /// </summary> internal static System.Drawing.Bitmap mm2v481 { get { object obj = ResourceManager.GetObject("mm2v481", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
36.304094
177
0.550419
[ "MIT" ]
kuma4649/mucomMD2vgm
mucomMD2vgm/Properties/Resources.Designer.cs
7,366
C#
using System; using System.Windows.Input; using System.Runtime.CompilerServices; using Xamarin.Forms; namespace XFArchitecture.Controls { public class CheckBox : Image, IDisposable { #region Bindable Properties public static readonly BindableProperty CheckedProperty = BindableProperty.Create(nameof(Checked), typeof(bool), typeof(CheckBox), false, BindingMode.TwoWay, propertyChanged: OnCheckedPropertyChanged); public bool Checked { get { return (bool)GetValue(CheckedProperty); } set { SetValue(CheckedProperty, value); } } public static readonly BindableProperty UnCheckedImageProperty = BindableProperty.Create(nameof(UnCheckedImage), typeof(string), typeof(CheckBox), "ic_checkbox_unchecked"); public string UnCheckedImage { get { return (string)GetValue(UnCheckedImageProperty); } set { SetValue(UnCheckedImageProperty, value); } } public static readonly BindableProperty CheckedImageProperty = BindableProperty.Create(nameof(CheckedImage), typeof(string), typeof(CheckBox), "ic_checkbox_checked"); public string CheckedImage { get { return (string)GetValue(CheckedImageProperty); } set { SetValue(CheckedImageProperty, value); } } public static readonly BindableProperty CheckedCommandProperty = BindableProperty.Create(nameof(CheckedCommand), typeof(ICommand), typeof(CheckBox), null); public ICommand CheckedCommand { get { return (ICommand)GetValue(CheckedCommandProperty); } set { SetValue(CheckedCommandProperty, value); } } #endregion private TapGestureRecognizer imageTapGesture; public event EventHandler<bool> CheckedChanged; public CheckBox() { InitElements(); SetProperties(); AddEventHandlers(); } private void InitElements() { imageTapGesture = new TapGestureRecognizer(); } private void SetProperties() { Aspect = Aspect.AspectFit; BackgroundColor = Color.Transparent; Source = Checked ? CheckedImage : UnCheckedImage; } private void AddEventHandlers() { imageTapGesture.Tapped += ImageTapGesture_OnTapped; GestureRecognizers.Add(imageTapGesture); } private void RemoveEventHandlers() { imageTapGesture.Tapped -= ImageTapGesture_OnTapped; GestureRecognizers.Remove(imageTapGesture); } private void ImageTapGesture_OnTapped(object sender, EventArgs eventArgs) { if (IsEnabled) Checked = !Checked; CheckedCommand?.Execute(Checked); CheckedChanged?.Invoke(this, Checked); } private static void OnCheckedPropertyChanged(BindableObject bindable, object oldValue, object newValue) { (bindable as CheckBox).OnCheckedChanged((bool)newValue); } public void OnCheckedChanged(bool newValue) { Checked = newValue; Source = newValue ? CheckedImage : UnCheckedImage; } protected override void OnPropertyChanged([CallerMemberName] string propertyName = null) { base.OnPropertyChanged(propertyName); if (propertyName.Equals(CheckedProperty.PropertyName) || propertyName.Equals(CheckedImageProperty.PropertyName) || propertyName.Equals(UnCheckedImageProperty.PropertyName)) Source = Checked ? CheckedImage : UnCheckedImage; } public void Dispose() { RemoveEventHandlers(); } } }
35.660377
209
0.643386
[ "MIT" ]
JosueDM94/XFArchitecture
XFArchitecture/Controls/CheckBox.cs
3,782
C#
namespace MassTransit.KafkaIntegration.Contexts { using System; using Confluent.Kafka; public class KafkaHeaderAdapter<TKey, TValue> : MessageContext { readonly ReceiveContext _receiveContext; readonly ConsumeResult<TKey, TValue> _result; Guid? _conversationId; Guid? _correlationId; Guid? _initiatorId; Guid? _messageId; DateTime? _sentTime; Uri _sourceAddress; public KafkaHeaderAdapter(ConsumeResult<TKey, TValue> result, ReceiveContext receiveContext) { _result = result; _receiveContext = receiveContext; } public Guid? MessageId => _messageId ??= Headers.Get<Guid>(nameof(MessageId)); public Guid? RequestId { get; } = default; public Guid? CorrelationId => _correlationId ??= Headers.Get<Guid>(nameof(CorrelationId)); public Guid? ConversationId => _conversationId ??= Headers.Get<Guid>(nameof(ConversationId)); public Guid? InitiatorId => _initiatorId ??= Headers.Get<Guid>(nameof(InitiatorId)); public DateTime? ExpirationTime { get; } = default; public Uri SourceAddress => _sourceAddress ??= GetEndpointAddress(nameof(SourceAddress)); public Uri DestinationAddress => _receiveContext.InputAddress; public Uri ResponseAddress { get; } = default; public Uri FaultAddress { get; } = default; public DateTime? SentTime => _sentTime ??= _result.Message.Timestamp.UtcDateTime; public MassTransit.Headers Headers => _receiveContext.TransportHeaders; public HostInfo Host => default; Uri GetEndpointAddress(string key) { var endpoint = Headers.Get<string>(key); return string.IsNullOrWhiteSpace(endpoint) ? default : new Uri(endpoint); } } }
39.041667
101
0.651547
[ "ECL-2.0", "Apache-2.0" ]
Aerodynamite/MassTrans
src/Transports/MassTransit.KafkaIntegration/Contexts/KafkaHeaderAdapter.cs
1,874
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AlipayOpenMiniUserportraitQueryModel Data Structure. /// </summary> [Serializable] public class AlipayOpenMiniUserportraitQueryModel : AopObject { /// <summary> /// 用户画像的时间范围。RECENT_7_DAY代表近7日,RECENT_30_DAY代表近30日 /// </summary> [XmlElement("date_scope")] public string DateScope { get; set; } /// <summary> /// 画像类型。AGE-年龄,PROVINCE-省份,CITY-城市,DEVICE-设备,GENDER-性别 /// </summary> [XmlElement("portrait_type")] public string PortraitType { get; set; } /// <summary> /// 用户类型。NEW_USER新用户,ACTIVE_USER活跃用户 /// </summary> [XmlElement("user_type")] public string UserType { get; set; } } }
26.580645
65
0.598301
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Domain/AlipayOpenMiniUserportraitQueryModel.cs
926
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. /***************************************************************************\ * * File: WrapperUtil.cs * * Wrapper utilities * * \***************************************************************************/ using System; using System.Globalization; using System.Security; using System.Security.Permissions; using System.Reflection; // namespace Microsoft.Test.Serialization { /// <summary> /// Class containing utility methods to load assemblies. /// </summary> internal static class WrapperUtil { /// <summary> /// Reference to framework assembly. /// </summary> public static Assembly AssemblyPF = LoadAssemblyPF(); /// <summary> /// Reference to core assembly. /// </summary> public static Assembly AssemblyPC = LoadAssemblyPC(); /// <summary> /// Reference to base assembly. /// </summary> public static Assembly AssemblyWB = LoadAssemblyWB(); /// <summary> /// Default flags to reflect into methods. /// </summary> public static BindingFlags MethodBindFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod; /// <summary> /// Default flags to reflect into properties. /// </summary> public static BindingFlags PropertyBindFlags = BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetProperty; private const string PRESENTATIONCOREASSEMBLYNAME = @"PresentationCore"; private const string PRESENTATIONFRAMEWORKASSEMBLYNAME = @"PresentationFramework"; private const string WINDOWSBASEASSEMBLYNAME = @"WindowsBase"; private const string DOTNETCULTURE = @"en-us"; private static Assembly LoadAssemblyPF() { Assembly assm = FindAssemblyInDomain(PRESENTATIONFRAMEWORKASSEMBLYNAME); if (assm == null) { // A quick way to load the compatible version of "PresentationFramework" Type parserType = typeof(System.Windows.Markup.XamlReader); assm = parserType.Assembly; } return assm; } private static Assembly LoadAssemblyPC() { Assembly assm = FindAssemblyInDomain(PRESENTATIONCOREASSEMBLYNAME); if (assm == null) { // A quick way to load the compatible version of "PresentationCore" Type parserType = typeof(System.Windows.UIElement); assm = parserType.Assembly; } return assm; } private static Assembly LoadAssemblyWB() { Assembly assm = FindAssemblyInDomain(WINDOWSBASEASSEMBLYNAME); if (assm == null) { // A quick way to load the compatible version of "WindowsBase" Type dispatcherType = typeof(System.Windows.Threading.Dispatcher); assm = dispatcherType.Assembly; } return assm; } // Loads the Assembly with the specified name. internal static Assembly FindAssemblyInDomain(string assemblyName) { Assembly returnAssembly = null; // //for (int i = 0; i < assemblies.Length; i++) //{ // AssemblySW assembly = assemblies[i]; // if (String.Compare(assembly.FullName, assemblyName, false, CultureInfo.GetCultureInfo(DOTNETCULTURE)) == 0 || // String.Compare(assembly.GetName().Name, assemblyName, false, CultureInfo.GetCultureInfo(DOTNETCULTURE)) == 0) // { // returnAssembly = assembly.InnerObject; // break; // } //} return returnAssembly; } } }
30.783582
178
0.577212
[ "MIT" ]
batzen/wpf-test
src/Test/Common/Code/Microsoft/Test/Serialization/WrapperUtil.cs
4,125
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request a list of departments in an enterprise. You may request only the /// list of departments defined at the enterprise-level, or you may request /// the list of all departments in the enterprise including all the departments /// defined within the groups inside the enterprise. /// The response is either EnterpriseDepartmentGetListResponse or ErrorResponse. /// <see cref="EnterpriseDepartmentGetListResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""5395c7df0157d44aa22f3351d1a5f3da:707""}]")] public class EnterpriseDepartmentGetListRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _enterpriseId; [XmlElement(ElementName = "enterpriseId", IsNullable = false, Namespace = "")] [Group(@"5395c7df0157d44aa22f3351d1a5f3da:707")] [MinLength(1)] [MaxLength(30)] public string EnterpriseId { get => _enterpriseId; set { EnterpriseIdSpecified = true; _enterpriseId = value; } } [XmlIgnore] protected bool EnterpriseIdSpecified { get; set; } private bool _includeGroupDepartments; [XmlElement(ElementName = "includeGroupDepartments", IsNullable = false, Namespace = "")] [Group(@"5395c7df0157d44aa22f3351d1a5f3da:707")] public bool IncludeGroupDepartments { get => _includeGroupDepartments; set { IncludeGroupDepartmentsSpecified = true; _includeGroupDepartments = value; } } [XmlIgnore] protected bool IncludeGroupDepartmentsSpecified { get; set; } } }
33.47619
129
0.646752
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/EnterpriseDepartmentGetListRequest.cs
2,109
C#
using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Scorpio.Data; using Scorpio.Entities; namespace Scorpio.EntityFrameworkCore { internal class TestDbContext : ScorpioDbContext<TestDbContext> { public TestDbContext(DbContextOptions<TestDbContext> contextOptions) : base(contextOptions) { } public DbSet<TestTable> TestTables { get; set; } public DbSet<TestTableDetail> TableDetails { get; set; } public DbSet<SimpleTable> SimpleTables { get; set; } } public class TestTable : Entity<int>, ISoftDelete, IHasExtraProperties, IStringValue { public TestTable() => Details = new HashSet<TestTableDetail>(); public string StringValue { get; set; } public bool IsDeleted { get; set; } public ExtraPropertyDictionary ExtraProperties { get; set; } public virtual ICollection<TestTableDetail> Details { get; set; } } public class TestTableDetail : Entity<int> { public string DetailValue { get; set; } public virtual TestTable TestTable { get; set; } } public class SimpleTable : Entity<int> { public string StringValue { get; set; } } }
26.673913
99
0.670742
[ "MIT" ]
project-scorpio/Scorpio
src/EntityFrameworkCore/test/Scorpio.EntityFrameworkCore.Tests/Scorpio/EntityFrameworkCore/TestDbContext.cs
1,229
C#
using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace MediaCreationLib.Planning.NET { public class EditionMappingXML { [XmlRoot(ElementName = "Edition")] public class Edition { [XmlElement(ElementName = "Name")] public string Name { get; set; } [XmlElement(ElementName = "ParentEdition")] public string ParentEdition { get; set; } [XmlAttribute(AttributeName = "virtual")] public string Virtual { get; set; } } [XmlRoot(ElementName = "WindowsEditions")] public class WindowsEditions { [XmlElement(ElementName = "Edition")] public List<Edition> Edition { get; set; } [XmlAttribute(AttributeName = "e", Namespace = "http://www.w3.org/2000/xmlns/")] public string E { get; set; } } public static WindowsEditions Deserialize(string editionMappingXml) { if (editionMappingXml == null) return null; var xmlSerializer = new XmlSerializer(typeof(WindowsEditions)); using (var stringReader = new StringReader(editionMappingXml)) { return (WindowsEditions)xmlSerializer.Deserialize(stringReader); } } } }
30.409091
92
0.592676
[ "MIT" ]
ADeltaX/UUPMediaCreator
src/MediaCreationLib.Planning.NET/EditionMappingXML.cs
1,340
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("03. A Miner Task")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03. A Miner Task")] [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("317f03eb-dc44-4cbc-839b-686c0b8f93b2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.972973
84
0.740925
[ "MIT" ]
Shtereva/Fundamentals-with-CSharp
Lambda and LINQ/03. A Miner Task/Properties/AssemblyInfo.cs
1,408
C#
using BeetleX; using BeetleX.Buffers; using SpanJson; using System; using System.Collections.Generic; using System.Text; namespace PlatformBenchmarks { public partial class HttpHandler { public async void db(PipeStream stream, HttpToken token, ISession session) { try { var data = await token.Db.LoadSingleQueryRow(); await JsonSerializer.NonGeneric.Utf8.SerializeAsync(data, stream); } catch(Exception e_) { HttpServer.ApiServer.Log(BeetleX.EventArgs.LogType.Error, null, $"db error {e_.Message}@{e_.StackTrace}"); stream.Write(e_.Message); } OnCompleted(stream, session, token); } } }
26.689655
122
0.595607
[ "BSD-3-Clause" ]
Adel/FrameworkBenchmarks
frameworks/CSharp/beetlex/PlatformBenchmarks/db.cs
776
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Windows; using Bindables.Fody; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using Mono.Cecil; using NUnit.Framework; // ReSharper disable PossibleNullReferenceException namespace Bindables.Test { public class Weaver { public static Assembly Weave(string code) { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code); string[] assemblyPaths = { typeof(Exception).Assembly.Location, typeof(DependencyObject).Assembly.Location, typeof(DependencyPropertyAttribute).Assembly.Location, typeof(FrameworkPropertyMetadataOptions).Assembly.Location, typeof(Console).GetTypeInfo().Assembly.Location, Path.Combine(Path.GetDirectoryName(typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly.Location), "System.Runtime.dll") }; PortableExecutableReference[] references = assemblyPaths.Select(x => MetadataReference.CreateFromFile(x)).ToArray(); CSharpCompilation compilation = CSharpCompilation.Create( Guid.NewGuid() + ".dll", new[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (MemoryStream stream = new MemoryStream()) { EmitResult result = compilation.Emit(stream); if (!result.Success) { Console.Error.WriteLine("Compilation failed!"); IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { Console.Error.WriteLine("\t{0}: {1}", diagnostic.Id, diagnostic.GetMessage()); } Assert.That(result.Success); } stream.Seek(0, SeekOrigin.Begin); using (MemoryStream conversionStream = new MemoryStream()) using (ModuleDefinition module = ModuleDefinition.ReadModule(stream, new ReaderParameters { InMemory = true })) { ModuleWeaver weavingTask = new ModuleWeaver { ModuleDefinition = module }; weavingTask.Execute(); module.Write(conversionStream); conversionStream.Seek(0, SeekOrigin.Begin); using (FileStream fileStream = File.Create($"{Guid.NewGuid()}.dll")) { conversionStream.CopyToAsync(fileStream); conversionStream.Seek(0, SeekOrigin.Begin); } return Assembly.Load(conversionStream.ToArray()); } } } } }
28.693182
128
0.726337
[ "MIT" ]
notanaverageman/Bindables
Bindables.Test/Weaver.cs
2,525
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Configuration; using System.IO; using System.Xml; using SemWeb; using SemWeb.Query; using Search.Common; namespace Search { // NOTE: If you change the class name "ProfilesSPARQLAPI" here, you must also update the reference to "ProfilesSPARQLAPI" in Web.config. public class ProfilesSPARQLAPI : IProfilesSPARQLAPI { public object Search(queryrequest xml) { SemWeb.Query.Query query = null; string q = string.Empty; try { query = new SparqlEngine(new StringReader(xml.query)); } catch (QueryFormatException ex) { var malformed = new malformedquery(); malformed.faultdetails = ex.Message; return malformed; } // Load the data from sql server SemWeb.Stores.SQLStore store; string connstr = ConfigurationManager.ConnectionStrings["SemWebDB"].ConnectionString; DebugLogging.Log(connstr); store = (SemWeb.Stores.SQLStore)SemWeb.Store.CreateForInput(connstr); //Create a Sink for the results to be writen once the query is run. MemoryStream ms = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8); QueryResultSink sink = new SparqlXmlQuerySink(writer); try { // Run the query. query.Run(store, sink); } catch (Exception ex) { // Run the query. query.Run(store, sink); DebugLogging.Log("Run the query a second time"); DebugLogging.Log(ex.Message); } //flush the writer then load the memory stream writer.Flush(); ms.Seek(0, SeekOrigin.Begin); //Write the memory stream out to the response. ASCIIEncoding ascii = new ASCIIEncoding(); DebugLogging.Log(ascii.GetString(ms.ToArray()).Replace("???", "")); writer.Close(); DebugLogging.Log("End of Processing"); return SerializeXML.DeserializeObject(ascii.GetString(ms.ToArray()).Replace("???", ""), typeof(sparql)) as sparql; } } }
29.86747
149
0.582493
[ "BSD-3-Clause" ]
HSSC/ProfilesRNS
Website/SourceCode/ProfilesSPARQLAPI/ProfilesSPARQLAPI.svc.cs
2,481
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 29.03.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int16.Double{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Int16; using T_DATA2 =System.Double; //////////////////////////////////////////////////////////////////////////////// //class TestSet_R504AAB004__param public static class TestSet_R504AAB004__param { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { string vv1="1"; string vv2="12"; var recs=db.testTable.Where(r => (string)(object)(((T_DATA1)vv1.Length)*((T_DATA1)vv1.Length)*((T_DATA2)vv2.Length))=="2.000000000000000"); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { string vv1="1"; string vv2="12"; var recs=db.testTable.Where(r => (string)(object)((((T_DATA1)vv1.Length)*((T_DATA1)vv1.Length))*((T_DATA2)vv2.Length))=="2.000000000000000"); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 //----------------------------------------------------------------------- [Test] public static void Test_003() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { string vv1="1"; string vv2="12"; var recs=db.testTable.Where(r => (string)(object)(((T_DATA1)vv1.Length)*(((T_DATA1)vv1.Length)*((T_DATA2)vv2.Length)))=="2.000000000000000"); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_003 };//class TestSet_R504AAB004__param //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int16.Double
24.300971
146
0.526568
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_002__AS_STR/Multiply/Complete/Int16/Double/TestSet_R504AAB004__param.cs
5,008
C#
namespace BookShop.DataProcessor { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; using BookShop.Data.Models; using BookShop.Data.Models.Enums; using BookShop.DataProcessor.ImportDto; using Data; using Newtonsoft.Json; using ValidationContext = System.ComponentModel.DataAnnotations.ValidationContext; public class Deserializer { private const string ErrorMessage = "Invalid data!"; private const string SuccessfullyImportedBook = "Successfully imported book {0} for {1:F2}."; private const string SuccessfullyImportedAuthor = "Successfully imported author - {0} with {1} books."; public static string ImportBooks(BookShopContext context, string xmlString) { StringBuilder sb = new StringBuilder(); StringReader reader = new StringReader(xmlString); XmlRootAttribute xmlRoot = new XmlRootAttribute("Books"); XmlSerializer xmlSerializer = new XmlSerializer(typeof(ImportBookDto[]), xmlRoot); ImportBookDto[] dtoBooks = (ImportBookDto[])xmlSerializer.Deserialize(reader); HashSet<Book> validBooks = new HashSet<Book>(); foreach (ImportBookDto dtoBook in dtoBooks) { if (!IsValid(dtoBook)) { sb.AppendLine(ErrorMessage); continue; } DateTime parsedPublishedOn = DateTime.ParseExact(dtoBook.PublishedOn, "MM/dd/yyyy", CultureInfo.InvariantCulture); Book book = new Book() { Name = dtoBook.Name, Genre = (Genre)dtoBook.Genre, Price = dtoBook.Price, Pages = dtoBook.Pages, PublishedOn = parsedPublishedOn, }; validBooks.Add(book); sb.AppendLine(string.Format(SuccessfullyImportedBook, book.Name, book.Price)); } context.Books.AddRange(validBooks); context.SaveChanges(); return sb.ToString().TrimEnd(); } public static string ImportAuthors(BookShopContext context, string jsonString) { StringBuilder sb = new StringBuilder(); ICollection<ImportAuthorDto> dtoAuthors = JsonConvert.DeserializeObject<ICollection<ImportAuthorDto>>(jsonString); HashSet<Author> validAuthors = new HashSet<Author>(); foreach (ImportAuthorDto dtoAuthor in dtoAuthors) { if (!IsValid(dtoAuthor)) { sb.AppendLine(ErrorMessage); continue; } if (validAuthors.Any(x => x.Email == dtoAuthor.Email)) { sb.AppendLine(ErrorMessage); continue; } Author author = new Author() { FirstName = dtoAuthor.FirstName, LastName = dtoAuthor.LastName, Phone = dtoAuthor.Phone, Email = dtoAuthor.Email, }; HashSet<AuthorBook> authorBooks = new HashSet<AuthorBook>(); foreach (ImportAuthorBooksDto dtoBook in dtoAuthor.Books) { Book book = context.Books.Find(dtoBook.Id); if (book == null) { continue; } AuthorBook authorBook = new AuthorBook() { Author = author, Book = book }; authorBooks.Add(authorBook); } if (authorBooks.Count == 0) { sb.AppendLine(ErrorMessage); continue; } author.AuthorsBooks = authorBooks; validAuthors.Add(author); sb.AppendLine(string.Format(SuccessfullyImportedAuthor, $"{author.FirstName} {author.LastName}", authorBooks.Count)); } context.Authors.AddRange(validAuthors); context.SaveChanges(); return sb.ToString().TrimEnd(); } private static bool IsValid(object dto) { var validationContext = new ValidationContext(dto); var validationResult = new List<ValidationResult>(); return Validator.TryValidateObject(dto, validationContext, validationResult, true); } } }
33.232877
133
0.538541
[ "MIT" ]
SuperBianka/SoftUni-CSharp-Track
CSharp Entity Framework Core/CSharpEFCore - Exam - 13December2019/BookShop/DataProcessor/Deserializer.cs
4,854
C#
using TMPro; using UnityEngine; public class UpdateCustomersServed : MonoBehaviour { private TextMeshProUGUI _text; void Start() { _text = GetComponent<TextMeshProUGUI>(); } void Update() { _text.text = GameState.Current.NumCustomersServed.ToString(); } }
17.111111
69
0.649351
[ "MIT" ]
EnigmaDragons/CV-Hackathon-2019
src/CVHackathon2019/Assets/Scripts/UI/UpdateCustomersServed.cs
310
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.CCC.Transform; using Aliyun.Acs.CCC.Transform.V20200701; namespace Aliyun.Acs.CCC.Model.V20200701 { public class ListSkillGroupsRequest : RpcAcsRequest<ListSkillGroupsResponse> { public ListSkillGroupsRequest() : base("CCC", "2020-07-01", "ListSkillGroups", "CCC", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.CCC.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.CCC.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private int? pageNumber; private string searchPattern; private string instanceId; private int? pageSize; public int? PageNumber { get { return pageNumber; } set { pageNumber = value; DictionaryUtil.Add(QueryParameters, "PageNumber", value.ToString()); } } public string SearchPattern { get { return searchPattern; } set { searchPattern = value; DictionaryUtil.Add(QueryParameters, "SearchPattern", value); } } public string InstanceId { get { return instanceId; } set { instanceId = value; DictionaryUtil.Add(QueryParameters, "InstanceId", value); } } public int? PageSize { get { return pageSize; } set { pageSize = value; DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString()); } } public override bool CheckShowJsonItemName() { return false; } public override ListSkillGroupsResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ListSkillGroupsResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
26.017544
134
0.669252
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-ccc/CCC/Model/V20200701/ListSkillGroupsRequest.cs
2,966
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace P1_DaytonSchuh.Models { public class Location { [Key] public int Id { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } } }
23.105263
44
0.644647
[ "MIT" ]
12142020-dotnet-uta/DaytonSchuhRepo1
Projects/P1_DaytonSchuh/ModelLayer/Models/Location.cs
441
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class IkControl : MonoBehaviour { protected Animator animator; public bool ikActive = false; public Transform TagetTr; public Transform lookObj = null; private Vector3 maxsize = new Vector3(0f, 5f, 0f); public float startSize; public float stopSize; private void Start() { animator = GetComponent<Animator>(); } public bool FlowerIKSet(float scale) { if (scale > startSize && ikActive == false) { TagetTr.localPosition += Vector3.Lerp(TagetTr.localPosition, maxsize, Time.deltaTime * 15f) /*new Vector3(1f, 0f, 0f)*/; if (scale > stopSize) { ikActive = true; } return true; } return false; } private void OnAnimatorIK(/*int layerIndex*/) { if (animator) { // IK가 활성화 된 경우 위치 및 회전을 목표에 직접 설정합니다. if (ikActive) { // 보이는 목표 위치가 지정되면 설정합니다. if (lookObj != null) { animator.SetLookAtWeight(1); animator.SetLookAtPosition(lookObj.position); } // 오른쪽 목표 위치와 회전이 설정되어 있으면이를 설정합니다. if (TagetTr != null) { animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1); animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1); animator.SetIKPosition(AvatarIKGoal.RightHand, TagetTr.position); animator.SetIKRotation(AvatarIKGoal.RightHand, TagetTr.rotation); } } else { animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 0); animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 0); animator.SetLookAtWeight(0); } } } }
28.342857
132
0.536794
[ "MIT" ]
Kingminje/AR_Plant-Growth-ARKit-
IkControl.cs
2,116
C#
using Windows.UI.Xaml.Controls; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace Famoser.OfflineMedia.WinUniversal.UserControls.ArticlePageControls { public sealed partial class Read : UserControl { public Read() { this.InitializeComponent(); } } }
23.866667
96
0.684358
[ "MIT" ]
famoser/OfflineMedia
Famoser.OfflineMedia.WinUniversal/UserControls/ArticlePageControls/Read.xaml.cs
360
C#
 // Author: Alejandro Benítez López // Date: 01/03/2019 // benitezdev@gmail.com using UnityEngine; [RequireComponent(typeof(CharacterController))] public class MovementController : MonoBehaviour { CharacterController controller; [Header("Playe Speeds")] [SerializeField] float playerRotationSpeed = 100; [SerializeField] float playerMovementSpeed = 10; [Space(5)] [SerializeField] float gravity; // Absolute value of Gravity float velocityY; // Velocity of the character in Y [SerializeField] float jumpStrength; [Space(5)] [SerializeField] float debugRayLenght = 5; // Lenght of debug ray private void Awake() { controller = GetComponent<CharacterController>(); } private void Update() { // Get the resultant direction Vector3 direction = transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal"); #region Debugs DrawRay // Draw foreward ray Debug.DrawRay(transform.position, transform.forward * debugRayLenght * Input.GetAxis("Vertical"), Color.blue); // Draw right/left ray Debug.DrawRay(transform.position, transform.right * debugRayLenght * Input.GetAxis("Horizontal"), Color.red); // Draw resultant direction Debug.DrawRay(transform.position, direction * debugRayLenght, Color.cyan); #endregion #region Calculate rotation // Filter if it is moving in any axis if (direction != Vector3.zero && direction.normalized != -transform.forward) { // Calculate the rotation according to the direction Quaternion rotation = Quaternion.LookRotation(direction); // Rotate the character progressively transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, Time.deltaTime * playerRotationSpeed); } #endregion // This Vector3 contain the direction foreward or backwards of the character(0,0,Z) Vector3 directorVector = Input.GetAxis("Vertical") * transform.forward * playerMovementSpeed; // Vector3 that represent the force in Y of the character (used for gravity and jump) Vector3 axisY = new Vector3(0, velocityY, 0); // Character Jump if (Input.GetButtonDown("Jump") && controller.isGrounded) velocityY = jumpStrength; // Character is in air if (!controller.isGrounded) velocityY -= gravity * Time.deltaTime; // Resultant vector of the direction and Y axis directorVector += axisY; // Apply the movement to the character controller.Move(directorVector * Time.deltaTime); // Draw the movement direction Debug.DrawRay(transform.position, directorVector * debugRayLenght, Color.magenta); } }
35.940476
127
0.631997
[ "MIT" ]
BenitezDev/CharacterController-for-Unity
MovementController.cs
3,023
C#
using System; using System.Collections.Generic; using System.Linq; namespace ClosedXML.Excel { internal class XLNamedRange : IXLNamedRange { private String _name; private readonly XLNamedRanges _namedRanges; public XLNamedRange(XLNamedRanges namedRanges, String rangeName, String range, String comment = null) { _namedRanges = namedRanges; Visible = true; Name = rangeName; RangeList.Add(range); Comment = comment; } public XLNamedRange(XLNamedRanges namedRanges, String rangeName, IXLRanges ranges, String comment = null) { _namedRanges = namedRanges; Visible = true; Name = rangeName; ranges.ForEach(r => RangeList.Add(r.RangeAddress.ToStringFixed(XLReferenceStyle.A1, true))); Comment = comment; } public String Name { get { return _name; } set { if (_name == value) return; var oldname = _name ?? string.Empty; var existingNames = _namedRanges.Select(nr => nr.Name).ToList(); if (_namedRanges.Scope == XLNamedRangeScope.Workbook) existingNames.AddRange(_namedRanges.Workbook.NamedRanges.Select(nr => nr.Name)); if (_namedRanges.Scope == XLNamedRangeScope.Worksheet) existingNames.AddRange(_namedRanges.Worksheet.NamedRanges.Select(nr => nr.Name)); existingNames = existingNames.Distinct().ToList(); if (!XLHelper.ValidateName("named range", value, oldname, existingNames, out String message)) throw new ArgumentException(message, nameof(value)); _name = value; if (!String.IsNullOrWhiteSpace(oldname) && !String.Equals(oldname, _name, StringComparison.OrdinalIgnoreCase)) { _namedRanges.Delete(oldname); _namedRanges.Add(_name, this); } } } public IXLRanges Ranges { get { var ranges = new XLRanges(); foreach (var rangeToAdd in from rangeAddress in RangeList.SelectMany(c => c.Split(',')).Where(s => s[0] != '"') let match = XLHelper.NamedRangeReferenceRegex.Match(rangeAddress) select match.Groups["Sheet"].Success ? _namedRanges.Workbook.WorksheetsInternal.Worksheet(match.Groups["Sheet"].Value).Range(match.Groups["Range"].Value) as IXLRangeBase : _namedRanges.Workbook.Worksheets.SelectMany(sheet => sheet.Tables).Single(table => table.Name == match.Groups["Table"].Value).DataRange.Column(match.Groups["Column"].Value)) { ranges.Add(rangeToAdd); } return ranges; } } public String Comment { get; set; } public Boolean Visible { get; set; } public XLNamedRangeScope Scope { get { return _namedRanges.Scope; } } public IXLRanges Add(XLWorkbook workbook, String rangeAddress) { var ranges = new XLRanges(); var byExclamation = rangeAddress.Split('!'); var wsName = byExclamation[0].Replace("'", ""); var rng = byExclamation[1]; var rangeToAdd = workbook.WorksheetsInternal.Worksheet(wsName).Range(rng); ranges.Add(rangeToAdd); return Add(ranges); } public IXLRanges Add(IXLRange range) { var ranges = new XLRanges { range }; return Add(ranges); } public IXLRanges Add(IXLRanges ranges) { ranges.ForEach(r => RangeList.Add(r.ToString())); return ranges; } public void Delete() { _namedRanges.Delete(Name); } public void Clear() { RangeList.Clear(); } public void Remove(String rangeAddress) { RangeList.Remove(rangeAddress); } public void Remove(IXLRange range) { RangeList.Remove(range.ToString()); } public void Remove(IXLRanges ranges) { ranges.ForEach(r => RangeList.Remove(r.ToString())); } public override string ToString() { String retVal = RangeList.Aggregate(String.Empty, (agg, r) => agg + (r + ",")); if (retVal.Length > 0) retVal = retVal.Substring(0, retVal.Length - 1); return retVal; } public String RefersTo { get { return ToString(); } set { RangeList.Clear(); RangeList.Add(value); } } public IXLNamedRange CopyTo(IXLWorksheet targetSheet) { if (targetSheet == _namedRanges.Worksheet) throw new InvalidOperationException("Cannot copy named range to the worksheet it already belongs to."); var ranges = new XLRanges(); foreach (var r in Ranges) { if (_namedRanges.Worksheet == r.Worksheet) // Named ranges on the source worksheet have to point to the new destination sheet ranges.Add(targetSheet.Range(((XLRangeAddress)r.RangeAddress).WithoutWorksheet())); else ranges.Add(r); } return targetSheet.NamedRanges.Add(Name, ranges); } internal IList<String> RangeList { get; set; } = new List<String>(); public IXLNamedRange SetRefersTo(String range) { RefersTo = range; return this; } public IXLNamedRange SetRefersTo(IXLRangeBase range) { RangeList.Clear(); RangeList.Add(range.RangeAddress.ToStringFixed(XLReferenceStyle.A1, true)); return this; } public IXLNamedRange SetRefersTo(IXLRanges ranges) { RangeList.Clear(); ranges.ForEach(r => RangeList.Add(r.RangeAddress.ToStringFixed(XLReferenceStyle.A1, true))); return this; } } }
33.994819
199
0.530407
[ "MIT" ]
Gallardo13/ClosedXML
ClosedXML/Excel/NamedRanges/XLNamedRange.cs
6,369
C#
using AutoIt.Controls; namespace AutoIt.OSD.Background { partial class FormBackground { /// <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)) { _eventShutdownRequested.Dispose(); _eventNewOptionsAvailable.Dispose(); _keyboardHook.Dispose(); if (_namedPipeServerStream != null) { _namedPipeServerStream.Dispose(); } if (_mutexApplication != null) { _mutexApplication.Dispose(); } 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(); this.pictureBoxBackground = new System.Windows.Forms.PictureBox(); this.timerRefresh = new System.Windows.Forms.Timer(this.components); this.progressBar = new AutoIt.Controls.SimpleProgressBar(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxBackground)).BeginInit(); this.SuspendLayout(); // // pictureBoxBackground // this.pictureBoxBackground.BackColor = System.Drawing.SystemColors.WindowFrame; this.pictureBoxBackground.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.pictureBoxBackground.Location = new System.Drawing.Point(12, 12); this.pictureBoxBackground.Name = "pictureBoxBackground"; this.pictureBoxBackground.Size = new System.Drawing.Size(1000, 727); this.pictureBoxBackground.TabIndex = 0; this.pictureBoxBackground.TabStop = false; // // timerRefresh // this.timerRefresh.Tick += new System.EventHandler(this.TimerHandleTickEvent); // // progressBar // this.progressBar.DrawBorder = false; this.progressBar.ForeColor = System.Drawing.Color.CornflowerBlue; this.progressBar.Location = new System.Drawing.Point(0, 760); this.progressBar.Maximum = 100; this.progressBar.Minimum = 0; this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(1024, 8); this.progressBar.TabIndex = 1; this.progressBar.Value = 80; this.progressBar.Visible = false; // // FormBackground // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.CausesValidation = false; this.ClientSize = new System.Drawing.Size(1024, 768); this.ControlBox = false; this.Controls.Add(this.progressBar); this.Controls.Add(this.pictureBoxBackground); this.DoubleBuffered = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "FormBackground"; this.ShowIcon = false; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Text = "OSD Branding"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormBackground_FormClosing); this.Load += new System.EventHandler(this.FormBackground_Load); this.Shown += new System.EventHandler(this.FormBackground_Shown); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxBackground)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pictureBoxBackground; private System.Windows.Forms.Timer timerRefresh; private SimpleProgressBar progressBar; } }
40.327586
114
0.600043
[ "MIT" ]
AutoItConsulting/autoit-osd-background
src/AutoIt.OSD.Background/FormBackground.Designer.cs
4,680
C#
using APIMessageBoard.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace APIMessageBoard { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<APIMessageBoardContext>(opt => opt.UseMySql(Configuration.GetConnectionString("DefaultConnection"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // app.UseHttpsRedirection(); app.UseMvc(); } } }
31
137
0.716846
[ "MIT" ]
tawneeh/MessageBoard.Solution
APIMessageBoard/Startup.cs
1,395
C#
namespace CrmSystem.Data.Migrations { using CrmSystem.Models; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Linq; public sealed class Configuration : DbMigrationsConfiguration<CrmDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(CrmDbContext context) { if (!context.Sales.Any()) { var customers = new List<Customer>(); var companies = new List<Company>(); var projects = new List<Project>(); var products = new List<Product>(); var sales = new List<Sale>(); for (int i = 0; i < 15; i++) { var customer = new Customer { Email = "asd" + i + "@gmail.com", Name = "Customer-" + i, Phone = 08841122 + i + i, Info = "asdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasd" }; customers.Add(customer); context.Customers.Add(customer); var company = new Company { Email = "asd" + i + "@gmail.com", Name = "Customer-" + i, Info = "hfkdhsfjkhdkhfkdhsfjkhdkhfkdhsfjkhdkhfkdhsfjkhdkhfkdhsfjkhdkhfkdhsfjkhdkhfkdhsfjkhdk" }; companies.Add(company); context.Companies.Add(company); var project = new Project { Name = "Project-" + i, Description = "DJSDJFKLDSJFDDJSDJFKLDSJFDDJSDJFKLDSJFDDJSDJFKLDSJFDDJSDJFKLDSJFD", Customer = customer, Company = company }; projects.Add(project); context.Projects.Add(project); var product = new Product { Name = "Product" + i, Price = i + 4545 + i * 20, Info = "Info for product asd Info for product asd Info for product asd" }; products.Add(product); context.Products.Add(product); var sale = new Sale() { Products = new List<Product> { new Product { Name = "Product" + i + 200, Price = i + 4545 + i * 2, Info = "Info for product asd Info for product asd Info for product asd" }, new Product { Name = "Product" + i + 100, Price = i + 4545 + i * 3, Info = "Info for product asd Info for product asd Info for product asd" } }, Company = company, Customer = customer }; sales.Add(sale); context.Sales.Add(sale); }; context.SaveChanges(); } } } }
35.715686
117
0.407631
[ "MIT" ]
AsiaBecheva/CrmSystem-AngularJs-WebApi2
CrmSystem/CrmSystem.Data/Migrations/Configuration.cs
3,643
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor { [ExportLanguageService(typeof(IGenerateConstructorService), LanguageNames.CSharp), Shared] internal class CSharpGenerateConstructorService : AbstractGenerateConstructorService<CSharpGenerateConstructorService, ArgumentSyntax, AttributeArgumentSyntax> { private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation(); protected override bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is SimpleNameSyntax; protected override bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is ConstructorInitializerSyntax; protected override bool TryInitializeConstructorInitializerGeneration( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<ArgumentSyntax> arguments, out INamedTypeSymbol typeToGenerateIn) { var constructorInitializer = (ConstructorInitializerSyntax)node; if (!constructorInitializer.ArgumentList.CloseParenToken.IsMissing) { token = constructorInitializer.ThisOrBaseKeyword; arguments = constructorInitializer.ArgumentList.Arguments.ToImmutableArray(); var semanticModel = document.SemanticModel; var currentType = semanticModel.GetEnclosingNamedType(constructorInitializer.SpanStart, cancellationToken); typeToGenerateIn = constructorInitializer.IsKind(SyntaxKind.ThisConstructorInitializer) ? currentType : currentType.BaseType.OriginalDefinition; return typeToGenerateIn != null; } token = default(SyntaxToken); arguments = default(ImmutableArray<ArgumentSyntax>); typeToGenerateIn = null; return false; } protected override bool TryInitializeSimpleNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<ArgumentSyntax> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is ObjectCreationExpressionSyntax) { var objectCreationExpression = (ObjectCreationExpressionSyntax)fullName.Parent; if (objectCreationExpression.ArgumentList != null && !objectCreationExpression.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(objectCreationExpression.Type, cancellationToken); token = simpleName.Identifier; arguments = objectCreationExpression.ArgumentList.Arguments.ToImmutableArray(); typeToGenerateIn = symbolInfo.GetAnySymbol() as INamedTypeSymbol; return typeToGenerateIn != null; } } token = default(SyntaxToken); arguments = default(ImmutableArray<ArgumentSyntax>); typeToGenerateIn = null; return false; } protected override bool TryInitializeSimpleAttributeNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<ArgumentSyntax> arguments, out ImmutableArray<AttributeArgumentSyntax> attributeArguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is AttributeSyntax) { var attribute = (AttributeSyntax)fullName.Parent; if (attribute.ArgumentList != null && !attribute.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(attribute, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !symbolInfo.CandidateSymbols.IsEmpty) { token = simpleName.Identifier; attributeArguments = attribute.ArgumentList.Arguments.ToImmutableArray(); arguments = attributeArguments.Select( x => SyntaxFactory.Argument( x.NameColon ?? (x.NameEquals != null ? SyntaxFactory.NameColon(x.NameEquals.Name) : null), default(SyntaxToken), x.Expression)).ToImmutableArray(); typeToGenerateIn = symbolInfo.CandidateSymbols.FirstOrDefault().ContainingSymbol as INamedTypeSymbol; return typeToGenerateIn != null; } } } token = default(SyntaxToken); arguments = default(ImmutableArray<ArgumentSyntax>); attributeArguments = default(ImmutableArray<AttributeArgumentSyntax>); typeToGenerateIn = null; return false; } protected override ImmutableArray<ParameterName> GenerateParameterNames( SemanticModel semanticModel, IEnumerable<ArgumentSyntax> arguments, IList<string> reservedNames, CancellationToken cancellationToken) => semanticModel.GenerateParameterNames(arguments, reservedNames, cancellationToken); protected override ImmutableArray<ParameterName> GenerateParameterNames( SemanticModel semanticModel, IEnumerable<AttributeArgumentSyntax> arguments, IList<string> reservedNames, CancellationToken cancellationToken) => semanticModel.GenerateParameterNames(arguments, reservedNames, cancellationToken).ToImmutableArray(); protected override string GenerateNameForArgument(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken) => semanticModel.GenerateNameForArgument(argument, cancellationToken); protected override string GenerateNameForArgument(SemanticModel semanticModel, AttributeArgumentSyntax argument, CancellationToken cancellationToken) => semanticModel.GenerateNameForArgument(argument, cancellationToken); protected override RefKind GetRefKind(ArgumentSyntax argument) { return argument.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword ? RefKind.Ref : argument.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword ? RefKind.Out : RefKind.None; } protected override bool IsNamedArgument(ArgumentSyntax argument) { return argument.NameColon != null; } protected override ITypeSymbol GetArgumentType( SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken) { return argument.DetermineParameterType(semanticModel, cancellationToken); } protected override ITypeSymbol GetAttributeArgumentType( SemanticModel semanticModel, AttributeArgumentSyntax argument, CancellationToken cancellationToken) { return semanticModel.GetType(argument.Expression, cancellationToken); } protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) { return compilation.ClassifyConversion(sourceType, targetType).IsImplicit; } internal override IMethodSymbol GetDelegatingConstructor( State state, SemanticDocument document, int argumentCount, INamedTypeSymbol namedType, ISet<IMethodSymbol> candidates, CancellationToken cancellationToken) { var oldToken = state.Token; var tokenKind = oldToken.Kind(); if (state.IsConstructorInitializerGeneration) { SyntaxToken thisOrBaseKeyword; SyntaxKind newCtorInitializerKind; if (tokenKind != SyntaxKind.BaseKeyword && state.TypeToGenerateIn == namedType) { thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.ThisKeyword); newCtorInitializerKind = SyntaxKind.ThisConstructorInitializer; } else { thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.BaseKeyword); newCtorInitializerKind = SyntaxKind.BaseConstructorInitializer; } var ctorInitializer = (ConstructorInitializerSyntax)oldToken.Parent; var oldArgumentList = ctorInitializer.ArgumentList; var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount); var newCtorInitializer = SyntaxFactory.ConstructorInitializer(newCtorInitializerKind, ctorInitializer.ColonToken, thisOrBaseKeyword, newArgumentList); if (document.SemanticModel.TryGetSpeculativeSemanticModel(ctorInitializer.Span.Start, newCtorInitializer, out var speculativeModel)) { var symbolInfo = speculativeModel.GetSymbolInfo(newCtorInitializer, cancellationToken); return GenerateConstructorHelpers.GetDelegatingConstructor( document, symbolInfo, candidates, namedType, state.ParameterTypes); } } else { var oldNode = oldToken.Parent .AncestorsAndSelf(ascendOutOfTrivia: false) .Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node)) .LastOrDefault(); var typeNameToReplace = (TypeSyntax)oldToken.Parent; TypeSyntax newTypeName; if (namedType != state.TypeToGenerateIn) { while (true) { var parentType = typeNameToReplace.Parent as TypeSyntax; if (parentType == null) { break; } typeNameToReplace = parentType; } newTypeName = namedType.GenerateTypeSyntax().WithAdditionalAnnotations(s_annotation); } else { newTypeName = typeNameToReplace.WithAdditionalAnnotations(s_annotation); } var newNode = oldNode.ReplaceNode(typeNameToReplace, newTypeName); newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single(); var oldArgumentList = (ArgumentListSyntax)newTypeName.Parent.ChildNodes().FirstOrDefault(n => n is ArgumentListSyntax); if (oldArgumentList != null) { var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount); if (newArgumentList != oldArgumentList) { newNode = newNode.ReplaceNode(oldArgumentList, newArgumentList); newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single(); } } var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, document.SemanticModel); if (speculativeModel != null) { var symbolInfo = speculativeModel.GetSymbolInfo(newTypeName.Parent, cancellationToken); return GenerateConstructorHelpers.GetDelegatingConstructor( document, symbolInfo, candidates, namedType, state.ParameterTypes); } } return null; } private static ArgumentListSyntax GetNewArgumentList(ArgumentListSyntax oldArgumentList, int argumentCount) { if (oldArgumentList.IsMissing || oldArgumentList.Arguments.Count == argumentCount) { return oldArgumentList; } var newArguments = oldArgumentList.Arguments.Take(argumentCount); return SyntaxFactory.ArgumentList(new SeparatedSyntaxList<ArgumentSyntax>().AddRange(newArguments)); } } }
49.155235
166
0.646592
[ "Apache-2.0" ]
amcasey/roslyn
src/Features/CSharp/Portable/GenerateConstructor/CSharpGenerateConstructorService.cs
13,616
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 copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using Aurora.Framework; namespace OpenSim.Region.Physics.BulletSPlugin { public class BSCharacter : PhysicsCharacter { private static readonly string LogHeader = "[BULLETS CHAR]"; private readonly float _mass = 80f; private readonly Vector3 _scale; private readonly BSScene _scene; private Vector3 _acceleration; private UUID _avID; private String _avName; private bool _collidingGround; private long _collidingGroundStep; private long _collidingStep; public float _density = 60f; private bool _floatOnWater; private bool _flying; private Vector3 _force; private bool _isColliding; private bool _isPhysical; private bool _jumping; private uint _localID; private Quaternion _orientation; private Vector3 _position; private Vector3 _preJumpForce; private int _preJumpTime; private bool _preJumping; private Vector3 _rotationalVelocity; private bool _setAlwaysRun; private Vector3 _size; private float _speedModifier = 1; private Vector3 _targetVelocity; private bool _targetVelocityIsDecaying; private Vector3 _velocity; public BSCharacter(uint localID, UUID avID, String avName, BSScene parent_scene, Vector3 pos, Quaternion rotation, Vector3 size, bool isFlying) { _localID = localID; _avID = avID; _avName = avName; _scene = parent_scene; _position = pos; _orientation = rotation; _size = size; _orientation = Quaternion.Identity; _velocity = Vector3.Zero; _scale = new Vector3(1f, 1f, 1f); float AVvolume = (float) (Math.PI*Math.Pow(_scene.Params.avatarCapsuleRadius, 2)*_scene.Params.avatarCapsuleHeight); _density = _scene.Params.avatarDensity; _mass = _density*AVvolume; _isPhysical = true; ShapeData shapeData = new ShapeData { ID = _localID, Type = ShapeData.PhysicsShapeType.SHAPE_AVATAR, Position = _position, Rotation = _orientation, Velocity = _velocity, Scale = _scale, Mass = _mass, Buoyancy = isFlying ? 1f : 0f, Static = ShapeData.numericFalse, Friction = _scene.Params.avatarFriction, Restitution = _scene.Params.defaultRestitution }; // do actual create at taint time _scene.TaintedObject(() => BulletSimAPI.CreateObject(parent_scene.WorldID, shapeData)); return; } // called when this character is being destroyed and the resources should be released public override Vector3 Size { get { return _size; } set { _size = value; } } public override uint LocalID { set { _localID = value; } get { return _localID; } } public override Vector3 Position { get { // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); return _position; } set { _position = value; _scene.TaintedObject( () => BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation)); } } public override float Mass { get { return _mass; } } public override Vector3 Force { get { return _force; } set { _force = value; _scene.TaintedObject(() => BulletSimAPI.SetObjectForce(_scene.WorldID, _localID, _force)); } } public override Vector3 Velocity { get { return _velocity; } set { _velocity = value; } } public override float CollisionScore { get; set; } public override Quaternion Orientation { get { return _orientation; } set { _orientation = value; _scene.TaintedObject(() => BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation)); } } public override int PhysicsActorType { get { return (int) ActorTypes.Agent; } } public override bool IsPhysical { get { return _isPhysical; } set { _isPhysical = value; } } public override bool Flying { get { return _flying; } set { if (_flying != value) { _flying = value; ChangeFlying(); _scene.TaintedObject(() => BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, LocalID, _flying ? 1f : 0f)); } } } public override bool SetAlwaysRun { get { return _setAlwaysRun; } set { _setAlwaysRun = value; } } public override bool ThrottleUpdates { get; set; } public override bool IsTruelyColliding { get; set; } public override bool IsColliding { get { return (_collidingStep == _scene.SimulationStep); } set { _isColliding = value; } } public bool CollidingGround { get { return (_collidingGroundStep == _scene.SimulationStep); } set { _collidingGround = value; } } public bool CollidingObj { get; set; } public override bool FloatOnWater { set { _floatOnWater = value; } } public override Vector3 RotationalVelocity { get { return _rotationalVelocity; } set { _rotationalVelocity = value; } } public override bool IsJumping { get { return _jumping; } } public override float SpeedModifier { get { return _speedModifier; } set { _speedModifier = value; } } public override bool IsPreJumping { get { return _preJumping; } } public override void Destroy() { _scene.TaintedObject(() => BulletSimAPI.DestroyObject(_scene.WorldID, _localID)); } public override void AddForce(Vector3 force, bool pushforce) { if (force.IsFinite()) { _force.X += force.X; _force.Y += force.Y; _force.Z += force.Z; _scene.TaintedObject(() => BulletSimAPI.SetObjectForce(_scene.WorldID, _localID, _force)); } else { MainConsole.Instance.WarnFormat("{0}: Got a NaN force applied to a Character", LogHeader); } //m_lastUpdateSent = false; } public override bool SubscribedEvents() { return true; } #region Movement/Update // The physics engine says that properties have updated. Update same and inform // the world that things have changed. public void UpdateProperties(EntityProperties entprop) { bool changed = false; #region Updating Position if (entprop.ID != 0) { // we assign to the local variables so the normal set action does not happen if (_position != entprop.Position) { _position = entprop.Position; changed = true; } if (_orientation != entprop.Rotation) { _orientation = entprop.Rotation; changed = true; } if (_velocity != entprop.Velocity) { changed = true; _velocity = entprop.Velocity; } if (_acceleration != entprop.Acceleration) { _acceleration = entprop.Acceleration; changed = true; } if (_rotationalVelocity != entprop.RotationalVelocity) { changed = true; _rotationalVelocity = entprop.RotationalVelocity; } if (changed) TriggerMovementUpdate(); } #endregion #region Jump code if (_preJumping && Util.EnvironmentTickCountSubtract(_preJumpTime) > _scene.PreJumpTime) { //Time to jump _jumping = true; _preJumping = false; Velocity += _preJumpForce; _targetVelocityIsDecaying = false; TriggerMovementUpdate(); } if (_jumping && Util.EnvironmentTickCountSubtract(_preJumpTime) > _scene.PreJumpTime + 2000) { _jumping = false; _targetVelocity = Vector3.Zero; TriggerMovementUpdate(); } else if (_jumping && Util.EnvironmentTickCountSubtract(_preJumpTime) > _scene.PreJumpTime + 750) { _targetVelocityIsDecaying = false; TriggerMovementUpdate(); } else if (_jumping && Util.EnvironmentTickCountSubtract(_preJumpTime) > _scene.PreJumpTime + 500) { _targetVelocityIsDecaying = false; Velocity -= _preJumpForce/100; //Cut down on going up TriggerMovementUpdate(); } #endregion #region Decaying velocity if (_targetVelocityIsDecaying) { _targetVelocity *= _scene.DelayingVelocityMultiplier; if (_targetVelocity.ApproxEquals(Vector3.Zero, 0.1f) || _velocity == Vector3.Zero) _targetVelocity = Vector3.Zero; } if (_targetVelocity != Vector3.Zero) Velocity = new Vector3( _targetVelocity.X == 0 ? Velocity.X : (_targetVelocity.X*0.25f) + (Velocity.X*0.75f), _targetVelocity.Y == 0 ? Velocity.Y : (_targetVelocity.Y*0.25f) + (Velocity.Y*0.75f), _targetVelocity.Z == 0 ? Velocity.Z : (_targetVelocity.Z*0.25f) + (Velocity.Z*0.75f)); else if (Velocity.X != 0 || Velocity.Y != 0 || Velocity.Z > 0) Velocity *= _scene.DelayingVelocityMultiplier; if (Velocity.ApproxEquals(Vector3.Zero, 0.3f)) Velocity = Vector3.Zero; #endregion } public override void SetMovementForce(Vector3 force) { if (!_flying) { if (force.Z >= 0.5f) { if (!_scene.AllowJump) return; if (_scene.AllowPreJump) { _preJumping = true; if (force.X == 0 && force.Y == 0) _preJumpForce = force*_scene.PreJumpForceMultiplier*2; else _preJumpForce = force*_scene.PreJumpForceMultiplier*3.5f; _preJumpTime = Util.EnvironmentTickCount(); TriggerMovementUpdate(); return; } else { _jumping = true; _preJumpTime = Util.EnvironmentTickCountAdd(_scene.PreJumpTime); TriggerMovementUpdate(); Velocity += force*_scene.PreJumpForceMultiplier; } } } if (_preJumping) { TriggerMovementUpdate(); return; } if (force != Vector3.Zero) { float multiplier; multiplier = !_setAlwaysRun ? _scene.AvWalkingSpeed : _scene.AvRunningSpeed; multiplier *= SpeedModifier*5; multiplier *= (1/_scene.TimeDilation); //Factor in Time Dilation if (Flying) multiplier *= _scene.AvFlyingSpeed; //Add flying speeds _targetVelocity = force*multiplier; _targetVelocityIsDecaying = false; //We arn't decaying yet if (!_flying) _targetVelocity.Z = Velocity.Z; Velocity = _targetVelocity; //Step it up } else _targetVelocityIsDecaying = true; //Start slowing us down } private void ChangeFlying() { if (!_flying) //Do this so that we fall down immediately _targetVelocity = Vector3.Zero; } #endregion #region Collisions private readonly CollisionEventUpdate args = new CollisionEventUpdate(); public void Collide(uint collidingWith, ActorTypes type, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth) { // MainConsole.Instance.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); // The following makes IsColliding() and IsCollidingGround() work _collidingStep = _scene.SimulationStep; if (collidingWith == BSScene.TERRAIN_ID || collidingWith == BSScene.GROUNDPLANE_ID) { _collidingGroundStep = _scene.SimulationStep; } Dictionary<uint, ContactPoint> contactPoints = new Dictionary<uint, ContactPoint>(); AddCollisionEvent(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth, type)); } public override void SendCollisions() { if (!args.Cleared) { SendCollisionUpdate(args.Copy()); args.Clear(); } } public override void AddCollisionEvent(uint localID, ContactPoint contact) { args.addCollider(localID, contact); } #endregion #region ForceSet** public override void ForceSetPosition(Vector3 position) { Position = position; _position = position; } public override void ForceSetVelocity(Vector3 velocity) { _velocity = velocity; Velocity = velocity; } #endregion } }
36.121457
147
0.50779
[ "BSD-3-Clause" ]
BillyWarrhol/Aurora-Sim
Aurora/Physics/ModifiedBulletSim/BSCharacter.cs
17,846
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("azdyrski.Umbraco-User-Reporting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("azdyrski.Umbraco-User-Reporting")] [assembly: AssemblyCopyright("Copyright 2021")] [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("c4355462-5b41-48a4-adc8-91a3926042a0")] [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
40.740741
84
0.776364
[ "MIT" ]
azdyrski/Umbraco-User-Reporting
azdyrski.Umbraco-User-Reporting/Properties/AssemblyInfo.cs
1,100
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Animation; namespace PipeShot.Libraries.Helper { public static class Extensions { public const int BufferSize = 4096; public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { if (source == null) throw new ArgumentNullException(nameof(source)); if (action == null) throw new ArgumentNullException(nameof(action)); foreach (T item in source) { action(item); } } public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison) { if (string.IsNullOrEmpty(oldValue)) { return str; } StringBuilder sb = new StringBuilder(); int previousIndex = 0; int index = str.IndexOf(oldValue, comparison); while (index != -1) { sb.Append(str.Substring(previousIndex, index - previousIndex)); sb.Append(newValue); index += oldValue.Length; previousIndex = index; index = str.IndexOf(oldValue, index, comparison); } sb.Append(str.Substring(previousIndex)); return sb.ToString(); } #region UI public static async Task AnimateAsync(this UIElement element, DependencyProperty dp, double from, double to, int duration, int beginTime = 0) { TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); try { await element.Dispatcher.BeginInvoke(new Action(() => { DoubleAnimation animation = new DoubleAnimation(from, to, TimeSpan.FromMilliseconds(duration)) { BeginTime = TimeSpan.FromMilliseconds(beginTime) }; animation.Completed += delegate { tcs.SetResult(true); }; element.BeginAnimation(dp, animation); })); } catch { //Task was canceled return; } await tcs.Task; } public static async Task AnimateAsync(this UIElement element, DependencyProperty dp, DoubleAnimation animation) { TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); try { await element.Dispatcher.BeginInvoke(new Action(() => { animation.Completed += delegate { tcs.SetResult(true); }; element.BeginAnimation(dp, animation); })); } catch { //Task was canceled return; } await tcs.Task; } public static async void Animate(this UIElement element, DependencyProperty dp, double from, double to, int duration, int beginTime = 0) { TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); try { await element.Dispatcher.BeginInvoke(new Action(() => { DoubleAnimation animation = new DoubleAnimation(from, to, TimeSpan.FromMilliseconds(duration)) { BeginTime = TimeSpan.FromMilliseconds(beginTime) }; animation.Completed += delegate { tcs.SetResult(true); }; element.BeginAnimation(dp, animation); })); } catch { //Task was canceled return; } await tcs.Task; } public static async void Animate(this UIElement element, DependencyProperty dp, DoubleAnimation animation) { TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); try { await element.Dispatcher.BeginInvoke(new Action(() => { animation.Completed += delegate { tcs.SetResult(true); }; element.BeginAnimation(dp, animation); })); } catch { //Task was canceled return; } await tcs.Task; } #endregion } }
35.886179
151
0.531717
[ "MIT" ]
PipeRift/Pipeshot
PipeShot/Libraries/Helper/Extensions.cs
4,416
C#
/** * Copyright 2013 Canada Health Infoway, Inc. * * 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. * * Author: $LastChangedBy: gng $ * Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $ * Revision: $LastChangedRevision: 9755 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_shr.Domainvalue { public interface TopicalApplication : Code { } }
36.344828
83
0.709677
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab_r02_04_03_shr/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_shr/Domainvalue/TopicalApplication.cs
1,054
C#
using Ocelot.Configuration.Builder; using Ocelot.Configuration.File; namespace Ocelot.Configuration.Creator { public class ServiceProviderConfigurationCreator : IServiceProviderConfigurationCreator { public ServiceProviderConfiguration Create(FileGlobalConfiguration globalConfiguration) { var port = globalConfiguration?.ServiceDiscoveryProvider?.Port ?? 0; var host = globalConfiguration?.ServiceDiscoveryProvider?.Host ?? "consul"; return new ServiceProviderConfigurationBuilder() .WithHost(host) .WithPort(port) .WithType(globalConfiguration?.ServiceDiscoveryProvider?.Type) .WithToken(globalConfiguration?.ServiceDiscoveryProvider?.Token) .WithConfigurationKey(globalConfiguration?.ServiceDiscoveryProvider?.ConfigurationKey) .Build(); } } }
39.869565
102
0.694656
[ "MIT" ]
chinayou25/Ocelot
src/Ocelot/Configuration/Creator/ServiceProviderConfigurationCreator.cs
917
C#
using System; namespace Structure.Domain.Interfaces { public interface IBase { DateTime? CreatedDate { get; set; } int Id { get; set; } bool? IsDeleted { get; set; } DateTime? UpdatedDate { get; set; } void Reset(); } }
19.571429
43
0.562044
[ "MIT" ]
FShieldheart/pcms
Structure/Domain/Interfaces/IBase.cs
276
C#
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; namespace Rave.NET.API { internal abstract class RaveRequestBase<T1, T2> : IRaveRequest<T1, T2> where T1 : RaveResponse<T2>, new() where T2 : class { protected RaveRequestBase() { Config = new RaveConfig(false); HttpClient = new HttpClient { BaseAddress = Config.IsLive ? new Uri(Rave.NET.Config.Const.LiveUrl) : new Uri(Rave.NET.Config.Const.SanboxUrl) }; HttpClient.DefaultRequestHeaders.Accept.Clear(); HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } protected RaveRequestBase(RaveConfig config) { Config = config; HttpClient = new HttpClient() { BaseAddress = Config.IsLive ? new Uri(Rave.NET.Config.Const.LiveUrl) : new Uri(Rave.NET.Config.Const.SanboxUrl) }; HttpClient.DefaultRequestHeaders.Accept.Clear(); HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } protected HttpClient HttpClient { get; } protected RaveConfig Config { get; set; } public virtual async Task<T1> Request(HttpRequestMessage requestBody) { var httpResponse = await HttpClient.SendAsync(requestBody); T1 response; if (httpResponse.IsSuccessStatusCode) { response = JsonConvert.DeserializeObject<T1>(await httpResponse.Content.ReadAsStringAsync()); } else { response = await ExamineFailedRespone(httpResponse); } // Todo: If request fails find out the type of failure return response; } public async Task<T0> Request<T0>(HttpRequestMessage requestBody) { var httpResponse = await HttpClient.SendAsync(requestBody); var response = JsonConvert.DeserializeObject<T0>(await httpResponse.Content.ReadAsStringAsync()); return response; } private static async Task<T1> ExamineFailedRespone(HttpResponseMessage httpResponse) { return JsonConvert.DeserializeObject<T1>(await httpResponse.Content.ReadAsStringAsync()); // Todo: This is a placeholder } } }
37.449275
132
0.60565
[ "MIT" ]
DaraOladapo/Rave.NET
Rave.NET/API/RaveRequestBase.cs
2,586
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace YAF.Pages.Admin { public partial class EditForum { /// <summary> /// PageLinks control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.PageLinks PageLinks; /// <summary> /// LocalizedLabel1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.LocalizedLabel LocalizedLabel1; /// <summary> /// Label1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label Label1; /// <summary> /// LocalizedLabel2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.LocalizedLabel LocalizedLabel2; /// <summary> /// ForumNameTitle control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label ForumNameTitle; /// <summary> /// HelpLabel3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel3; /// <summary> /// Name control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Name; /// <summary> /// HelpLabel4 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel4; /// <summary> /// Description control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Description; /// <summary> /// HelpLabel1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel1; /// <summary> /// CategoryList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList CategoryList; /// <summary> /// HelpLabel2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel2; /// <summary> /// ParentList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ParentList; /// <summary> /// LocalizedLabel4 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.LocalizedLabel LocalizedLabel4; /// <summary> /// AccessList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Repeater AccessList; /// <summary> /// HelpLabel14 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel14; /// <summary> /// remoteurl control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox remoteurl; /// <summary> /// HelpLabel12 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel12; /// <summary> /// SortOrder control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox SortOrder; /// <summary> /// HelpLabel13 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel13; /// <summary> /// ThemeList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ThemeList; /// <summary> /// HelpLabel11 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel11; /// <summary> /// HideNoAccess control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox HideNoAccess; /// <summary> /// HelpLabel10 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel10; /// <summary> /// Locked control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox Locked; /// <summary> /// HelpLabel9 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel9; /// <summary> /// IsTest control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox IsTest; /// <summary> /// HelpLabel8 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel8; /// <summary> /// Moderated control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox Moderated; /// <summary> /// ModerateNewTopicOnlyRow control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder ModerateNewTopicOnlyRow; /// <summary> /// HelpLabel16 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel16; /// <summary> /// ModerateNewTopicOnly control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox ModerateNewTopicOnly; /// <summary> /// ModeratedPostCountRow control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder ModeratedPostCountRow; /// <summary> /// HelpLabel15 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel15; /// <summary> /// ModerateAllPosts control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox ModerateAllPosts; /// <summary> /// ModeratedPostCount control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox ModeratedPostCount; /// <summary> /// HelpLabel7 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel7; /// <summary> /// ForumImages control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.ImageListBox ForumImages; /// <summary> /// HelpLabel6 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel6; /// <summary> /// Styles control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Styles; /// <summary> /// Save control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.ThemeButton Save; /// <summary> /// Cancel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::YAF.Web.Controls.ThemeButton Cancel; } }
35.356061
89
0.54389
[ "Apache-2.0" ]
dotnetframeworknewbie/YAFNET
yafsrc/YetAnotherForum.NET/Pages/Admin/EditForum.ascx.designer.cs
13,606
C#
using System; namespace Framework.Exceptions { public class ObjectByCodeNotFoundException<TCode> : BusinessLogicException { public ObjectByCodeNotFoundException(Type type, TCode code) : base($"{type.Name} with code = \"{code}\" not found") { } } }
23.846154
79
0.612903
[ "MIT" ]
Luxoft/BSSFramework
src/Framework.Exceptions/BusinessLogic/NotFound/ObjectByCodeNotFoundException.cs
300
C#
using System; namespace EsapiEssentials.Standalone { public class LogInRequiredException : Exception { public LogInRequiredException() { } public LogInRequiredException(Exception innerException) : base("The user has not logged in to Eclipse.", innerException) { } } }
26.75
81
0.666667
[ "MIT" ]
redcurry/EsapiEssentials
src/EsapiEssentials/Standalone/Async/LogInRequiredException.cs
323
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; namespace Azure.Messaging.EventGrid.SystemEvents { /// <summary> Job output finished event data. </summary> public partial class MediaJobOutputFinishedEventData : MediaJobOutputStateChangeEventData { /// <summary> Initializes a new instance of MediaJobOutputFinishedEventData. </summary> internal MediaJobOutputFinishedEventData() { } /// <summary> Initializes a new instance of MediaJobOutputFinishedEventData. </summary> /// <param name="previousState"> The previous state of the Job. </param> /// <param name="output"> Gets the output. </param> /// <param name="jobCorrelationData"> Gets the Job correlation data. </param> internal MediaJobOutputFinishedEventData(MediaJobState? previousState, MediaJobOutput output, IReadOnlyDictionary<string, string> jobCorrelationData) : base(previousState, output, jobCorrelationData) { } } }
38.344828
207
0.71223
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/MediaJobOutputFinishedEventData.cs
1,112
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Nop.Core; using Nop.Core.Domain.Stores; using Nop.Core.Plugins; using Nop.Plugin.Feed.Froogle.Domain; using Nop.Plugin.Feed.Froogle.Models; using Nop.Plugin.Feed.Froogle.Services; using Nop.Services.Catalog; using Nop.Services.Configuration; using Nop.Services.Directory; using Nop.Services.Localization; using Nop.Services.Logging; using Nop.Services.Security; using Nop.Services.Stores; using Nop.Web.Framework.Controllers; using Nop.Web.Framework.Kendoui; using Nop.Web.Framework.Mvc; namespace Nop.Plugin.Feed.Froogle.Controllers { [AdminAuthorize] public class FeedFroogleController : BasePluginController { private readonly IGoogleService _googleService; private readonly IProductService _productService; private readonly ICurrencyService _currencyService; private readonly ILocalizationService _localizationService; private readonly IPluginFinder _pluginFinder; private readonly ILogger _logger; private readonly IWebHelper _webHelper; private readonly IStoreService _storeService; private readonly FroogleSettings _froogleSettings; private readonly ISettingService _settingService; private readonly IPermissionService _permissionService; public FeedFroogleController(IGoogleService googleService, IProductService productService, ICurrencyService currencyService, ILocalizationService localizationService, IPluginFinder pluginFinder, ILogger logger, IWebHelper webHelper, IStoreService storeService, FroogleSettings froogleSettings, ISettingService settingService, IPermissionService permissionService) { this._googleService = googleService; this._productService = productService; this._currencyService = currencyService; this._localizationService = localizationService; this._pluginFinder = pluginFinder; this._logger = logger; this._webHelper = webHelper; this._storeService = storeService; this._froogleSettings = froogleSettings; this._settingService = settingService; this._permissionService = permissionService; } [ChildActionOnly] public ActionResult Configure() { var model = new FeedFroogleModel(); //picture model.ProductPictureSize = _froogleSettings.ProductPictureSize; //stores model.StoreId = _froogleSettings.StoreId; model.AvailableStores.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); foreach (var s in _storeService.GetAllStores()) model.AvailableStores.Add(new SelectListItem() { Text = s.Name, Value = s.Id.ToString() }); //currencies model.CurrencyId = _froogleSettings.CurrencyId; foreach (var c in _currencyService.GetAllCurrencies()) model.AvailableCurrencies.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString() }); //Google categories model.DefaultGoogleCategory = _froogleSettings.DefaultGoogleCategory; model.AvailableGoogleCategories.Add(new SelectListItem() {Text = "Select a category", Value = ""}); foreach (var gc in _googleService.GetTaxonomyList()) model.AvailableGoogleCategories.Add(new SelectListItem() {Text = gc, Value = gc}); //file paths foreach (var store in _storeService.GetAllStores()) { var localFilePath = System.IO.Path.Combine(HttpRuntime.AppDomainAppPath, "content\\files\\exportimport", store.Id + "-" + _froogleSettings.StaticFileName); if (System.IO.File.Exists(localFilePath)) model.GeneratedFiles.Add(new FeedFroogleModel.GeneratedFileModel() { StoreName = store.Name, FileUrl = string.Format("{0}content/files/exportimport/{1}-{2}", _webHelper.GetStoreLocation(false), store.Id, _froogleSettings.StaticFileName) }); } return View("~/Plugins/Feed.Froogle/Views/FeedFroogle/Configure.cshtml", model); } [HttpPost] [ChildActionOnly] [FormValueRequired("save")] public ActionResult Configure(FeedFroogleModel model) { if (!ModelState.IsValid) { return Configure(); } //save settings _froogleSettings.ProductPictureSize = model.ProductPictureSize; _froogleSettings.CurrencyId = model.CurrencyId; _froogleSettings.StoreId = model.StoreId; _froogleSettings.DefaultGoogleCategory = model.DefaultGoogleCategory; _settingService.SaveSetting(_froogleSettings); //redisplay the form return Configure(); } [HttpPost, ActionName("Configure")] [ChildActionOnly] [FormValueRequired("generate")] public ActionResult GenerateFeed(FeedFroogleModel model) { try { var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName("PromotionFeed.Froogle"); if (pluginDescriptor == null) throw new Exception("Cannot load the plugin"); //plugin var plugin = pluginDescriptor.Instance() as FroogleService; if (plugin == null) throw new Exception("Cannot load the plugin"); var stores = new List<Store>(); var storeById = _storeService.GetStoreById(_froogleSettings.StoreId); if (storeById != null) stores.Add(storeById); else stores.AddRange(_storeService.GetAllStores()); foreach (var store in stores) plugin.GenerateStaticFile(store); model.GenerateFeedResult = _localizationService.GetResource("Plugins.Feed.Froogle.SuccessResult"); } catch (Exception exc) { model.GenerateFeedResult = exc.Message; _logger.Error(exc.Message, exc); } //stores model.AvailableStores.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" }); foreach (var s in _storeService.GetAllStores()) model.AvailableStores.Add(new SelectListItem() { Text = s.Name, Value = s.Id.ToString() }); //currencies foreach (var c in _currencyService.GetAllCurrencies()) model.AvailableCurrencies.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString() }); //Google categories model.AvailableGoogleCategories.Add(new SelectListItem() { Text = "Select a category", Value = "" }); foreach (var gc in _googleService.GetTaxonomyList()) model.AvailableGoogleCategories.Add(new SelectListItem() { Text = gc, Value = gc }); //file paths foreach (var store in _storeService.GetAllStores()) { var localFilePath = System.IO.Path.Combine(HttpRuntime.AppDomainAppPath, "content\\files\\exportimport", store.Id + "-" + _froogleSettings.StaticFileName); if (System.IO.File.Exists(localFilePath)) model.GeneratedFiles.Add(new FeedFroogleModel.GeneratedFileModel() { StoreName = store.Name, FileUrl = string.Format("{0}content/files/exportimport/{1}-{2}", _webHelper.GetStoreLocation(false), store.Id, _froogleSettings.StaticFileName) }); } return View("~/Plugins/Feed.Froogle/Views/FeedFroogle/Configure.cshtml", model); } [HttpPost] public ActionResult GoogleProductList(DataSourceRequest command) { if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins)) return Content("Access denied"); var products = _productService.SearchProducts(pageIndex: command.Page - 1, pageSize: command.PageSize, showHidden: true); var productsModel = products .Select(x => { var gModel = new FeedFroogleModel.GoogleProductModel() { ProductId = x.Id, ProductName = x.Name }; var googleProduct = _googleService.GetByProductId(x.Id); if (googleProduct != null) { gModel.GoogleCategory = googleProduct.Taxonomy; gModel.Gender = googleProduct.Gender; gModel.AgeGroup = googleProduct.AgeGroup; gModel.Color = googleProduct.Color; gModel.GoogleSize = googleProduct.Size; } return gModel; }) .ToList(); var gridModel = new DataSourceResult { Data = productsModel, Total = products.TotalCount }; return Json(gridModel); } [HttpPost] public ActionResult GoogleProductUpdate(FeedFroogleModel.GoogleProductModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins)) return Content("Access denied"); var googleProduct = _googleService.GetByProductId(model.ProductId); if (googleProduct != null) { googleProduct.Taxonomy = model.GoogleCategory; googleProduct.Gender = model.Gender; googleProduct.AgeGroup = model.AgeGroup; googleProduct.Color = model.Color; googleProduct.Size = model.GoogleSize; _googleService.UpdateGoogleProductRecord(googleProduct); } else { //insert googleProduct = new GoogleProductRecord() { ProductId = model.ProductId, Taxonomy = model.GoogleCategory, Gender = model.Gender, AgeGroup = model.AgeGroup, Color = model.Color, Size = model.GoogleSize }; _googleService.InsertGoogleProductRecord(googleProduct); } return new NullJsonResult(); } } }
43.80315
171
0.589071
[ "MIT" ]
shoy160/nopCommerce
Plugins/Nop.Plugin.Feed.Froogle/Controllers/FeedFroogleController.cs
11,128
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 DBCopyTool { public partial class FormBackup : Form { public FormBackup() { InitializeComponent(); } } }
18.047619
42
0.691293
[ "Apache-2.0" ]
mlund337/DBCopyTool
FormBackup.cs
381
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.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal partial class EventHookupCommandHandler : IChainedCommandHandler<TypeCharCommandArgs> { public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); nextHandler(); if (!args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.EventHookup)) { EventHookupSessionManager.CancelAndDismissExistingSessions(); return; } // Event hookup is current uncancellable. var cancellationToken = CancellationToken.None; using (Logger.LogBlock(FunctionId.EventHookup_Type_Char, cancellationToken)) { if (args.TypedChar == '=') { // They've typed an equals. Cancel existing sessions and potentially start a // new session. EventHookupSessionManager.CancelAndDismissExistingSessions(); if (IsTextualPlusEquals(args.TextView, args.SubjectBuffer)) { EventHookupSessionManager.BeginSession(this, args.TextView, args.SubjectBuffer, _asyncListener, TESTSessionHookupMutex); } } else { // Spaces are the only non-'=' character that allow the session to continue if (args.TypedChar != ' ') { EventHookupSessionManager.CancelAndDismissExistingSessions(); } } } } private bool IsTextualPlusEquals(ITextView textView, ITextBuffer subjectBuffer) { AssertIsForeground(); var caretPoint = textView.GetCaretPoint(subjectBuffer); if (!caretPoint.HasValue) { return false; } var position = caretPoint.Value.Position; return position - 2 >= 0 && subjectBuffer.CurrentSnapshot.GetText(position - 2, 2) == "+="; } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler) { AssertIsForeground(); return nextHandler(); } } }
37.948718
144
0.617905
[ "MIT" ]
06needhamt/roslyn
src/VisualStudio/CSharp/Impl/EventHookup/EventHookupCommandHandler_TypeCharCommand.cs
2,962
C#
using Findo.Framework.Service.Service; using MicroService.CheckList.Domain.Model; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Text; namespace MicroService.CheckList.Service { public class CheckListService : GenericService<IUserRepository, CheckList>, IUserService { IConfiguration _config; public CheckListService( IUnitOfWork unitOfWork, IUserRepository repository, IConfiguration configuration, ILogger<UserService> logger) : base(unitOfWork, repository, logger) { _config = configuration; } } }
26.36
92
0.698027
[ "MIT" ]
FagnerFun/Findo
FindoApi/MicroService.CheckList.API/MicroService.CheckList.Service/CheckListService.cs
661
C#
using Estrol.KREmu.Servers; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Estrol.KREmu.Servers.Payloads { public class opcode_Planet : SendPacket { public override void GetData(Connection state) { state.payload = "planet"; int planetNumber = state.Buffer[3]; Console.WriteLine("[Server] Client connected to planet no. {0}", planetNumber); using (MemoryStream ms = new MemoryStream()) using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(new byte[] { 0x0E, 0x01, 0xEB, 0x03 }); // Opcode and Packet length bw.Write(new byte[] { // Total channel? 0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); for (int i = 0; i < 20; i++) { bw.Write(new byte[] { // Write channel data 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00 }); bw.Write(new byte[] { // Channel position (byte)(i + 1), 0x00 }); } bw.Write(new byte[] { // Same channel data but the post goto one again. 0x78, 0x00, 0x00, 0x00, // Idk why. 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00 }); state.Send(ms.ToArray()); } } } }
36.595745
118
0.423256
[ "MIT" ]
Estrol/KREmu
Estrol.KREmu/Servers/Payloads/opcode_Planet.cs
1,722
C#
using System.Collections.Generic; namespace WYUN.Deserialization { [System.Serializable] public class RoomList { public List<Queries.CreateQuery> rooms; public RoomList() { rooms = new List<Queries.CreateQuery>(); } public void Add(Queries.CreateQuery item) { rooms.Add(item); } public void Remove(Queries.CreateQuery item) { rooms.Remove(item); } } }
22.954545
53
0.536634
[ "MIT" ]
ystt-lita/WYUN_Library
Scripts/Deserialization/RoomList.cs
505
C#
using Sys = global::System; using SysConv = global::System.Convert; using SysTxt = global::System.Text; using SysCll = global::System.Collections; using SysClG = global::System.Collections.Generic; using SysSock = global::System.Net.Sockets; using SysCfg = global::System.Configuration; using SysService = global::System.ServiceProcess; using LDap = global::Libs.LDAP; using LCore = global::Libs.LDAP.Core; using LServ = global::Libs.Service; namespace Libs.Service { public interface IServer : Sys.IDisposable { bool IsStarted { get; } void Start(); void Stop(); } public sealed class ServiceRunner : SysService.ServiceBase { private SysClG.IList<LServ.IServer> Servers; public void Execute() { if (this.Servers != null) { foreach (LServ.IServer Server in this.Servers) { Server.Start(); } } } protected override void OnStart(string[] args) { this.Execute(); base.OnStart(args); } protected override void OnStop() { if (this.Servers != null) { foreach (LServ.IServer Server in this.Servers) { Server.Stop(); } } base.OnStop(); } protected override void OnPause() { if (this.Servers != null) { foreach (LServ.IServer Server in this.Servers) { Server.Stop(); } } base.OnPause(); } protected override void OnContinue() { this.OnStart(null); base.OnContinue(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (this.Servers != null) { foreach (LServ.IServer Server in this.Servers) { Server.Dispose(); } this.Servers.Clear(); this.Servers = null; } } public ServiceRunner(SysClG.IList<LServ.IServer> Servers) : base() { this.Servers = Servers; } } [Sys.ComponentModel.RunInstaller(true)] public abstract class ServiceInstaller : SysCfg.Install.Installer { internal const string LogDateFormat = "yyyy-MM-dd hh:mm:ss.fff"; public const string InstallKey = "install"; public const string StartKey = "start"; public const string AutoStartKey = "auto"; public const string PauseKey = "pause"; public const string ContinueKey = "continue"; public const string StopKey = "stop"; public const string UninstallKey = "uninstall"; public const string RunKey = "run"; private SysService.ServiceProcessInstaller pInstaller; private SysService.ServiceInstaller sInstaller; protected static bool ServiceIsRunning(string ServiceName) { using (SysService.ServiceController sc = new SysService.ServiceController(ServiceName)) { try { return (sc.Status == SysService.ServiceControllerStatus.Running); } catch { return false; } } } protected static void ServicePause(string ServiceName) { using (SysService.ServiceController sc = new SysService.ServiceController(ServiceName)) { if (sc.Status == SysService.ServiceControllerStatus.Running) { sc.Pause(); } } } protected static void ServiceContinue(string ServiceName) { using (SysService.ServiceController sc = new SysService.ServiceController(ServiceName)) { if (sc.Status == SysService.ServiceControllerStatus.Paused) { sc.Continue(); } } } protected static void ServiceStart(string ServiceName) { using (SysService.ServiceController sc = new SysService.ServiceController(ServiceName)) { if (sc.Status != SysService.ServiceControllerStatus.Running) { sc.Start(); } } } protected static void ServiceStop(string ServiceName) { using (SysService.ServiceController sc = new SysService.ServiceController(ServiceName)) { if (sc.Status == SysService.ServiceControllerStatus.Running) { sc.Stop(); } } } protected static void ServiceInstall(string ServiceName) { SysCfg.Install.ManagedInstallerClass.InstallHelper(new string[] { LServ.ServiceInstaller.Location(true) }); } protected static void ServiceUninstall(string ServiceName) { SysCfg.Install.ManagedInstallerClass.InstallHelper(new string[] { "/u", LServ.ServiceInstaller.Location(true) }); } public static string Location(bool FileName) //APPDATA for Services is on (something like): C:\Windows\System32\config\systemprofile\AppData\Roaming { Sys.Reflection.Assembly Asm = Sys.Reflection.Assembly.GetExecutingAssembly(); string File = string.Empty; if (FileName) { File = Asm.CodeBase.Replace("file:///", string.Empty).Replace('/', '\\'); } else { File = Asm.CodeBase.Replace("file:///", string.Empty).Replace('/', '\\').Replace(Asm.ManifestModule.Name, string.Empty); } return File; } private static void Run(SysClG.IList<LServ.IServer> Servers) { Sys.Console.WriteLine("Will Instantiate Server with " + Servers.Count.ToString() + " Servers Listening (" + Sys.DateTime.Now.ToString(LServ.ServiceInstaller.LogDateFormat, Sys.Globalization.CultureInfo.InvariantCulture) + ")"); using (LServ.ServiceRunner instance = new LServ.ServiceRunner(Servers)) { Sys.Console.WriteLine("Server Instantiated, Will call the \"Execute()\" method (" + Sys.DateTime.Now.ToString(LServ.ServiceInstaller.LogDateFormat, Sys.Globalization.CultureInfo.InvariantCulture) + ")"); instance.Execute(); Sys.Console.WriteLine("\"Execute()\" method completed, all Servers are Listening (" + Sys.DateTime.Now.ToString(LServ.ServiceInstaller.LogDateFormat, Sys.Globalization.CultureInfo.InvariantCulture) + ")"); Sys.Console.WriteLine("Server is Running, press any key to Stop it (or \"c\" to clear log)"); Sys.Console.WriteLine(); Sys.ConsoleKeyInfo K = Sys.Console.ReadKey(); while (K.KeyChar == 'c' || K.KeyChar == 'C') { Sys.Console.Clear(); K = Sys.Console.ReadKey(); } } Sys.Console.WriteLine(); Sys.Console.WriteLine("Server has Stoped"); Sys.Console.WriteLine("Press any ket to exit"); Sys.Console.ReadKey(); } protected static int Process(string ServiceName, SysClG.IList<LServ.IServer> Servers, params string[] args) { if (args == null || args.Length == 0) { #if DEBUG LServ.ServiceInstaller.Run(Servers); #else if (!LServ.ServiceInstaller.ServiceIsRunning(ServiceName)) { SysService.ServiceBase.Run(new LServ.ServiceRunner(Servers)); } #endif } else { switch (args[0].ToLower()) { case LServ.ServiceInstaller.InstallKey: LServ.ServiceInstaller.ServiceInstall(ServiceName); if (args.Length == 2 && args[1] == LServ.ServiceInstaller.AutoStartKey) { LServ.ServiceInstaller.ServiceStart(ServiceName); } break; case LServ.ServiceInstaller.UninstallKey: LServ.ServiceInstaller.ServiceStop(ServiceName); LServ.ServiceInstaller.ServiceUninstall(ServiceName); break; case LServ.ServiceInstaller.StopKey: LServ.ServiceInstaller.ServiceStop(ServiceName); break; case LServ.ServiceInstaller.ContinueKey: LServ.ServiceInstaller.ServiceContinue(ServiceName); break; case LServ.ServiceInstaller.PauseKey: LServ.ServiceInstaller.ServicePause(ServiceName); break; case LServ.ServiceInstaller.StartKey: LServ.ServiceInstaller.ServiceStart(ServiceName); break; case LServ.ServiceInstaller.RunKey: default: LServ.ServiceInstaller.Run(Servers); break; } } return 0; } protected ServiceInstaller(string ServiceName, string ServiceDescription = "") : base() { this.Context = new SysCfg.Install.InstallContext((LServ.ServiceInstaller.Location(false) + "server.log"), new string[] { /* NOTHING */ }); this.pInstaller = new SysService.ServiceProcessInstaller(); this.pInstaller.Account = SysService.ServiceAccount.LocalSystem; this.pInstaller.Context = this.Context; this.Installers.Add(this.pInstaller); this.sInstaller = new SysService.ServiceInstaller(); this.sInstaller.ServiceName = ServiceName; this.sInstaller.DisplayName = ServiceName; this.sInstaller.Description = (string.IsNullOrEmpty(ServiceDescription) ? ServiceName : ServiceDescription); this.sInstaller.StartType = SysService.ServiceStartMode.Automatic; this.sInstaller.Context = this.Context; this.Installers.Add(this.sInstaller); //knowledge base http://www.bryancook.net/2008/04/running-multiple-net-services-within.html } } } namespace Libs.LDAP { namespace Core //https://github.com/vforteli/Flexinets.Ldap.Core | https://tools.ietf.org/html/rfc4511 { internal delegate bool Verify<T>(T obj); internal static class Utils { internal static byte[] StringToByteArray(string hex, bool trimWhitespace = true) { if (trimWhitespace) { hex = hex.Replace(" ", string.Empty); } int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) { bytes[i / 2] = SysConv.ToByte(hex.Substring(i, 2), 16); } return bytes; } internal static string ByteArrayToString(byte[] bytes) { SysTxt.StringBuilder hex = new SysTxt.StringBuilder(bytes.Length * 2); foreach (byte b in bytes) { hex.Append(b.ToString("X2")); } return hex.ToString(); } internal static string BitsToString(SysCll.BitArray bits) { int i = 1; string derp = string.Empty; foreach (object bit in bits) { derp += SysConv.ToInt32(bit); if (i % 8 == 0) { derp += " "; } i++; } return derp.Trim(); } internal static byte[] IntToBerLength(int length) //https://en.wikipedia.org/wiki/X.690#BER_encoding { if (length <= 127) { return new byte[] { (byte)length }; } else { byte[] intbytes = Sys.BitConverter.GetBytes(length); Sys.Array.Reverse(intbytes); byte intbyteslength = (byte)intbytes.Length; int lengthByte = intbyteslength + 128; byte[] berBytes = new byte[1 + intbyteslength]; berBytes[0] = (byte)lengthByte; Sys.Buffer.BlockCopy(intbytes, 0, berBytes, 1, intbyteslength); return berBytes; } } internal static TObject[] Reverse<TObject>(SysClG.IEnumerable<TObject> enumerable) { SysClG.List<TObject> acum = new SysClG.List<TObject>(10); foreach (TObject obj in enumerable) { if (acum.Count == acum.Capacity) { acum.Capacity += 10; } acum.Add(obj); } acum.Reverse(); return acum.ToArray(); } internal static bool Any<T>(SysClG.IEnumerable<T> enumerator, LCore.Verify<T> verifier) { foreach (T obj in enumerator) { if (verifier(obj)) { return true; } } return false; } internal static T SingleOrDefault<T>(SysClG.IEnumerable<T> enumerator, LCore.Verify<T> verifier) { foreach (T obj in enumerator) { if (verifier(obj)) { return obj; } } return default(T); } private sealed class ArraySegmentEnumerator<T> : SysClG.IEnumerator<T>, SysClG.IEnumerable<T> //https://referencesource.microsoft.com/#mscorlib/system/arraysegment.cs,9b6becbc5eb6a533 { private T[] _array; private int _start; private int _end; private int _current; public bool MoveNext() { if (this._current < this._end) { this._current++; return (this._current < this._end); } return false; } public T Current { get { if (this._current < this._start) throw new Sys.InvalidOperationException(); else if (this._current >= this._end) throw new Sys.InvalidOperationException(); else return this._array[this._current]; } } SysClG.IEnumerator<T> SysClG.IEnumerable<T>.GetEnumerator() { return this; } SysCll.IEnumerator SysCll.IEnumerable.GetEnumerator() { return this; } object SysCll.IEnumerator.Current { get { return this.Current; } } void SysCll.IEnumerator.Reset() { this._current = this._start - 1; } void Sys.IDisposable.Dispose() { /* NOTHING */ } internal ArraySegmentEnumerator(T[] Array, int Start, int Count) { this._array = Array; this._start = Start; this._end = this._start + Count; this._current = this._start - 1; } } internal static int BerLengthToInt(byte[] bytes, int offset, out int berByteCount) { berByteCount = 1; int attributeLength = 0; if (bytes[offset] >> 7 == 1) { int lengthoflengthbytes = bytes[offset] & 127; byte[] temp = LCore.Utils.Reverse<byte>(new LCore.Utils.ArraySegmentEnumerator<byte>(bytes, offset + 1, lengthoflengthbytes)); Sys.Array.Resize<byte>(ref temp, 4); attributeLength = Sys.BitConverter.ToInt32(temp, 0); berByteCount += lengthoflengthbytes; } else { attributeLength = bytes[offset] & 127; } return attributeLength; } internal static int BerLengthToInt(Sys.IO.Stream stream, out int berByteCount) { berByteCount = 1; int attributeLength = 0; byte[] berByte = new byte[1]; stream.Read(berByte, 0, 1); if (berByte[0] >> 7 == 1) { int lengthoflengthbytes = berByte[0] & 127; byte[] lengthBytes = new byte[lengthoflengthbytes]; stream.Read(lengthBytes, 0, lengthoflengthbytes); byte[] temp = LCore.Utils.Reverse<byte>(lengthBytes); Sys.Array.Resize<byte>(ref temp, 4); attributeLength = Sys.BitConverter.ToInt32(temp, 0); berByteCount += lengthoflengthbytes; } else { attributeLength = berByte[0] & 127; } return attributeLength; } internal static string Repeat(string stuff, int n) { SysTxt.StringBuilder concat = new SysTxt.StringBuilder(stuff.Length * n); for (int i = 0; i < n; i++) { concat.Append(stuff); } return concat.ToString(); } } public enum LdapFilterChoice : byte { and = 0, or = 1, not = 2, equalityMatch = 3, substrings = 4, greaterOrEqual = 5, lessOrEqual = 6, present = 7, approxMatch = 8, extensibleMatch = 9 } public enum LdapOperation : byte { BindRequest = 0, BindResponse = 1, UnbindRequest = 2, SearchRequest = 3, SearchResultEntry = 4, SearchResultDone = 5, SearchResultReference = 19, ModifyRequest = 6, ModifyResponse = 7, AddRequest = 8, AddResponse = 9, DelRequest = 10, DelResponse = 11, ModifyDNRequest = 12, ModifyDNResponse = 13, CompareRequest = 14, CompareResponse = 15, AbandonRequest = 16, ExtendedRequest = 23, ExtendedResponse = 24, IntermediateResponse = 25, NONE = 255 //SAMMUEL (not in protocol - never use it!) } public enum LdapResult : byte { success = 0, operationError = 1, protocolError = 2, timeLimitExceeded = 3, sizeLimitExceeded = 4, compareFalse = 5, compareTrue = 6, authMethodNotSupported = 7, strongerAuthRequired = 8, // 9 reserved -- referral = 10, adminLimitExceeded = 11, unavailableCriticalExtension = 12, confidentialityRequired = 13, saslBindInProgress = 14, noSuchAttribute = 16, undefinedAttributeType = 17, inappropriateMatching = 18, constraintViolation = 19, attributeOrValueExists = 20, invalidAttributeSyntax = 21, // 22-31 unused -- noSuchObject = 32, aliasProblem = 33, invalidDNSyntax = 34, // 35 reserved for undefined isLeaf -- aliasDereferencingProblem = 36, // 37-47 unused -- inappropriateAuthentication = 48, invalidCredentials = 49, insufficientAccessRights = 50, busy = 51, unavailable = 52, unwillingToPerform = 53, loopDetect = 54, // 55-63 unused -- namingViolation = 64, objectClassViolation = 65, notAllowedOnNonLeaf = 66, notAllowedOnRDN = 67, entryAlreadyExists = 68, objectClassModsProhibited = 69, // 70 reserved for CLDAP -- affectsMultipleDSAs = 71, // 72-79 unused -- other = 80 } public enum TagClass : byte { Universal = 0, Application = 1, Context = 2, Private = 3 } public enum UniversalDataType : byte { EndOfContent = 0, Boolean = 1, Integer = 2, BitString = 3, OctetString = 4, Null = 5, ObjectIdentifier = 6, ObjectDescriptor = 7, External = 8, Real = 9, Enumerated = 10, EmbeddedPDV = 11, UTF8String = 12, Relative = 13, Reserved = 14, Reserved2 = 15, Sequence = 16, Set = 17, NumericString = 18, PrintableString = 19, T61String = 20, VideotexString = 21, IA5String = 22, UTCTime = 23, GeneralizedTime = 24, GraphicString = 25, VisibleString = 26, GeneralString = 27, UniversalString = 28, CharacterString = 29, BMPString = 30, NONE = 255 //SAMMUEL (not in protocol - never use it!) } internal enum Scope : byte { baseObject = 0, singleLevel = 1, wholeSubtree = 2 } public class Tag { public byte TagByte { get; internal set; } public LCore.TagClass Class { get { return (LCore.TagClass)(this.TagByte >> 6); } } public LCore.UniversalDataType DataType { get { return this.Class == LCore.TagClass.Universal ? (LCore.UniversalDataType)(this.TagByte & 31) : LCore.UniversalDataType.NONE; } } public LCore.LdapOperation LdapOperation { get { return this.Class == LCore.TagClass.Application ? (LCore.LdapOperation)(this.TagByte & 31) : LCore.LdapOperation.NONE; } } public byte? ContextType { get { return this.Class == LCore.TagClass.Context ? (byte?)(this.TagByte & 31) : null; } } public static LCore.Tag Parse(byte tagByte) { return new LCore.Tag { TagByte = tagByte }; } public override string ToString() { return "Tag[class=" + this.Class.ToString() + ",datatype=" + this.DataType.ToString() + ",ldapoperation=" + this.LdapOperation.ToString() + ",contexttype=" + (this.ContextType == null ? "NULL" : ((LCore.LdapFilterChoice)this.ContextType).ToString()) + "]"; } public bool IsConstructed { get { return new SysCll.BitArray(new byte[] { this.TagByte }).Get(5); } set { SysCll.BitArray foo = new SysCll.BitArray(new byte[] { this.TagByte }); foo.Set(5, value); byte[] temp = new byte[1]; foo.CopyTo(temp, 0); this.TagByte = temp[0]; } } private Tag() { /* NOTHING */ } public Tag(LCore.LdapOperation operation) { TagByte = (byte)((byte)operation + ((byte)LCore.TagClass.Application << 6)); } public Tag(LCore.UniversalDataType dataType) { TagByte = (byte)(dataType + ((byte)LCore.TagClass.Universal << 6)); } public Tag(byte context) { TagByte = (byte)(context + ((byte)LCore.TagClass.Context << 6)); } } public class LdapAttribute : Sys.IDisposable { private LCore.Tag _tag; internal byte[] Value = new byte[0]; public SysClG.List<LCore.LdapAttribute> ChildAttributes = new SysClG.List<LCore.LdapAttribute>(); public LCore.TagClass Class { get { return this._tag.Class; } } public bool IsConstructed { get { return (this._tag.IsConstructed || this.ChildAttributes.Count > 0); } } public LCore.LdapOperation LdapOperation { get { return this._tag.LdapOperation; } } public LCore.UniversalDataType DataType { get { return this._tag.DataType; } } public byte? ContextType { get { return this._tag.ContextType; } } public object GetValue() { if (this._tag.Class == LCore.TagClass.Universal) { switch (this._tag.DataType) { case LCore.UniversalDataType.Boolean: return Sys.BitConverter.ToBoolean(this.Value, 0); case LCore.UniversalDataType.Integer: byte[] intbytes = new byte[4]; Sys.Buffer.BlockCopy(this.Value, 0, intbytes, 4 - this.Value.Length, this.Value.Length); Sys.Array.Reverse(intbytes); return Sys.BitConverter.ToInt32(intbytes, 0); default: return SysTxt.Encoding.UTF8.GetString(this.Value, 0, this.Value.Length); } } return SysTxt.Encoding.UTF8.GetString(Value, 0, Value.Length); } private byte[] GetBytes(object val) { if (val == null) { return new byte[0]; } else { Sys.Type typeOFval = val.GetType(); if (typeOFval == typeof(string)) { return SysTxt.Encoding.UTF8.GetBytes(val as string); } else if (typeOFval == typeof(int)) { return LCore.Utils.Reverse<byte>(Sys.BitConverter.GetBytes((int)val)); } else if (typeOFval == typeof(byte)) { return new byte[] { (byte)val }; } else if (typeOFval == typeof(bool)) { return Sys.BitConverter.GetBytes((bool)val); } else if (typeOFval == typeof(byte[])) { return (val as byte[]); } else { throw new Sys.InvalidOperationException("Nothing found for " + typeOFval); } } } public override string ToString() { return this._tag.ToString() + ",Value={" + ((this.Value == null || this.Value.Length == 0) ? "\"\"" : (this.Value.Length == 1 ? this.Value[0].ToString() : SysTxt.Encoding.UTF8.GetString(this.Value))) + "},attr=" + this.ChildAttributes.Count.ToString(); } public T GetValue<T>() { return (T)SysConv.ChangeType(this.GetValue(), typeof(T)); } public byte[] GetBytes() { SysClG.List<byte> contentBytes = new SysClG.List<byte>(); if (ChildAttributes.Count > 0) { this._tag.IsConstructed = true; foreach (LCore.LdapAttribute attr in this.ChildAttributes) { contentBytes.AddRange(attr.GetBytes()); } } else { contentBytes.AddRange(Value); } SysClG.List<byte> ret = new System.Collections.Generic.List<byte>(1); ret.Add(this._tag.TagByte); ret.AddRange(LCore.Utils.IntToBerLength(contentBytes.Count)); ret.Capacity += contentBytes.Count; ret.AddRange(contentBytes); contentBytes.Clear(); contentBytes = null; return ret.ToArray(); } public virtual void Dispose() { this.Value = null; foreach (LCore.LdapAttribute attr in this.ChildAttributes) { attr.Dispose(); } this.ChildAttributes.Clear(); } protected static SysClG.List<LCore.LdapAttribute> ParseAttributes(byte[] bytes, int currentPosition, int length) { SysClG.List<LCore.LdapAttribute> list = new SysClG.List<LCore.LdapAttribute>(); while (currentPosition < length) { LCore.Tag tag = LCore.Tag.Parse(bytes[currentPosition]); currentPosition++; int i = 0; int attributeLength = LCore.Utils.BerLengthToInt(bytes, currentPosition, out i); currentPosition += i; LCore.LdapAttribute attribute = new LCore.LdapAttribute(tag); if (tag.IsConstructed && attributeLength > 0) { attribute.ChildAttributes = ParseAttributes(bytes, currentPosition, currentPosition + attributeLength); } else { attribute.Value = new byte[attributeLength]; Sys.Buffer.BlockCopy(bytes, currentPosition, attribute.Value, 0, attributeLength); } list.Add(attribute); currentPosition += attributeLength; } return list; } protected LdapAttribute(LCore.Tag tag) { this._tag = tag; } public LdapAttribute(LCore.LdapOperation operation) { this._tag = new LCore.Tag(operation); } public LdapAttribute(LCore.LdapOperation operation, object value) : this(operation) { this.Value = this.GetBytes(value); } public LdapAttribute(LCore.UniversalDataType dataType) { this._tag = new LCore.Tag(dataType); } public LdapAttribute(LCore.UniversalDataType dataType, object value) : this(dataType) { this.Value = this.GetBytes(value); } public LdapAttribute(byte contextType) { this._tag = new LCore.Tag(contextType); } public LdapAttribute(byte contextType, object value) : this(contextType) { this.Value = this.GetBytes(value); } } public class LdapResultAttribute : LCore.LdapAttribute { public LdapResultAttribute(LCore.LdapOperation operation, LCore.LdapResult result, string matchedDN = "", string diagnosticMessage = "") : base(operation) { this.ChildAttributes.Add(new LCore.LdapAttribute(LCore.UniversalDataType.Enumerated, (byte)result)); this.ChildAttributes.Add(string.IsNullOrEmpty(matchedDN) ? new LCore.LdapAttribute(LCore.UniversalDataType.OctetString, false) : new LCore.LdapAttribute(LCore.UniversalDataType.OctetString, matchedDN)); this.ChildAttributes.Add(string.IsNullOrEmpty(diagnosticMessage) ? new LCore.LdapAttribute(LCore.UniversalDataType.OctetString, false) : new LCore.LdapAttribute(LCore.UniversalDataType.OctetString, diagnosticMessage)); } } public class LdapPacket : LCore.LdapAttribute { public int MessageId { get { return this.ChildAttributes[0].GetValue<int>(); } } public static LCore.LdapPacket ParsePacket(byte[] bytes) { LCore.LdapPacket packet = new LCore.LdapPacket(LCore.Tag.Parse(bytes[0])); int lengthBytesCount = 0; int contentLength = LCore.Utils.BerLengthToInt(bytes, 1, out lengthBytesCount); packet.ChildAttributes.AddRange(LCore.LdapAttribute.ParseAttributes(bytes, 1 + lengthBytesCount, contentLength)); return packet; } public static bool TryParsePacket(Sys.IO.Stream stream, out LCore.LdapPacket packet) { try { if (stream.CanRead) { byte[] tagByte = new byte[1]; int i = stream.Read(tagByte, 0, 1); if (i != 0) { int n = 0; int contentLength = LCore.Utils.BerLengthToInt(stream, out n); byte[] contentBytes = new byte[contentLength]; stream.Read(contentBytes, 0, contentLength); packet = new LCore.LdapPacket(LCore.Tag.Parse(tagByte[0])); packet.ChildAttributes.AddRange(LCore.LdapAttribute.ParseAttributes(contentBytes, 0, contentLength)); return true; } } } catch { /* NOTHING */ } packet = null; return false; } private LdapPacket(LCore.Tag tag) : base(tag) { /* NOTHING */ } public LdapPacket(int messageId) : base(LCore.UniversalDataType.Sequence) { this.ChildAttributes.Add(new LCore.LdapAttribute(LCore.UniversalDataType.Integer, messageId)); } } } internal struct SearchKey { internal string Key; internal string[] Values; internal SearchKey(string Key, string[] Values) : this() { this.Key = Key; this.Values = Values; } internal SearchKey(string Key, string Value) : this(Key, new string[] { Value }) { /* NOTHING */ } } internal struct SearchValue { internal string[] Keys; internal string Value; internal SearchValue(string[] Keys, string Value) : this() { this.Keys = Keys; this.Value = Value; } internal SearchValue(string Key, string Value) : this(new string[] { Key }, Value) { /* NOTHING */ } } internal class SearchCondition { internal LCore.LdapFilterChoice Filter = LCore.LdapFilterChoice.or; internal SysClG.List<LDap.SearchKey> Keys = new SysClG.List<LDap.SearchKey>(30); } public class Company { public string Name { get; set; } public string Phone { get; set; } public string Country { get; set; } public string State { get; set; } public string City { get; set; } public string PostCode { get; set; } public string Address { get; set; } } public interface IDataList { SysClG.IEnumerable<LDap.IUserData> ListUsers(); SysClG.IEnumerable<LDap.IGroup> ListGroups(); } public interface INamed { string Name { get; } } public interface IGroup : LDap.IDataList, LDap.INamed { string BuildCN(); } public class Domain { protected LDap.IDataSource Source; public LDap.Company Company { get; set; } private string dc; private string pc; public string DomainCommon { get { return this.dc; } set { this.dc = (value == null ? "com" : value.ToLower()); } } public override string ToString() { return ("dc=" + this.NormalizedDC + ",dc=" + this.DomainCommon); } public string NormalizedDC { get { if (this.pc == null) { this.pc = (this.Company == null ? "null" : this.Company.Name.Replace(' ', '.').Replace('\t', '.').Replace(';', '.').ToLower()); if (this.pc.EndsWith(".")) { this.pc = this.pc.Substring(0, (this.pc.Length - 1)); } } return this.pc; } } public Domain(LDap.IDataSource Source) { this.Source = Source; this.dc = "com"; } } public interface IUserData : LDap.INamed { long UserID { get; } string FirstName { get; } string LastName { get; } string FullName { get; } string EMail { get; } LDap.IGroup Department { get; } string Job { get; } string Mobile { get; } bool TestPassword(string Password); } public interface IDataSource : LDap.IGroup { string AdminUser { get; } string AdminPassword { get; } LDap.Domain Domain { get; } bool Validate(string UserName, string Password, out bool IsAdmin); } public class Server : LServ.IServer //https://github.com/vforteli/Flexinets.Ldap.Server/blob/master/LdapServer.cs | https://docs.iredmail.org/use.openldap.as.address.book.in.outlook.html { public const int StandardPort = 389; public const string AccountClass = "SAMAccount"; protected const string PosixAccountClass = "posixAccount"; protected const string GroupAccountClass = "organizationalUnit"; private SysSock.TcpListener _server; private bool _running; bool LServ.IServer.IsStarted { get { return this._running; } } private LDap.IDataSource _source; public LDap.IDataSource Source { get { return this._source; } } private bool IsValidType(ref string type) { return (type.ToLower() == "objectclass" || type == "top" || type == LDap.Server.AccountClass || type == LDap.Server.PosixAccountClass || type == LDap.Server.GroupAccountClass); } private LDap.SearchValue GetCompare(LDap.SearchValue[] pack, LDap.SearchKey key) { foreach (LDap.SearchValue val in pack) { foreach (string valKey in val.Keys) { if (valKey == key.Key) { return val; } } } return default(LDap.SearchValue); } private bool IsBind(LCore.LdapAttribute attr) { return (attr.LdapOperation == LCore.LdapOperation.BindRequest); } private bool IsSearch(LCore.LdapAttribute attr) { return (attr.LdapOperation == LCore.LdapOperation.SearchRequest); } private bool IsDisconnect(LCore.LdapAttribute attr) { return (attr.LdapOperation == LCore.LdapOperation.UnbindRequest || attr.LdapOperation == LCore.LdapOperation.AbandonRequest); } private string BuildCN(string AttributeSG, LDap.INamed named, LDap.IGroup Source) { return (AttributeSG + "=" + named.Name + "," + Source.BuildCN()); } private void WriteAttributes(byte[] pkB, SysSock.NetworkStream stream) { stream.Write(pkB, 0, pkB.Length); } private void WriteAttributes(LCore.LdapAttribute attr, SysSock.NetworkStream stream) { this.WriteAttributes(attr.GetBytes(), stream); } private LDap.IGroup FindGroup(string NormalizedNAME, LDap.IGroup Source) { foreach (LDap.IGroup grp in Source.ListGroups()) { if (grp.Name == NormalizedNAME) { return grp; } } return null; } #if DEBUG private string LogThread() { return "{Thread;" + Sys.Threading.Thread.CurrentContext.ContextID.ToString() + ";" + Sys.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "}"; } private string LogDate() { return Sys.DateTime.Now.ToString(LServ.ServiceInstaller.LogDateFormat, Sys.Globalization.CultureInfo.InvariantCulture); } private void LogPacket(LCore.LdapAttribute pkO, int ident) { if (ident == 0) { Sys.Console.WriteLine("----------BEGIN----------"); } Sys.Console.WriteLine(new string('.', (3 + ident)) + " " + pkO.ToString()); foreach (LCore.LdapAttribute pkI in pkO.ChildAttributes) { this.LogPacket(pkI, (ident + 1)); } if (ident == 0) { Sys.Console.WriteLine("-----------END-----------"); } } #endif private int Matched(LDap.SearchValue[] pack, LDap.SearchKey key) { LDap.SearchValue comp = this.GetCompare(pack, key); if (comp.Keys == null || comp.Keys.Length == 0) { return -1; } else if (key.Values == null || key.Values.Length == 0 || (key.Values.Length == 1 && (key.Values[0] == "*" || key.Values[0] == ""))) { return 2; } else { int m = 0; foreach (string kv in key.Values) { if (comp.Value != null && comp.Value.IndexOf(kv, 0, Sys.StringComparison.CurrentCultureIgnoreCase) > -1) { m++; break; } } if (m == key.Values.Length) { m = 2; } else if (m > 0) { m = 1; } return m; } } public void Stop() { if (this._server != null) { this._server.Stop(); } this._running = false; } void Sys.IDisposable.Dispose() { this.Stop(); this._server = null; this._running = false; } public void Start() { this._server.Start(); this._running = true; this._server.BeginAcceptTcpClient(this.OnClientConnect, null); } private void AddAttribute(LCore.LdapAttribute partialAttributeList, string AttributeName, string AttributeValue) { if (!string.IsNullOrEmpty(AttributeValue)) { LCore.LdapAttribute partialAttr = new LCore.LdapAttribute(LCore.UniversalDataType.Sequence); partialAttr.ChildAttributes.Add(new LCore.LdapAttribute(LCore.UniversalDataType.OctetString, AttributeName)); LCore.LdapAttribute partialAttrVals = new LCore.LdapAttribute(LCore.UniversalDataType.Set); partialAttrVals.ChildAttributes.Add(new LCore.LdapAttribute(LCore.UniversalDataType.OctetString, AttributeValue)); partialAttr.ChildAttributes.Add(partialAttrVals); partialAttributeList.ChildAttributes.Add(partialAttr); } } private void BuildPack(LCore.LdapAttribute holder, LDap.SearchValue[] pack) { LCore.LdapAttribute partialAttributeList = new LCore.LdapAttribute(LCore.UniversalDataType.Sequence); foreach (LDap.SearchValue pkItem in pack) { foreach (string Key in pkItem.Keys) { this.AddAttribute(partialAttributeList, Key, pkItem.Value); } } holder.ChildAttributes.Add(partialAttributeList); } private LDap.SearchValue[] UserPack(LDap.IUserData user) { LDap.SearchValue[] pk = new LDap.SearchValue[20]; pk[0] = new LDap.SearchValue(new string[] { "cn", "commonName" }, user.Name); pk[1] = new LDap.SearchValue(new string[] { "uid", "id" }, user.UserID.ToString()); pk[2] = new LDap.SearchValue(new string[] { "mail" }, user.EMail); pk[3] = new LDap.SearchValue(new string[] { "displayname", "display-name", "mailNickname", "mozillaNickname" }, user.FullName); pk[4] = new LDap.SearchValue(new string[] { "givenName" }, user.FirstName); pk[5] = new LDap.SearchValue(new string[] { "sn", "surname" }, user.LastName); pk[6] = new LDap.SearchValue(new string[] { "ou", "department" }, user.Department.Name); pk[7] = new LDap.SearchValue(new string[] { "co", "countryname" }, this._source.Domain.Company.Country); pk[8] = new LDap.SearchValue(new string[] { "postalAddress", "streetaddress" }, this._source.Domain.Company.Address); pk[9] = new LDap.SearchValue(new string[] { "company", "organizationName", "organizationUnitName" }, this._source.Domain.Company.Name); pk[10] = new LDap.SearchValue(new string[] { "objectClass" }, LDap.Server.AccountClass); pk[11] = new LDap.SearchValue(new string[] { "objectClass" }, LDap.Server.PosixAccountClass); pk[12] = new LDap.SearchValue(new string[] { "objectClass" }, "top"); pk[13] = new LDap.SearchValue(new string[] { "title", "roleOccupant" }, user.Job); pk[14] = new LDap.SearchValue(new string[] { "telephoneNumber" }, this._source.Domain.Company.Phone); pk[15] = new LDap.SearchValue(new string[] { "l" }, this._source.Domain.Company.City); pk[16] = new LDap.SearchValue(new string[] { "st" }, this._source.Domain.Company.State); pk[17] = new LDap.SearchValue(new string[] { "postalCode" }, this._source.Domain.Company.PostCode); pk[18] = new LDap.SearchValue(new string[] { "mobile" }, user.Mobile); pk[19] = new LDap.SearchValue(new string[] { "initials" }, ((!string.IsNullOrEmpty(user.FirstName) && !string.IsNullOrEmpty(user.LastName)) ? (user.FirstName.Substring(0, 1) + user.LastName.Substring(0, 1)) : string.Empty)); return pk; } private LDap.SearchValue[] GroupPack(LDap.IGroup grp) { LDap.SearchValue[] pk = new LDap.SearchValue[3]; pk[0] = new LDap.SearchValue(new string[] { "ou", "organizationalUnitName", "cn", "commonName" }, grp.Name); pk[1] = new LDap.SearchValue(new string[] { "objectclass" }, LDap.Server.GroupAccountClass); pk[2] = new LDap.SearchValue(new string[] { "objectclass" }, "top"); return pk; } private LCore.LdapPacket RespondCN(string CN, LDap.SearchValue[] pack, int MessageID) { LCore.LdapAttribute searchResultEntry = new LCore.LdapAttribute(LCore.LdapOperation.SearchResultEntry); searchResultEntry.ChildAttributes.Add(new LCore.LdapAttribute(LCore.UniversalDataType.OctetString, CN)); this.BuildPack(searchResultEntry, pack); LCore.LdapPacket response = new LCore.LdapPacket(MessageID); response.ChildAttributes.Add(searchResultEntry); return response; } private void ReturnTrue(SysSock.NetworkStream stream, int MessageID) { LCore.LdapPacket pkO = new LCore.LdapPacket(MessageID); pkO.ChildAttributes.Add(new LCore.LdapAttribute(LCore.UniversalDataType.Boolean, true)); pkO.ChildAttributes.Add(new LCore.LdapAttribute(LCore.UniversalDataType.Sequence)); this.WriteAttributes(pkO, stream); } private void ReturnElements(SysSock.NetworkStream stream, int MessageID, int Limit, LDap.IGroup Source, LCore.Scope Scope) { #if DEBUG Sys.Console.WriteLine(">>>> " + this.LogThread() + "ReturnAllUsers(NetworkStream,int,int) started at " + this.LogDate()); #endif foreach (LDap.IGroup grp in Source.ListGroups()) //'... appliy scope to list subgroups (don't know how yet) { if (Limit > 0) { using (LCore.LdapPacket pkO = this.RespondCN(this.BuildCN("ou", grp, Source), this.GroupPack(grp), MessageID)) { this.WriteAttributes(pkO, stream); } Limit--; } else { break; } } foreach (LDap.IUserData user in Source.ListUsers()) { if (Limit > 0) { using (LCore.LdapPacket pkO = this.RespondCN(this.BuildCN("cn", user, Source), this.UserPack(user), MessageID)) { this.WriteAttributes(pkO, stream); } Limit--; } else { break; } } #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "ReturnAllUsers(NetworkStream,int,int) ended at " + this.LogDate()); #endif } private void ReturnSingleElement(SysSock.NetworkStream stream, int MessageID, ref string Name, LDap.IGroup Source, LCore.Scope Scope, bool IsGroup) { #if DEBUG Sys.Console.WriteLine(">>>> " + this.LogThread() + "ReturnSingleUser(NetworkStream,int,string,bool) started at " + this.LogDate()); #endif if (!string.IsNullOrEmpty(Name)) { Name = Name.ToLower(); if (IsGroup) { LDap.IGroup grp = this.FindGroup(Name, Source); if (grp != null) { using (LCore.LdapPacket pkO = this.RespondCN(this.BuildCN("ou", grp, Source), this.GroupPack(grp), MessageID)) { this.WriteAttributes(pkO, stream); } } } else { foreach (LDap.IUserData user in Source.ListUsers()) { if (user.Name == Name) { using (LCore.LdapPacket pkO = this.RespondCN(this.BuildCN("cn", user, Source), this.UserPack(user), MessageID)) { this.WriteAttributes(pkO, stream); } } } } } } private string ExtractUser(string arg, ref string BindUR, out LDap.IGroup Source, out bool IsGroup) { Source = this._source; IsGroup = false; if (!string.IsNullOrEmpty(arg)) { if (arg == BindUR) { arg = string.Empty; } else { arg = arg.Trim().Replace(BindUR, string.Empty).ToLower(); if (arg.EndsWith(",")) { arg = arg.Substring(0, (arg.Length - 1)); } if (arg.StartsWith("cn=") || arg.StartsWith("ou=") || arg.StartsWith("id=")) { arg = arg.Substring(3); } else if (arg.StartsWith("uid=")) { arg = arg.Substring(4); } int cIDX = arg.LastIndexOf(','); if (cIDX != -1) { string AUX = string.Empty; while (cIDX != -1) { AUX = arg.Substring(cIDX + 1); arg = arg.Substring(0, cIDX); if (AUX.StartsWith("cn=") || AUX.StartsWith("ou=") || AUX.StartsWith("id=")) { AUX = AUX.Substring(3); } else if (AUX.StartsWith("uid=")) { AUX = AUX.Substring(4); } Source = this.FindGroup(AUX, Source); if (Source == null) //FAIL { Source = this._source; arg = string.Empty; break; } else { cIDX = arg.LastIndexOf(','); } } } if (!string.IsNullOrEmpty(arg)) { IsGroup = (this.FindGroup(arg, Source) != null); } } } return arg; } private LDap.SearchCondition GetSearchOptions(LCore.LdapAttribute filter) { LDap.SearchKey cur = new LDap.SearchKey("*", filter.GetValue<string>()); LDap.SearchCondition args = new LDap.SearchCondition(); try { args.Filter = (LCore.LdapFilterChoice)filter.ContextType; if (string.IsNullOrEmpty(cur.Values[0])) { if (filter.ChildAttributes.Count == 1) { filter = filter.ChildAttributes[0]; } if (filter.ChildAttributes.Count > 0) { args.Filter = (LCore.LdapFilterChoice)filter.ContextType; string[] nARG = null; LCore.LdapAttribute varg = null; foreach (LCore.LdapAttribute arg in filter.ChildAttributes) { if (arg.ChildAttributes.Count == 2 && arg.ChildAttributes[0].DataType == LCore.UniversalDataType.OctetString) { cur = new LDap.SearchKey(arg.ChildAttributes[0].GetValue<string>(), (null as string[])); varg = arg.ChildAttributes[1]; if (varg.DataType == LCore.UniversalDataType.OctetString) { cur.Values = new string[] { varg.GetValue<string>() }; } else { nARG = new string[varg.ChildAttributes.Count]; for (int i = 0; i < varg.ChildAttributes.Count; i++) { nARG[i] = varg.ChildAttributes[i].GetValue<string>(); } cur.Values = nARG; nARG = null; } if (!string.IsNullOrEmpty(cur.Key)) { args.Keys.Add(cur); } } } } } else { args.Keys.Add(cur); } } #if DEBUG catch (Sys.Exception e) { args.Keys.Clear(); Sys.Console.WriteLine(">>>>> " + this.LogThread() + "GetSearchOptions(LdapAttribute) error at " + this.LogDate() + ", exception: " + e.Message); } #else catch { args.Keys.Clear(); } #endif return args; } private bool Matched(LDap.SearchValue[] pack, LDap.SearchCondition args) { int mcount = -1; switch (args.Filter) { case LCore.LdapFilterChoice.or: foreach (LDap.SearchKey key in args.Keys) { mcount = this.Matched(pack, key); if (mcount > 0) { return true; } } break; case LCore.LdapFilterChoice.and: bool Matched = true; if (args.Keys.Count == pack.Length) //Since all must match anyway { Matched = true; foreach (LDap.SearchKey key in args.Keys) { mcount = this.Matched(pack, key); if (mcount != 2) { Matched = false; break; } } } return Matched; } return false; } private void ReturnMatchs(SysSock.NetworkStream stream, int MessageID, int Limit, LDap.SearchCondition args, LDap.IGroup Source) { #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "ReturnUsers(NetworkStream,int,int,SearchCondition) started at " + this.LogDate()); #endif LDap.SearchValue[] pack = null; foreach (LDap.IGroup grp in Source.ListGroups()) { if (Limit > 0) { pack = this.GroupPack(grp); if (this.Matched(pack, args)) { using (LCore.LdapPacket pkO = this.RespondCN(this.BuildCN("ou", grp, Source), pack, MessageID)) { this.WriteAttributes(pkO, stream); } Limit--; } } else { break; } } foreach (LDap.IUserData user in Source.ListUsers()) { if (Limit > 0) { pack = this.UserPack(user); if (this.Matched(pack, args)) { using (LCore.LdapPacket pkO = this.RespondCN(this.BuildCN("cn", user, Source), pack, MessageID)) { this.WriteAttributes(pkO, stream); } Limit--; } } else { break; } } #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "ReturnUsers(NetworkStream,int,int,SearchCondition) ended at " + this.LogDate()); #endif } private void ReturnHello(SysSock.NetworkStream stream, int MessageID, LCore.LdapPacket responsePacket, int Limit, LDap.IGroup Source) { #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "ReturnHello(NetworkStream,int,LdapPacket,int) started at " + this.LogDate()); #endif LDap.SearchValue[] pack = new LDap.SearchValue[5]; pack[0] = new LDap.SearchValue("objectclass", "top"); pack[1] = new LDap.SearchValue("objectclass", "dcObject"); pack[2] = new LDap.SearchValue("objectclass", "organization"); pack[3] = new LDap.SearchValue("o", (this._source.Domain.NormalizedDC + "." + this._source.Domain.DomainCommon)); pack[4] = new LDap.SearchValue("dc", this._source.Domain.NormalizedDC); this.WriteAttributes(this.RespondCN(this._source.Domain.ToString(), pack, MessageID), stream); this.ReturnElements(stream, MessageID, Limit, Source, LCore.Scope.baseObject); #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "ReturnHello(NetworkStream,int,LdapPacket,int) ended at " + this.LogDate()); #endif } private void HandleSearchRequest(SysSock.NetworkStream stream, LCore.LdapPacket requestPacket, bool IsAdmin) { #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleSearchRequest(NetworkStream,LdapPacket,bool) started at " + this.LogDate()); this.LogPacket(requestPacket, 0); #endif LCore.LdapAttribute searchRequest = LCore.Utils.SingleOrDefault<LCore.LdapAttribute>(requestPacket.ChildAttributes, this.IsSearch); LCore.LdapPacket responsePacket = new LCore.LdapPacket(requestPacket.MessageId); if (searchRequest == null || searchRequest.ChildAttributes.Count < 7) { responsePacket.ChildAttributes.Add(new LCore.LdapResultAttribute(LCore.LdapOperation.SearchResultDone, LCore.LdapResult.compareFalse)); } else { string arg = string.Empty; LCore.Scope scope = LCore.Scope.baseObject; try { if (searchRequest.ChildAttributes[1].DataType == LCore.UniversalDataType.Integer) { scope = (LCore.Scope)searchRequest.ChildAttributes[1].GetValue<int>(); } else { switch (searchRequest.ChildAttributes[1].Value[0]) { case 1: scope = LCore.Scope.singleLevel; break; case 2: scope = LCore.Scope.wholeSubtree; break; default: scope = LCore.Scope.baseObject; break; } } } catch { /* NOTHING */ } int limit = searchRequest.ChildAttributes[3].GetValue<int>(); if (limit == 0) { limit = 999; } //max on outlook/thunderbird | target clients arg = searchRequest.ChildAttributes[0].GetValue<string>(); if (arg != null) { arg = arg.ToLower(); } LCore.LdapAttribute filter = searchRequest.ChildAttributes[6]; LCore.LdapFilterChoice filterMode = (LCore.LdapFilterChoice)filter.ContextType; string BindUR = this._source.Domain.ToString(); if (arg != null && arg.Contains(BindUR)) { LDap.IGroup Source = null; bool IsGroup = false; arg = this.ExtractUser(arg, ref BindUR, out Source, out IsGroup); switch (filterMode) { case LCore.LdapFilterChoice.equalityMatch: case LCore.LdapFilterChoice.present: if (arg == null || arg == string.Empty) { if (Source == this._source) { this.ReturnHello(stream, requestPacket.MessageId, responsePacket, limit, Source); } else { arg = filter.GetValue<string>(); this.ReturnSingleElement(stream, requestPacket.MessageId, ref arg, Source, scope, IsGroup); } } else if (scope == LCore.Scope.baseObject) { this.ReturnSingleElement(stream, requestPacket.MessageId, ref arg, Source, scope, IsGroup); } else if (IsGroup) { this.ReturnElements(stream, requestPacket.MessageId, limit, this.FindGroup(arg, Source), scope); } break; case LCore.LdapFilterChoice.and: case LCore.LdapFilterChoice.or: if (string.IsNullOrEmpty(arg) || this.IsValidType(ref arg)) { LDap.SearchCondition args = this.GetSearchOptions(filter); if (args.Keys.Count == 0 || args.Keys[0].Key == "*") { this.ReturnElements(stream, requestPacket.MessageId, limit, Source, scope); } else { this.ReturnMatchs(stream, requestPacket.MessageId, limit, args, Source); } } else { this.ReturnSingleElement(stream, requestPacket.MessageId, ref arg, Source, scope, IsGroup); } break; } } else { arg = filter.GetValue<string>(); if (!string.IsNullOrEmpty(arg)) { switch (filterMode) { case LCore.LdapFilterChoice.present: if (this.IsValidType(ref arg)) { this.ReturnTrue(stream, requestPacket.MessageId); } break; default: break; //NOTHING YET! } } } responsePacket.ChildAttributes.Add(new LCore.LdapResultAttribute(LCore.LdapOperation.SearchResultDone, LCore.LdapResult.success)); } #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleSearchRequest(NetworkStream,LdapPacket,bool) done at " + this.LogDate()); #endif this.WriteAttributes(responsePacket, stream); } private bool HandleBindRequest(SysSock.NetworkStream stream, LCore.LdapPacket requestPacket, out bool IsAdmin) { #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleBindRequest(NetworkStream,LdapPacket,out bool) started at " + this.LogDate()); #endif IsAdmin = false; LCore.LdapAttribute bindrequest = LCore.Utils.SingleOrDefault<LCore.LdapAttribute>(requestPacket.ChildAttributes, o => { return o.LdapOperation == LCore.LdapOperation.BindRequest; }); if (bindrequest == null) { #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleBindRequest(NetworkStream,LdapPacket,out bool) completed as FALSE at " + this.LogDate()); #endif return false; } else { LDap.IGroup Source = null; string AUX = this._source.Domain.ToString(); bool IsGroup = false; string username = this.ExtractUser(bindrequest.ChildAttributes[1].GetValue<string>(), ref AUX, out Source, out IsGroup); LCore.LdapResult response = LCore.LdapResult.invalidCredentials; if (!IsGroup) //Groups do not login { AUX = bindrequest.ChildAttributes[2].GetValue<string>(); if (this._source.Validate(username, AUX, out IsAdmin)) { response = LCore.LdapResult.success; } } LCore.LdapPacket responsePacket = new LCore.LdapPacket(requestPacket.MessageId); responsePacket.ChildAttributes.Add(new LCore.LdapResultAttribute(LCore.LdapOperation.BindResponse, response)); this.WriteAttributes(responsePacket, stream); #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleBindRequest(NetworkStream,LdapPacket,out bool) completed with response " + response.ToString() + " at " + this.LogDate()); #endif return (response == LCore.LdapResult.success); } } private void HandleClient(SysSock.TcpClient client) { #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleClient(TcpClient) started at " + this.LogDate()); #endif this._server.BeginAcceptTcpClient(this.OnClientConnect, null); try { bool isBound = false; bool IsAdmin = false; bool nonSearch = true; #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleClient(TcpClient), will call GetStream() at " + this.LogDate()); #endif SysSock.NetworkStream stream = client.GetStream(); #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleClient(TcpClient), GetStream() completed at " + this.LogDate()); long loopCount = 0; #endif LCore.LdapPacket requestPacket = null; while (LCore.LdapPacket.TryParsePacket(stream, out requestPacket)) { #if DEBUG loopCount++; Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleClient(TcpClient), PacketParsed (" + loopCount.ToString() + ") at " + this.LogDate()); #endif if (LCore.Utils.Any<LCore.LdapAttribute>(requestPacket.ChildAttributes, this.IsDisconnect)) { #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleClient(TcpClient), Abandon/Unbind Request received (" + loopCount.ToString() + ") at " + this.LogDate()); #endif break; } else { if (LCore.Utils.Any<LCore.LdapAttribute>(requestPacket.ChildAttributes, this.IsBind)) { isBound = this.HandleBindRequest(stream, requestPacket, out IsAdmin); } if (isBound && LCore.Utils.Any<LCore.LdapAttribute>(requestPacket.ChildAttributes, this.IsSearch)) { nonSearch = false; this.HandleSearchRequest(stream, requestPacket, IsAdmin); } } } #if DEBUG Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleClient(TcpClient), Packet parse completed at " + this.LogDate()); #endif if (nonSearch && (!isBound) && (requestPacket != null)) { LCore.LdapPacket responsePacket = new LCore.LdapPacket(requestPacket.MessageId); responsePacket.ChildAttributes.Add(new LCore.LdapResultAttribute(LCore.LdapOperation.CompareResponse, LCore.LdapResult.compareFalse)); this.WriteAttributes(responsePacket, stream); } #if DEBUG } catch (Sys.Exception e) { Sys.Console.WriteLine(">>> " + this.LogThread() + "HandleClient(TcpClient) error at " + this.LogDate() + ", exception: " + e.Message); } #else } catch { /* NOTHING */ } #endif } private void OnClientConnect(Sys.IAsyncResult asyn) { #if DEBUG Sys.Console.WriteLine(); Sys.Console.WriteLine("> Thread: " + this.LogThread()); Sys.Console.WriteLine(">> " + this.LogThread() + "OnClientConnect(IAsyncResult) called"); #endif try { if (this._server != null) { this.HandleClient(this._server.EndAcceptTcpClient(asyn)); } } #if DEBUG catch (Sys.Exception e) { Sys.Console.WriteLine(">> " + this.LogThread() + "OnClientConnect(IAsyncResult) error at " + this.LogDate() + ", exception: " + e.Message); } Sys.Console.WriteLine(">> " + this.LogThread() + "OnClientConnect(IAsyncResult) ended"); #else catch { /* NOTHING */ } #endif } protected Server(Sys.Net.IPEndPoint localEndpoint) { this._server = new SysSock.TcpListener(localEndpoint); } public Server(LDap.IDataSource Validator, Sys.Net.IPEndPoint localEndpoint) : this(localEndpoint) { this._source = Validator; } public Server(LDap.IDataSource Validator, string localEndpoint, int Port) : this(new Sys.Net.IPEndPoint(Sys.Net.IPAddress.Parse(localEndpoint), Port)) { this._source = Validator; } public Server(LDap.IDataSource Validator, string localEndpoint) : this(Validator, localEndpoint, LDap.Server.StandardPort) { /* NOTHING */ } } }
52.057858
307
0.549878
[ "MIT" ]
Sammuel-Miranda/Flexinets.Ldap.Server
Libs.cs
66,582
C#
// <copyright file="IGherkinBlock.cs" company="Erratic Motion Ltd"> // Copyright (c) Erratic Motion Ltd. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> namespace ErraticMotion.Test.Tools.Gherkin { using System.Collections.Generic; /// <summary> /// Represents a Gherkin block element that contains a collection of steps and comments. /// </summary> public interface IGherkinBlock : IGherkinKeyword, IGherkin { /// <summary> /// Gets the Gherkin steps for this scenario. /// </summary> IGherkinBlockSteps Steps { get; } /// <summary> /// Gets a collection of Gherkin Comments belonging to this feature. /// </summary> IList<IGherkinComment> Comments { get; } } }
33.96
101
0.6596
[ "MIT" ]
erraticmotion/gherkin-net
Gherkin.Net/Gherkin/Test/Tools/Gherkin/IGherkinBlock.cs
851
C#
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.ComponentModel; namespace Moq { static partial class MockExtensions { /// <summary> /// Resets all invocations recorded for this mock. /// </summary> /// <param name="mock">The mock whose recorded invocations should be reset.</param> [Obsolete("Use `mock.Invocations.Clear()` instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ResetCalls(this Mock mock) => mock.Invocations.Clear(); } }
31.05
85
0.7343
[ "BSD-3-Clause" ]
Damian-Pumar/moq4
src/Moq/Obsolete/MockExtensions.cs
621
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Planilo { /// <summary>Class for a AI graph blackboard.</summary> public class AIBlackboard : ScriptableObject { /// <summary>A serializable dictionary for the blackboard data.</summary> [System.Serializable] public class AIBlackboardDictionary : SerializableDictionary<string, object> { } /// <summary>A reference to the blackboard dictionary.</summary> [SerializeField] public AIBlackboardDictionary variables = new AIBlackboardDictionary(); } }
30.5
96
0.721311
[ "MIT" ]
adambrownmpvr/planilo
Blackboard/Base/AIBlackboard.cs
610
C#
using Up.NET.Models; namespace Up.NET.Api.Accounts; public class AccountTransactions { public RelatedLink Links { get; set; } }
16.75
42
0.738806
[ "MIT" ]
Hona/Up.NET
Up.NET/Api/Accounts/AccountTransactions.cs
136
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the polly-2016-06-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Net; using Amazon.Polly.Model; using Amazon.Polly.Model.Internal.MarshallTransformations; using Amazon.Polly.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.Polly { /// <summary> /// Implementation for accessing Polly /// /// Amazon Polly is a web service that makes it easy to synthesize speech from text. /// /// /// <para> /// The Amazon Polly service provides API operations for synthesizing high-quality speech /// from plain text and Speech Synthesis Markup Language (SSML), along with managing pronunciations /// lexicons that enable you to get the best results for your application domain. /// </para> /// </summary> public partial class AmazonPollyClient : AmazonServiceClient, IAmazonPolly { private static IServiceMetadata serviceMetadata = new AmazonPollyMetadata(); #if BCL45 || AWS_ASYNC_ENUMERABLES_API private IPollyPaginatorFactory _paginators; /// <summary> /// Paginators for the service /// </summary> public IPollyPaginatorFactory Paginators { get { if (this._paginators == null) { this._paginators = new PollyPaginatorFactory(this); } return this._paginators; } } #endif #region Constructors /// <summary> /// Constructs AmazonPollyClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonPollyClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonPollyConfig()) { } /// <summary> /// Constructs AmazonPollyClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonPollyClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonPollyConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonPollyClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonPollyClient Configuration Object</param> public AmazonPollyClient(AmazonPollyConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonPollyClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonPollyClient(AWSCredentials credentials) : this(credentials, new AmazonPollyConfig()) { } /// <summary> /// Constructs AmazonPollyClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonPollyClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonPollyConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonPollyClient with AWS Credentials and an /// AmazonPollyClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonPollyClient Configuration Object</param> public AmazonPollyClient(AWSCredentials credentials, AmazonPollyConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonPollyClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonPollyClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonPollyConfig()) { } /// <summary> /// Constructs AmazonPollyClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonPollyClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonPollyConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonPollyClient with AWS Access Key ID, AWS Secret Key and an /// AmazonPollyClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonPollyClient Configuration Object</param> public AmazonPollyClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonPollyConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonPollyClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonPollyClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonPollyConfig()) { } /// <summary> /// Constructs AmazonPollyClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonPollyClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonPollyConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonPollyClient with AWS Access Key ID, AWS Secret Key and an /// AmazonPollyClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonPollyClient Configuration Object</param> public AmazonPollyClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonPollyConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } /// <summary> /// Capture metadata for the service. /// </summary> protected override IServiceMetadata ServiceMetadata { get { return serviceMetadata; } } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region DeleteLexicon /// <summary> /// Deletes the specified pronunciation lexicon stored in an Amazon Web Services Region. /// A lexicon which has been deleted is not available for speech synthesis, nor is it /// possible to retrieve it using either the <code>GetLexicon</code> or <code>ListLexicon</code> /// APIs. /// /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/polly/latest/dg/managing-lexicons.html">Managing /// Lexicons</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteLexicon service method.</param> /// /// <returns>The response from the DeleteLexicon service method, as returned by Polly.</returns> /// <exception cref="Amazon.Polly.Model.LexiconNotFoundException"> /// Amazon Polly can't find the specified lexicon. This could be caused by a lexicon that /// is missing, its name is misspelled or specifying a lexicon that is in a different /// region. /// /// /// <para> /// Verify that the lexicon exists, is in the region (see <a>ListLexicons</a>) and that /// you spelled its name is spelled correctly. Then try again. /// </para> /// </exception> /// <exception cref="Amazon.Polly.Model.ServiceFailureException"> /// An unknown condition has caused a service failure. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/DeleteLexicon">REST API Reference for DeleteLexicon Operation</seealso> public virtual DeleteLexiconResponse DeleteLexicon(DeleteLexiconRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteLexiconRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteLexiconResponseUnmarshaller.Instance; return Invoke<DeleteLexiconResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteLexicon operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteLexicon operation on AmazonPollyClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteLexicon /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/DeleteLexicon">REST API Reference for DeleteLexicon Operation</seealso> public virtual IAsyncResult BeginDeleteLexicon(DeleteLexiconRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteLexiconRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteLexiconResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteLexicon operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLexicon.</param> /// /// <returns>Returns a DeleteLexiconResult from Polly.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/DeleteLexicon">REST API Reference for DeleteLexicon Operation</seealso> public virtual DeleteLexiconResponse EndDeleteLexicon(IAsyncResult asyncResult) { return EndInvoke<DeleteLexiconResponse>(asyncResult); } #endregion #region DescribeVoices /// <summary> /// Returns the list of voices that are available for use when requesting speech synthesis. /// Each voice speaks a specified language, is either male or female, and is identified /// by an ID, which is the ASCII version of the voice name. /// /// /// <para> /// When synthesizing speech ( <code>SynthesizeSpeech</code> ), you provide the voice /// ID for the voice you want from the list of voices returned by <code>DescribeVoices</code>. /// </para> /// /// <para> /// For example, you want your news reader application to read news in a specific language, /// but giving a user the option to choose the voice. Using the <code>DescribeVoices</code> /// operation you can provide the user with a list of available voices to select from. /// </para> /// /// <para> /// You can optionally specify a language code to filter the available voices. For example, /// if you specify <code>en-US</code>, the operation returns a list of all available US /// English voices. /// </para> /// /// <para> /// This operation requires permissions to perform the <code>polly:DescribeVoices</code> /// action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeVoices service method.</param> /// /// <returns>The response from the DescribeVoices service method, as returned by Polly.</returns> /// <exception cref="Amazon.Polly.Model.InvalidNextTokenException"> /// The NextToken is invalid. Verify that it's spelled correctly, and then try again. /// </exception> /// <exception cref="Amazon.Polly.Model.ServiceFailureException"> /// An unknown condition has caused a service failure. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/DescribeVoices">REST API Reference for DescribeVoices Operation</seealso> public virtual DescribeVoicesResponse DescribeVoices(DescribeVoicesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeVoicesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeVoicesResponseUnmarshaller.Instance; return Invoke<DescribeVoicesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeVoices operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeVoices operation on AmazonPollyClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeVoices /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/DescribeVoices">REST API Reference for DescribeVoices Operation</seealso> public virtual IAsyncResult BeginDescribeVoices(DescribeVoicesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeVoicesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeVoicesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeVoices operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeVoices.</param> /// /// <returns>Returns a DescribeVoicesResult from Polly.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/DescribeVoices">REST API Reference for DescribeVoices Operation</seealso> public virtual DescribeVoicesResponse EndDescribeVoices(IAsyncResult asyncResult) { return EndInvoke<DescribeVoicesResponse>(asyncResult); } #endregion #region GetLexicon /// <summary> /// Returns the content of the specified pronunciation lexicon stored in an Amazon Web /// Services Region. For more information, see <a href="https://docs.aws.amazon.com/polly/latest/dg/managing-lexicons.html">Managing /// Lexicons</a>. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetLexicon service method.</param> /// /// <returns>The response from the GetLexicon service method, as returned by Polly.</returns> /// <exception cref="Amazon.Polly.Model.LexiconNotFoundException"> /// Amazon Polly can't find the specified lexicon. This could be caused by a lexicon that /// is missing, its name is misspelled or specifying a lexicon that is in a different /// region. /// /// /// <para> /// Verify that the lexicon exists, is in the region (see <a>ListLexicons</a>) and that /// you spelled its name is spelled correctly. Then try again. /// </para> /// </exception> /// <exception cref="Amazon.Polly.Model.ServiceFailureException"> /// An unknown condition has caused a service failure. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/GetLexicon">REST API Reference for GetLexicon Operation</seealso> public virtual GetLexiconResponse GetLexicon(GetLexiconRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetLexiconRequestMarshaller.Instance; options.ResponseUnmarshaller = GetLexiconResponseUnmarshaller.Instance; return Invoke<GetLexiconResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetLexicon operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetLexicon operation on AmazonPollyClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetLexicon /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/GetLexicon">REST API Reference for GetLexicon Operation</seealso> public virtual IAsyncResult BeginGetLexicon(GetLexiconRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetLexiconRequestMarshaller.Instance; options.ResponseUnmarshaller = GetLexiconResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetLexicon operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetLexicon.</param> /// /// <returns>Returns a GetLexiconResult from Polly.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/GetLexicon">REST API Reference for GetLexicon Operation</seealso> public virtual GetLexiconResponse EndGetLexicon(IAsyncResult asyncResult) { return EndInvoke<GetLexiconResponse>(asyncResult); } #endregion #region GetSpeechSynthesisTask /// <summary> /// Retrieves a specific SpeechSynthesisTask object based on its TaskID. This object contains /// information about the given speech synthesis task, including the status of the task, /// and a link to the S3 bucket containing the output of the task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetSpeechSynthesisTask service method.</param> /// /// <returns>The response from the GetSpeechSynthesisTask service method, as returned by Polly.</returns> /// <exception cref="Amazon.Polly.Model.InvalidTaskIdException"> /// The provided Task ID is not valid. Please provide a valid Task ID and try again. /// </exception> /// <exception cref="Amazon.Polly.Model.ServiceFailureException"> /// An unknown condition has caused a service failure. /// </exception> /// <exception cref="Amazon.Polly.Model.SynthesisTaskNotFoundException"> /// The Speech Synthesis task with requested Task ID cannot be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/GetSpeechSynthesisTask">REST API Reference for GetSpeechSynthesisTask Operation</seealso> public virtual GetSpeechSynthesisTaskResponse GetSpeechSynthesisTask(GetSpeechSynthesisTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetSpeechSynthesisTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = GetSpeechSynthesisTaskResponseUnmarshaller.Instance; return Invoke<GetSpeechSynthesisTaskResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetSpeechSynthesisTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSpeechSynthesisTask operation on AmazonPollyClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetSpeechSynthesisTask /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/GetSpeechSynthesisTask">REST API Reference for GetSpeechSynthesisTask Operation</seealso> public virtual IAsyncResult BeginGetSpeechSynthesisTask(GetSpeechSynthesisTaskRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetSpeechSynthesisTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = GetSpeechSynthesisTaskResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetSpeechSynthesisTask operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetSpeechSynthesisTask.</param> /// /// <returns>Returns a GetSpeechSynthesisTaskResult from Polly.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/GetSpeechSynthesisTask">REST API Reference for GetSpeechSynthesisTask Operation</seealso> public virtual GetSpeechSynthesisTaskResponse EndGetSpeechSynthesisTask(IAsyncResult asyncResult) { return EndInvoke<GetSpeechSynthesisTaskResponse>(asyncResult); } #endregion #region ListLexicons /// <summary> /// Returns a list of pronunciation lexicons stored in an Amazon Web Services Region. /// For more information, see <a href="https://docs.aws.amazon.com/polly/latest/dg/managing-lexicons.html">Managing /// Lexicons</a>. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListLexicons service method.</param> /// /// <returns>The response from the ListLexicons service method, as returned by Polly.</returns> /// <exception cref="Amazon.Polly.Model.InvalidNextTokenException"> /// The NextToken is invalid. Verify that it's spelled correctly, and then try again. /// </exception> /// <exception cref="Amazon.Polly.Model.ServiceFailureException"> /// An unknown condition has caused a service failure. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/ListLexicons">REST API Reference for ListLexicons Operation</seealso> public virtual ListLexiconsResponse ListLexicons(ListLexiconsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListLexiconsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListLexiconsResponseUnmarshaller.Instance; return Invoke<ListLexiconsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListLexicons operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListLexicons operation on AmazonPollyClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListLexicons /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/ListLexicons">REST API Reference for ListLexicons Operation</seealso> public virtual IAsyncResult BeginListLexicons(ListLexiconsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListLexiconsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListLexiconsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListLexicons operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListLexicons.</param> /// /// <returns>Returns a ListLexiconsResult from Polly.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/ListLexicons">REST API Reference for ListLexicons Operation</seealso> public virtual ListLexiconsResponse EndListLexicons(IAsyncResult asyncResult) { return EndInvoke<ListLexiconsResponse>(asyncResult); } #endregion #region ListSpeechSynthesisTasks /// <summary> /// Returns a list of SpeechSynthesisTask objects ordered by their creation date. This /// operation can filter the tasks by their status, for example, allowing users to list /// only tasks that are completed. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListSpeechSynthesisTasks service method.</param> /// /// <returns>The response from the ListSpeechSynthesisTasks service method, as returned by Polly.</returns> /// <exception cref="Amazon.Polly.Model.InvalidNextTokenException"> /// The NextToken is invalid. Verify that it's spelled correctly, and then try again. /// </exception> /// <exception cref="Amazon.Polly.Model.ServiceFailureException"> /// An unknown condition has caused a service failure. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/ListSpeechSynthesisTasks">REST API Reference for ListSpeechSynthesisTasks Operation</seealso> public virtual ListSpeechSynthesisTasksResponse ListSpeechSynthesisTasks(ListSpeechSynthesisTasksRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListSpeechSynthesisTasksRequestMarshaller.Instance; options.ResponseUnmarshaller = ListSpeechSynthesisTasksResponseUnmarshaller.Instance; return Invoke<ListSpeechSynthesisTasksResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListSpeechSynthesisTasks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListSpeechSynthesisTasks operation on AmazonPollyClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListSpeechSynthesisTasks /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/ListSpeechSynthesisTasks">REST API Reference for ListSpeechSynthesisTasks Operation</seealso> public virtual IAsyncResult BeginListSpeechSynthesisTasks(ListSpeechSynthesisTasksRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListSpeechSynthesisTasksRequestMarshaller.Instance; options.ResponseUnmarshaller = ListSpeechSynthesisTasksResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListSpeechSynthesisTasks operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListSpeechSynthesisTasks.</param> /// /// <returns>Returns a ListSpeechSynthesisTasksResult from Polly.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/ListSpeechSynthesisTasks">REST API Reference for ListSpeechSynthesisTasks Operation</seealso> public virtual ListSpeechSynthesisTasksResponse EndListSpeechSynthesisTasks(IAsyncResult asyncResult) { return EndInvoke<ListSpeechSynthesisTasksResponse>(asyncResult); } #endregion #region PutLexicon /// <summary> /// Stores a pronunciation lexicon in an Amazon Web Services Region. If a lexicon with /// the same name already exists in the region, it is overwritten by the new lexicon. /// Lexicon operations have eventual consistency, therefore, it might take some time before /// the lexicon is available to the SynthesizeSpeech operation. /// /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/polly/latest/dg/managing-lexicons.html">Managing /// Lexicons</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutLexicon service method.</param> /// /// <returns>The response from the PutLexicon service method, as returned by Polly.</returns> /// <exception cref="Amazon.Polly.Model.InvalidLexiconException"> /// Amazon Polly can't find the specified lexicon. Verify that the lexicon's name is spelled /// correctly, and then try again. /// </exception> /// <exception cref="Amazon.Polly.Model.LexiconSizeExceededException"> /// The maximum size of the specified lexicon would be exceeded by this operation. /// </exception> /// <exception cref="Amazon.Polly.Model.MaxLexemeLengthExceededException"> /// The maximum size of the lexeme would be exceeded by this operation. /// </exception> /// <exception cref="Amazon.Polly.Model.MaxLexiconsNumberExceededException"> /// The maximum number of lexicons would be exceeded by this operation. /// </exception> /// <exception cref="Amazon.Polly.Model.ServiceFailureException"> /// An unknown condition has caused a service failure. /// </exception> /// <exception cref="Amazon.Polly.Model.UnsupportedPlsAlphabetException"> /// The alphabet specified by the lexicon is not a supported alphabet. Valid values are /// <code>x-sampa</code> and <code>ipa</code>. /// </exception> /// <exception cref="Amazon.Polly.Model.UnsupportedPlsLanguageException"> /// The language specified in the lexicon is unsupported. For a list of supported languages, /// see <a href="https://docs.aws.amazon.com/polly/latest/dg/API_LexiconAttributes.html">Lexicon /// Attributes</a>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/PutLexicon">REST API Reference for PutLexicon Operation</seealso> public virtual PutLexiconResponse PutLexicon(PutLexiconRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = PutLexiconRequestMarshaller.Instance; options.ResponseUnmarshaller = PutLexiconResponseUnmarshaller.Instance; return Invoke<PutLexiconResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the PutLexicon operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutLexicon operation on AmazonPollyClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutLexicon /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/PutLexicon">REST API Reference for PutLexicon Operation</seealso> public virtual IAsyncResult BeginPutLexicon(PutLexiconRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = PutLexiconRequestMarshaller.Instance; options.ResponseUnmarshaller = PutLexiconResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutLexicon operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutLexicon.</param> /// /// <returns>Returns a PutLexiconResult from Polly.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/PutLexicon">REST API Reference for PutLexicon Operation</seealso> public virtual PutLexiconResponse EndPutLexicon(IAsyncResult asyncResult) { return EndInvoke<PutLexiconResponse>(asyncResult); } #endregion #region StartSpeechSynthesisTask /// <summary> /// Allows the creation of an asynchronous synthesis task, by starting a new <code>SpeechSynthesisTask</code>. /// This operation requires all the standard information needed for speech synthesis, /// plus the name of an Amazon S3 bucket for the service to store the output of the synthesis /// task and two optional parameters (<code>OutputS3KeyPrefix</code> and <code>SnsTopicArn</code>). /// Once the synthesis task is created, this operation will return a <code>SpeechSynthesisTask</code> /// object, which will include an identifier of this task as well as the current status. /// The <code>SpeechSynthesisTask</code> object is available for 72 hours after starting /// the asynchronous synthesis task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartSpeechSynthesisTask service method.</param> /// /// <returns>The response from the StartSpeechSynthesisTask service method, as returned by Polly.</returns> /// <exception cref="Amazon.Polly.Model.EngineNotSupportedException"> /// This engine is not compatible with the voice that you have designated. Choose a new /// voice that is compatible with the engine or change the engine and restart the operation. /// </exception> /// <exception cref="Amazon.Polly.Model.InvalidS3BucketException"> /// The provided Amazon S3 bucket name is invalid. Please check your input with S3 bucket /// naming requirements and try again. /// </exception> /// <exception cref="Amazon.Polly.Model.InvalidS3KeyException"> /// The provided Amazon S3 key prefix is invalid. Please provide a valid S3 object key /// name. /// </exception> /// <exception cref="Amazon.Polly.Model.InvalidSampleRateException"> /// The specified sample rate is not valid. /// </exception> /// <exception cref="Amazon.Polly.Model.InvalidSnsTopicArnException"> /// The provided SNS topic ARN is invalid. Please provide a valid SNS topic ARN and try /// again. /// </exception> /// <exception cref="Amazon.Polly.Model.InvalidSsmlException"> /// The SSML you provided is invalid. Verify the SSML syntax, spelling of tags and values, /// and then try again. /// </exception> /// <exception cref="Amazon.Polly.Model.LanguageNotSupportedException"> /// The language specified is not currently supported by Amazon Polly in this capacity. /// </exception> /// <exception cref="Amazon.Polly.Model.LexiconNotFoundException"> /// Amazon Polly can't find the specified lexicon. This could be caused by a lexicon that /// is missing, its name is misspelled or specifying a lexicon that is in a different /// region. /// /// /// <para> /// Verify that the lexicon exists, is in the region (see <a>ListLexicons</a>) and that /// you spelled its name is spelled correctly. Then try again. /// </para> /// </exception> /// <exception cref="Amazon.Polly.Model.MarksNotSupportedForFormatException"> /// Speech marks are not supported for the <code>OutputFormat</code> selected. Speech /// marks are only available for content in <code>json</code> format. /// </exception> /// <exception cref="Amazon.Polly.Model.ServiceFailureException"> /// An unknown condition has caused a service failure. /// </exception> /// <exception cref="Amazon.Polly.Model.SsmlMarksNotSupportedForTextTypeException"> /// SSML speech marks are not supported for plain text-type input. /// </exception> /// <exception cref="Amazon.Polly.Model.TextLengthExceededException"> /// The value of the "Text" parameter is longer than the accepted limits. For the <code>SynthesizeSpeech</code> /// API, the limit for input text is a maximum of 6000 characters total, of which no more /// than 3000 can be billed characters. For the <code>StartSpeechSynthesisTask</code> /// API, the maximum is 200,000 characters, of which no more than 100,000 can be billed /// characters. SSML tags are not counted as billed characters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/StartSpeechSynthesisTask">REST API Reference for StartSpeechSynthesisTask Operation</seealso> public virtual StartSpeechSynthesisTaskResponse StartSpeechSynthesisTask(StartSpeechSynthesisTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartSpeechSynthesisTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = StartSpeechSynthesisTaskResponseUnmarshaller.Instance; return Invoke<StartSpeechSynthesisTaskResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StartSpeechSynthesisTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartSpeechSynthesisTask operation on AmazonPollyClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartSpeechSynthesisTask /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/StartSpeechSynthesisTask">REST API Reference for StartSpeechSynthesisTask Operation</seealso> public virtual IAsyncResult BeginStartSpeechSynthesisTask(StartSpeechSynthesisTaskRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StartSpeechSynthesisTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = StartSpeechSynthesisTaskResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartSpeechSynthesisTask operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartSpeechSynthesisTask.</param> /// /// <returns>Returns a StartSpeechSynthesisTaskResult from Polly.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/StartSpeechSynthesisTask">REST API Reference for StartSpeechSynthesisTask Operation</seealso> public virtual StartSpeechSynthesisTaskResponse EndStartSpeechSynthesisTask(IAsyncResult asyncResult) { return EndInvoke<StartSpeechSynthesisTaskResponse>(asyncResult); } #endregion #region SynthesizeSpeech /// <summary> /// Synthesizes UTF-8 input, plain text or SSML, to a stream of bytes. SSML input must /// be valid, well-formed SSML. Some alphabets might not be available with all the voices /// (for example, Cyrillic might not be read at all by English voices) unless phoneme /// mapping is used. For more information, see <a href="https://docs.aws.amazon.com/polly/latest/dg/how-text-to-speech-works.html">How /// it Works</a>. /// </summary> /// <param name="request">Container for the necessary parameters to execute the SynthesizeSpeech service method.</param> /// /// <returns>The response from the SynthesizeSpeech service method, as returned by Polly.</returns> /// <exception cref="Amazon.Polly.Model.EngineNotSupportedException"> /// This engine is not compatible with the voice that you have designated. Choose a new /// voice that is compatible with the engine or change the engine and restart the operation. /// </exception> /// <exception cref="Amazon.Polly.Model.InvalidSampleRateException"> /// The specified sample rate is not valid. /// </exception> /// <exception cref="Amazon.Polly.Model.InvalidSsmlException"> /// The SSML you provided is invalid. Verify the SSML syntax, spelling of tags and values, /// and then try again. /// </exception> /// <exception cref="Amazon.Polly.Model.LanguageNotSupportedException"> /// The language specified is not currently supported by Amazon Polly in this capacity. /// </exception> /// <exception cref="Amazon.Polly.Model.LexiconNotFoundException"> /// Amazon Polly can't find the specified lexicon. This could be caused by a lexicon that /// is missing, its name is misspelled or specifying a lexicon that is in a different /// region. /// /// /// <para> /// Verify that the lexicon exists, is in the region (see <a>ListLexicons</a>) and that /// you spelled its name is spelled correctly. Then try again. /// </para> /// </exception> /// <exception cref="Amazon.Polly.Model.MarksNotSupportedForFormatException"> /// Speech marks are not supported for the <code>OutputFormat</code> selected. Speech /// marks are only available for content in <code>json</code> format. /// </exception> /// <exception cref="Amazon.Polly.Model.ServiceFailureException"> /// An unknown condition has caused a service failure. /// </exception> /// <exception cref="Amazon.Polly.Model.SsmlMarksNotSupportedForTextTypeException"> /// SSML speech marks are not supported for plain text-type input. /// </exception> /// <exception cref="Amazon.Polly.Model.TextLengthExceededException"> /// The value of the "Text" parameter is longer than the accepted limits. For the <code>SynthesizeSpeech</code> /// API, the limit for input text is a maximum of 6000 characters total, of which no more /// than 3000 can be billed characters. For the <code>StartSpeechSynthesisTask</code> /// API, the maximum is 200,000 characters, of which no more than 100,000 can be billed /// characters. SSML tags are not counted as billed characters. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/SynthesizeSpeech">REST API Reference for SynthesizeSpeech Operation</seealso> public virtual SynthesizeSpeechResponse SynthesizeSpeech(SynthesizeSpeechRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = SynthesizeSpeechRequestMarshaller.Instance; options.ResponseUnmarshaller = SynthesizeSpeechResponseUnmarshaller.Instance; return Invoke<SynthesizeSpeechResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the SynthesizeSpeech operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SynthesizeSpeech operation on AmazonPollyClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSynthesizeSpeech /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/SynthesizeSpeech">REST API Reference for SynthesizeSpeech Operation</seealso> public virtual IAsyncResult BeginSynthesizeSpeech(SynthesizeSpeechRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = SynthesizeSpeechRequestMarshaller.Instance; options.ResponseUnmarshaller = SynthesizeSpeechResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the SynthesizeSpeech operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSynthesizeSpeech.</param> /// /// <returns>Returns a SynthesizeSpeechResult from Polly.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/polly-2016-06-10/SynthesizeSpeech">REST API Reference for SynthesizeSpeech Operation</seealso> public virtual SynthesizeSpeechResponse EndSynthesizeSpeech(IAsyncResult asyncResult) { return EndInvoke<SynthesizeSpeechResponse>(asyncResult); } #endregion } }
53.542424
176
0.660384
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/Polly/Generated/_bcl35/AmazonPollyClient.cs
53,007
C#
using System; using System.Collections.Generic; using System.Text; namespace Len.Domain { public interface IDomainEvent { } }
12.727273
33
0.714286
[ "MIT" ]
LenFon/TransferDemo
src/Len.Core/Len/Domain/IDomainEvent.cs
142
C#
// ReSharper disable All namespace FIOImport.POCOs.Planets { public class FioBuildRequirement { public string MaterialName { get; set; } public string MaterialId { get; set; } public string MaterialTicker { get; set; } public string MaterialCategory { get; set; } public int MaterialAmount { get; set; } public double MaterialWeight { get; set; } public double MaterialVolume { get; set; } } }
32.928571
52
0.642082
[ "MIT" ]
Jacudibu/PRUNner
FIOImport/Pocos/Planets/FioBuildRequirement.cs
461
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Numerics { /// <summary> /// Contains various methods useful for creating, manipulating, combining, and converting generic vectors with one another. /// </summary> [Intrinsic] public static partial class Vector { /// <summary> /// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector. /// </summary> /// <param name="condition">The integral mask vector used to drive selection.</param> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The new vector with elements selected based on the mask.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<float> ConditionalSelect(Vector<int> condition, Vector<float> left, Vector<float> right) { return (Vector<float>)Vector<float>.ConditionalSelect((Vector<float>)condition, left, right); } /// <summary> /// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector. /// </summary> /// <param name="condition">The integral mask vector used to drive selection.</param> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The new vector with elements selected based on the mask.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<double> ConditionalSelect(Vector<long> condition, Vector<double> left, Vector<double> right) { return (Vector<double>)Vector<double>.ConditionalSelect((Vector<double>)condition, left, right); } /// <summary> /// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector. /// </summary> /// <param name="condition">The mask vector used to drive selection.</param> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The new vector with elements selected based on the mask.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> ConditionalSelect<T>(Vector<T> condition, Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.ConditionalSelect(condition, left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left and right were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Equals<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.Equals(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether elements in the left and right floating point vectors were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> Equals(Vector<float> left, Vector<float> right) { return (Vector<int>)Vector<float>.Equals(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left and right were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> Equals(Vector<int> left, Vector<int> right) { return Vector<int>.Equals(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether elements in the left and right floating point vectors were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> Equals(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.Equals(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left and right were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> Equals(Vector<long> left, Vector<long> right) { return Vector<long>.Equals(left, right); } /// <summary> /// Returns a boolean indicating whether each pair of elements in the given vectors are equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The first vector to compare.</param> /// <returns>True if all elements are equal; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EqualsAll<T>(Vector<T> left, Vector<T> right) where T : struct { return left == right; } /// <summary> /// Returns a boolean indicating whether any single pair of elements in the given vectors are equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any element pairs are equal; False if no element pairs are equal.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EqualsAny<T>(Vector<T> left, Vector<T> right) where T : struct { return !Vector<T>.Equals(left, right).Equals(Vector<T>.Zero); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> LessThan<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.LessThan(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> LessThan(Vector<float> left, Vector<float> right) { return (Vector<int>)Vector<float>.LessThan(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> LessThan(Vector<int> left, Vector<int> right) { return Vector<int>.LessThan(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> LessThan(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.LessThan(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> LessThan(Vector<long> left, Vector<long> right) { return Vector<long>.LessThan(left, right); } /// <summary> /// Returns a boolean indicating whether all of the elements in left are less than their corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if all elements in left are less than their corresponding elements in right; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanAll<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.LessThan(left, right); return cond.Equals(Vector<int>.AllBitsSet); } /// <summary> /// Returns a boolean indicating whether any element in left is less than its corresponding element in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any elements in left are less than their corresponding elements in right; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanAny<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.LessThan(left, right); return !cond.Equals(Vector<int>.Zero); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> LessThanOrEqual<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.LessThanOrEqual(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> LessThanOrEqual(Vector<float> left, Vector<float> right) { return (Vector<int>)Vector<float>.LessThanOrEqual(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> LessThanOrEqual(Vector<int> left, Vector<int> right) { return Vector<int>.LessThanOrEqual(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> LessThanOrEqual(Vector<long> left, Vector<long> right) { return Vector<long>.LessThanOrEqual(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> LessThanOrEqual(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.LessThanOrEqual(left, right); } /// <summary> /// Returns a boolean indicating whether all elements in left are less than or equal to their corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if all elements in left are less than or equal to their corresponding elements in right; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanOrEqualAll<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.LessThanOrEqual(left, right); return cond.Equals(Vector<int>.AllBitsSet); } /// <summary> /// Returns a boolean indicating whether any element in left is less than or equal to its corresponding element in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any elements in left are less than their corresponding elements in right; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanOrEqualAny<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.LessThanOrEqual(left, right); return !cond.Equals(Vector<int>.Zero); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> GreaterThan<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.GreaterThan(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> GreaterThan(Vector<float> left, Vector<float> right) { return (Vector<int>)Vector<float>.GreaterThan(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> GreaterThan(Vector<int> left, Vector<int> right) { return Vector<int>.GreaterThan(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> GreaterThan(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.GreaterThan(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> GreaterThan(Vector<long> left, Vector<long> right) { return Vector<long>.GreaterThan(left, right); } /// <summary> /// Returns a boolean indicating whether all elements in left are greater than the corresponding elements in right. /// elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if all elements in left are greater than their corresponding elements in right; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanAll<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.GreaterThan(left, right); return cond.Equals(Vector<int>.AllBitsSet); } /// <summary> /// Returns a boolean indicating whether any element in left is greater than its corresponding element in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any elements in left are greater than their corresponding elements in right; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanAny<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.GreaterThan(left, right); return !cond.Equals(Vector<int>.Zero); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> GreaterThanOrEqual<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were greater than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> GreaterThanOrEqual(Vector<float> left, Vector<float> right) { return (Vector<int>)Vector<float>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> GreaterThanOrEqual(Vector<int> left, Vector<int> right) { return Vector<int>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> GreaterThanOrEqual(Vector<long> left, Vector<long> right) { return Vector<long>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were greater than or equal to /// their corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> GreaterThanOrEqual(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns a boolean indicating whether all of the elements in left are greater than or equal to /// their corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if all elements in left are greater than or equal to their corresponding elements in right; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanOrEqualAll<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.GreaterThanOrEqual(left, right); return cond.Equals(Vector<int>.AllBitsSet); } /// <summary> /// Returns a boolean indicating whether any element in left is greater than or equal to its corresponding element in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any elements in left are greater than or equal to their corresponding elements in right; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanOrEqualAny<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.GreaterThanOrEqual(left, right); return !cond.Equals(Vector<int>.Zero); } // Every operation must either be a JIT intrinsic or implemented over a JIT intrinsic // as a thin wrapper // Operations implemented over a JIT intrinsic should be inlined // Methods that do not have a <T> type parameter are recognized as intrinsics /// <summary> /// Returns whether or not vector operations are subject to hardware acceleration through JIT intrinsic support. /// </summary> public static bool IsHardwareAccelerated { [Intrinsic] get => false; } // Vector<T> // Basic Math // All Math operations for Vector<T> are aggressively inlined here /// <summary> /// Returns a new vector whose elements are the absolute values of the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The absolute value vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Abs<T>(Vector<T> value) where T : struct { return Vector<T>.Abs(value); } /// <summary> /// Returns a new vector whose elements are the minimum of each pair of elements in the two given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The minimum vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Min<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.Min(left, right); } /// <summary> /// Returns a new vector whose elements are the maximum of each pair of elements in the two given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The maximum vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Max<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.Max(left, right); } // Specialized vector operations /// <summary> /// Returns the dot product of two vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The dot product.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Dot<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.Dot(left, right); } /// <summary> /// Returns a new vector whose elements are the square roots of the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The square root vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> SquareRoot<T>(Vector<T> value) where T : struct { return Vector<T>.SquareRoot(value); } /// <summary> /// Returns a new vector whose elements are the smallest integral values that are greater than or equal to the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns> /// The vector whose elements are the smallest integral values that are greater than or equal to the given vector's elements. /// If a value is equal to <see cref="float.NaN"/>, <see cref="float.NegativeInfinity"/> or <see cref="float.PositiveInfinity"/>, that value is returned. /// Note that this method returns a <see cref="float"/> instead of an integral type. /// </returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<float> Ceiling(Vector<float> value) { return Vector<float>.Ceiling(value); } /// <summary> /// Returns a new vector whose elements are the smallest integral values that are greater than or equal to the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns> /// The vector whose elements are the smallest integral values that are greater than or equal to the given vector's elements. /// If a value is equal to <see cref="double.NaN"/>, <see cref="double.NegativeInfinity"/> or <see cref="double.PositiveInfinity"/>, that value is returned. /// Note that this method returns a <see cref="double"/> instead of an integral type. /// </returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<double> Ceiling(Vector<double> value) { return Vector<double>.Ceiling(value); } /// <summary> /// Returns a new vector whose elements are the largest integral values that are less than or equal to the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns> /// The vector whose elements are the largest integral values that are less than or equal to the given vector's elements. /// If a value is equal to <see cref="float.NaN"/>, <see cref="float.NegativeInfinity"/> or <see cref="float.PositiveInfinity"/>, that value is returned. /// Note that this method returns a <see cref="float"/> instead of an integral type. /// </returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<float> Floor(Vector<float> value) { return Vector<float>.Floor(value); } /// <summary> /// Returns a new vector whose elements are the largest integral values that are less than or equal to the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns> /// The vector whose elements are the largest integral values that are less than or equal to the given vector's elements. /// If a value is equal to <see cref="double.NaN"/>, <see cref="double.NegativeInfinity"/> or <see cref="double.PositiveInfinity"/>, that value is returned. /// Note that this method returns a <see cref="double"/> instead of an integral type. /// </returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<double> Floor(Vector<double> value) { return Vector<double>.Floor(value); } /// <summary> /// Creates a new vector whose values are the sum of each pair of elements from the two given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Add<T>(Vector<T> left, Vector<T> right) where T : struct { return left + right; } /// <summary> /// Creates a new vector whose values are the difference between each pairs of elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The difference vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Subtract<T>(Vector<T> left, Vector<T> right) where T : struct { return left - right; } /// <summary> /// Creates a new vector whose values are the product of each pair of elements from the two given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Multiply<T>(Vector<T> left, Vector<T> right) where T : struct { return left * right; } /// <summary> /// Returns a new vector whose values are the values of the given vector each multiplied by a scalar value. /// </summary> /// <param name="left">The source vector.</param> /// <param name="right">The scalar factor.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Multiply<T>(Vector<T> left, T right) where T : struct { return left * right; } /// <summary> /// Returns a new vector whose values are the values of the given vector each multiplied by a scalar value. /// </summary> /// <param name="left">The scalar factor.</param> /// <param name="right">The source vector.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Multiply<T>(T left, Vector<T> right) where T : struct { return left * right; } /// <summary> /// Returns a new vector whose values are the result of dividing the first vector's elements /// by the corresponding elements in the second vector. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The divided vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Divide<T>(Vector<T> left, Vector<T> right) where T : struct { return left / right; } /// <summary> /// Returns a new vector whose elements are the given vector's elements negated. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The negated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Negate<T>(Vector<T> value) where T : struct { return -value; } /// <summary> /// Returns a new vector by performing a bitwise-and operation on each of the elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The resultant vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> BitwiseAnd<T>(Vector<T> left, Vector<T> right) where T : struct { return left & right; } /// <summary> /// Returns a new vector by performing a bitwise-or operation on each of the elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The resultant vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> BitwiseOr<T>(Vector<T> left, Vector<T> right) where T : struct { return left | right; } /// <summary> /// Returns a new vector whose elements are obtained by taking the one's complement of the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The one's complement vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> OnesComplement<T>(Vector<T> value) where T : struct { return ~value; } /// <summary> /// Returns a new vector by performing a bitwise-exclusive-or operation on each of the elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The resultant vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> Xor<T>(Vector<T> left, Vector<T> right) where T : struct { return left ^ right; } /// <summary> /// Returns a new vector by performing a bitwise-and-not operation on each of the elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The resultant vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T> AndNot<T>(Vector<T> left, Vector<T> right) where T : struct { return left & ~right; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of unsigned bytes. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<byte> AsVectorByte<T>(Vector<T> value) where T : struct { return (Vector<byte>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of signed bytes. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<sbyte> AsVectorSByte<T>(Vector<T> value) where T : struct { return (Vector<sbyte>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of 16-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<ushort> AsVectorUInt16<T>(Vector<T> value) where T : struct { return (Vector<ushort>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of signed 16-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<short> AsVectorInt16<T>(Vector<T> value) where T : struct { return (Vector<short>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of unsigned 32-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<uint> AsVectorUInt32<T>(Vector<T> value) where T : struct { return (Vector<uint>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of signed 32-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<int> AsVectorInt32<T>(Vector<T> value) where T : struct { return (Vector<int>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of unsigned 64-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<ulong> AsVectorUInt64<T>(Vector<T> value) where T : struct { return (Vector<ulong>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of signed 64-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<long> AsVectorInt64<T>(Vector<T> value) where T : struct { return (Vector<long>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of 32-bit floating point numbers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<float> AsVectorSingle<T>(Vector<T> value) where T : struct { return (Vector<float>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of 64-bit floating point numbers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<double> AsVectorDouble<T>(Vector<T> value) where T : struct { return (Vector<double>)value; } /// <summary> /// Widens a Vector{Byte} into two Vector{UInt16}'s. /// <param name="source">The source vector whose elements are widened into the outputs.</param> /// <param name="low">The first output vector, whose elements will contain the widened elements from lower indices in the source vector.</param> /// <param name="high">The second output vector, whose elements will contain the widened elements from higher indices in the source vector.</param> /// </summary> [CLSCompliant(false)] [Intrinsic] public static unsafe void Widen(Vector<byte> source, out Vector<ushort> low, out Vector<ushort> high) { int elements = Vector<byte>.Count; ushort* lowPtr = stackalloc ushort[elements / 2]; for (int i = 0; i < elements / 2; i++) { lowPtr[i] = (ushort)source[i]; } ushort* highPtr = stackalloc ushort[elements / 2]; for (int i = 0; i < elements / 2; i++) { highPtr[i] = (ushort)source[i + (elements / 2)]; } low = *(Vector<ushort>*)lowPtr; high = *(Vector<ushort>*)highPtr; } /// <summary> /// Widens a Vector{UInt16} into two Vector{UInt32}'s. /// <param name="source">The source vector whose elements are widened into the outputs.</param> /// <param name="low">The first output vector, whose elements will contain the widened elements from lower indices in the source vector.</param> /// <param name="high">The second output vector, whose elements will contain the widened elements from higher indices in the source vector.</param> /// </summary> [CLSCompliant(false)] [Intrinsic] public static unsafe void Widen(Vector<ushort> source, out Vector<uint> low, out Vector<uint> high) { int elements = Vector<ushort>.Count; uint* lowPtr = stackalloc uint[elements / 2]; for (int i = 0; i < elements / 2; i++) { lowPtr[i] = (uint)source[i]; } uint* highPtr = stackalloc uint[elements / 2]; for (int i = 0; i < elements / 2; i++) { highPtr[i] = (uint)source[i + (elements / 2)]; } low = *(Vector<uint>*)lowPtr; high = *(Vector<uint>*)highPtr; } /// <summary> /// Widens a Vector{UInt32} into two Vector{UInt64}'s. /// <param name="source">The source vector whose elements are widened into the outputs.</param> /// <param name="low">The first output vector, whose elements will contain the widened elements from lower indices in the source vector.</param> /// <param name="high">The second output vector, whose elements will contain the widened elements from higher indices in the source vector.</param> /// </summary> [CLSCompliant(false)] [Intrinsic] public static unsafe void Widen(Vector<uint> source, out Vector<ulong> low, out Vector<ulong> high) { int elements = Vector<uint>.Count; ulong* lowPtr = stackalloc ulong[elements / 2]; for (int i = 0; i < elements / 2; i++) { lowPtr[i] = (ulong)source[i]; } ulong* highPtr = stackalloc ulong[elements / 2]; for (int i = 0; i < elements / 2; i++) { highPtr[i] = (ulong)source[i + (elements / 2)]; } low = *(Vector<ulong>*)lowPtr; high = *(Vector<ulong>*)highPtr; } /// <summary> /// Widens a Vector{SByte} into two Vector{Int16}'s. /// <param name="source">The source vector whose elements are widened into the outputs.</param> /// <param name="low">The first output vector, whose elements will contain the widened elements from lower indices in the source vector.</param> /// <param name="high">The second output vector, whose elements will contain the widened elements from higher indices in the source vector.</param> /// </summary> [CLSCompliant(false)] [Intrinsic] public static unsafe void Widen(Vector<sbyte> source, out Vector<short> low, out Vector<short> high) { int elements = Vector<sbyte>.Count; short* lowPtr = stackalloc short[elements / 2]; for (int i = 0; i < elements / 2; i++) { lowPtr[i] = (short)source[i]; } short* highPtr = stackalloc short[elements / 2]; for (int i = 0; i < elements / 2; i++) { highPtr[i] = (short)source[i + (elements / 2)]; } low = *(Vector<short>*)lowPtr; high = *(Vector<short>*)highPtr; } /// <summary> /// Widens a Vector{Int16} into two Vector{Int32}'s. /// <param name="source">The source vector whose elements are widened into the outputs.</param> /// <param name="low">The first output vector, whose elements will contain the widened elements from lower indices in the source vector.</param> /// <param name="high">The second output vector, whose elements will contain the widened elements from higher indices in the source vector.</param> /// </summary> [Intrinsic] public static unsafe void Widen(Vector<short> source, out Vector<int> low, out Vector<int> high) { int elements = Vector<short>.Count; int* lowPtr = stackalloc int[elements / 2]; for (int i = 0; i < elements / 2; i++) { lowPtr[i] = (int)source[i]; } int* highPtr = stackalloc int[elements / 2]; for (int i = 0; i < elements / 2; i++) { highPtr[i] = (int)source[i + (elements / 2)]; } low = *(Vector<int>*)lowPtr; high = *(Vector<int>*)highPtr; } /// <summary> /// Widens a Vector{Int32} into two Vector{Int64}'s. /// <param name="source">The source vector whose elements are widened into the outputs.</param> /// <param name="low">The first output vector, whose elements will contain the widened elements from lower indices in the source vector.</param> /// <param name="high">The second output vector, whose elements will contain the widened elements from higher indices in the source vector.</param> /// </summary> [Intrinsic] public static unsafe void Widen(Vector<int> source, out Vector<long> low, out Vector<long> high) { int elements = Vector<int>.Count; long* lowPtr = stackalloc long[elements / 2]; for (int i = 0; i < elements / 2; i++) { lowPtr[i] = (long)source[i]; } long* highPtr = stackalloc long[elements / 2]; for (int i = 0; i < elements / 2; i++) { highPtr[i] = (long)source[i + (elements / 2)]; } low = *(Vector<long>*)lowPtr; high = *(Vector<long>*)highPtr; } /// <summary> /// Widens a Vector{Single} into two Vector{Double}'s. /// <param name="source">The source vector whose elements are widened into the outputs.</param> /// <param name="low">The first output vector, whose elements will contain the widened elements from lower indices in the source vector.</param> /// <param name="high">The second output vector, whose elements will contain the widened elements from higher indices in the source vector.</param> /// </summary> [Intrinsic] public static unsafe void Widen(Vector<float> source, out Vector<double> low, out Vector<double> high) { int elements = Vector<float>.Count; double* lowPtr = stackalloc double[elements / 2]; for (int i = 0; i < elements / 2; i++) { lowPtr[i] = (double)source[i]; } double* highPtr = stackalloc double[elements / 2]; for (int i = 0; i < elements / 2; i++) { highPtr[i] = (double)source[i + (elements / 2)]; } low = *(Vector<double>*)lowPtr; high = *(Vector<double>*)highPtr; } /// <summary> /// Narrows two Vector{UInt16}'s into one Vector{Byte}. /// <param name="low">The first source vector, whose elements become the lower-index elements of the return value.</param> /// <param name="high">The second source vector, whose elements become the higher-index elements of the return value.</param> /// <returns>A Vector{Byte} containing elements narrowed from the source vectors.</returns> /// </summary> [CLSCompliant(false)] [Intrinsic] public static unsafe Vector<byte> Narrow(Vector<ushort> low, Vector<ushort> high) { int elements = Vector<byte>.Count; byte* retPtr = stackalloc byte[elements]; for (int i = 0; i < elements / 2; i++) { retPtr[i] = (byte)low[i]; } for (int i = 0; i < elements / 2; i++) { retPtr[i + (elements / 2)] = (byte)high[i]; } return *(Vector<byte>*)retPtr; } /// <summary> /// Narrows two Vector{UInt32}'s into one Vector{UInt16}. /// <param name="low">The first source vector, whose elements become the lower-index elements of the return value.</param> /// <param name="high">The second source vector, whose elements become the higher-index elements of the return value.</param> /// <returns>A Vector{UInt16} containing elements narrowed from the source vectors.</returns> /// </summary> [CLSCompliant(false)] [Intrinsic] public static unsafe Vector<ushort> Narrow(Vector<uint> low, Vector<uint> high) { int elements = Vector<ushort>.Count; ushort* retPtr = stackalloc ushort[elements]; for (int i = 0; i < elements / 2; i++) { retPtr[i] = (ushort)low[i]; } for (int i = 0; i < elements / 2; i++) { retPtr[i + (elements / 2)] = (ushort)high[i]; } return *(Vector<ushort>*)retPtr; } /// <summary> /// Narrows two Vector{UInt64}'s into one Vector{UInt32}. /// <param name="low">The first source vector, whose elements become the lower-index elements of the return value.</param> /// <param name="high">The second source vector, whose elements become the higher-index elements of the return value.</param> /// <returns>A Vector{UInt32} containing elements narrowed from the source vectors.</returns> /// </summary> [CLSCompliant(false)] [Intrinsic] public static unsafe Vector<uint> Narrow(Vector<ulong> low, Vector<ulong> high) { int elements = Vector<uint>.Count; uint* retPtr = stackalloc uint[elements]; for (int i = 0; i < elements / 2; i++) { retPtr[i] = (uint)low[i]; } for (int i = 0; i < elements / 2; i++) { retPtr[i + (elements / 2)] = (uint)high[i]; } return *(Vector<uint>*)retPtr; } /// <summary> /// Narrows two Vector{Int16}'s into one Vector{SByte}. /// <param name="low">The first source vector, whose elements become the lower-index elements of the return value.</param> /// <param name="high">The second source vector, whose elements become the higher-index elements of the return value.</param> /// <returns>A Vector{SByte} containing elements narrowed from the source vectors.</returns> /// </summary> [CLSCompliant(false)] [Intrinsic] public static unsafe Vector<sbyte> Narrow(Vector<short> low, Vector<short> high) { int elements = Vector<sbyte>.Count; sbyte* retPtr = stackalloc sbyte[elements]; for (int i = 0; i < elements / 2; i++) { retPtr[i] = (sbyte)low[i]; } for (int i = 0; i < elements / 2; i++) { retPtr[i + (elements / 2)] = (sbyte)high[i]; } return *(Vector<sbyte>*)retPtr; } /// <summary> /// Narrows two Vector{Int32}'s into one Vector{Int16}. /// <param name="low">The first source vector, whose elements become the lower-index elements of the return value.</param> /// <param name="high">The second source vector, whose elements become the higher-index elements of the return value.</param> /// <returns>A Vector{Int16} containing elements narrowed from the source vectors.</returns> /// </summary> [Intrinsic] public static unsafe Vector<short> Narrow(Vector<int> low, Vector<int> high) { int elements = Vector<short>.Count; short* retPtr = stackalloc short[elements]; for (int i = 0; i < elements / 2; i++) { retPtr[i] = (short)low[i]; } for (int i = 0; i < elements / 2; i++) { retPtr[i + (elements / 2)] = (short)high[i]; } return *(Vector<short>*)retPtr; } /// <summary> /// Narrows two Vector{Int64}'s into one Vector{Int32}. /// <param name="low">The first source vector, whose elements become the lower-index elements of the return value.</param> /// <param name="high">The second source vector, whose elements become the higher-index elements of the return value.</param> /// <returns>A Vector{Int32} containing elements narrowed from the source vectors.</returns> /// </summary> [Intrinsic] public static unsafe Vector<int> Narrow(Vector<long> low, Vector<long> high) { int elements = Vector<int>.Count; int* retPtr = stackalloc int[elements]; for (int i = 0; i < elements / 2; i++) { retPtr[i] = (int)low[i]; } for (int i = 0; i < elements / 2; i++) { retPtr[i + (elements / 2)] = (int)high[i]; } return *(Vector<int>*)retPtr; } /// <summary> /// Narrows two Vector{Double}'s into one Vector{Single}. /// <param name="low">The first source vector, whose elements become the lower-index elements of the return value.</param> /// <param name="high">The second source vector, whose elements become the higher-index elements of the return value.</param> /// <returns>A Vector{Single} containing elements narrowed from the source vectors.</returns> /// </summary> [Intrinsic] public static unsafe Vector<float> Narrow(Vector<double> low, Vector<double> high) { int elements = Vector<float>.Count; float* retPtr = stackalloc float[elements]; for (int i = 0; i < elements / 2; i++) { retPtr[i] = (float)low[i]; } for (int i = 0; i < elements / 2; i++) { retPtr[i + (elements / 2)] = (float)high[i]; } return *(Vector<float>*)retPtr; } /// <summary> /// Converts a Vector{Int32} to a Vector{Single}. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The converted vector.</returns> [Intrinsic] public static unsafe Vector<float> ConvertToSingle(Vector<int> value) { int elements = Vector<float>.Count; float* retPtr = stackalloc float[elements]; for (int i = 0; i < elements; i++) { retPtr[i] = (float)value[i]; } return *(Vector<float>*)retPtr; } /// <summary> /// Converts a Vector{UInt32} to a Vector{Single}. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The converted vector.</returns> [CLSCompliant(false)] [Intrinsic] public static unsafe Vector<float> ConvertToSingle(Vector<uint> value) { int elements = Vector<float>.Count; float* retPtr = stackalloc float[elements]; for (int i = 0; i < elements; i++) { retPtr[i] = (float)value[i]; } return *(Vector<float>*)retPtr; } /// <summary> /// Converts a Vector{Int64} to a Vector{Double}. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The converted vector.</returns> [Intrinsic] public static unsafe Vector<double> ConvertToDouble(Vector<long> value) { int elements = Vector<double>.Count; double* retPtr = stackalloc double[elements]; for (int i = 0; i < elements; i++) { retPtr[i] = (double)value[i]; } return *(Vector<double>*)retPtr; } /// <summary> /// Converts a Vector{UInt64} to a Vector{Double}. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The converted vector.</returns> [CLSCompliant(false)] [Intrinsic] public static unsafe Vector<double> ConvertToDouble(Vector<ulong> value) { int elements = Vector<double>.Count; double* retPtr = stackalloc double[elements]; for (int i = 0; i < elements; i++) { retPtr[i] = (double)value[i]; } return *(Vector<double>*)retPtr; } /// <summary> /// Converts a Vector{Single} to a Vector{Int32}. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The converted vector.</returns> [Intrinsic] public static unsafe Vector<int> ConvertToInt32(Vector<float> value) { int elements = Vector<int>.Count; int* retPtr = stackalloc int[elements]; for (int i = 0; i < elements; i++) { retPtr[i] = (int)value[i]; } return *(Vector<int>*)retPtr; } /// <summary> /// Converts a Vector{Single} to a Vector{UInt32}. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The converted vector.</returns> [CLSCompliant(false)] [Intrinsic] public static unsafe Vector<uint> ConvertToUInt32(Vector<float> value) { int elements = Vector<uint>.Count; uint* retPtr = stackalloc uint[elements]; for (int i = 0; i < elements; i++) { retPtr[i] = (uint)value[i]; } return *(Vector<uint>*)retPtr; } /// <summary> /// Converts a Vector{Double} to a Vector{Int64}. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The converted vector.</returns> [Intrinsic] public static unsafe Vector<long> ConvertToInt64(Vector<double> value) { int elements = Vector<long>.Count; long* retPtr = stackalloc long[elements]; for (int i = 0; i < elements; i++) { retPtr[i] = (long)value[i]; } return *(Vector<long>*)retPtr; } /// <summary> /// Converts a Vector{Double} to a Vector{UInt64}. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The converted vector.</returns> [CLSCompliant(false)] [Intrinsic] public static unsafe Vector<ulong> ConvertToUInt64(Vector<double> value) { int elements = Vector<ulong>.Count; ulong* retPtr = stackalloc ulong[elements]; for (int i = 0; i < elements; i++) { retPtr[i] = (ulong)value[i]; } return *(Vector<ulong>*)retPtr; } [DoesNotReturn] internal static void ThrowInsufficientNumberOfElementsException(int requiredElementCount) { throw new IndexOutOfRangeException(SR.Format(SR.Arg_InsufficientNumberOfElements, requiredElementCount, "values")); } /// <summary> /// Reinterprets a <see cref="Vector{T}"/> as a <see cref="Vector{T}"/> of new type. /// </summary> /// <typeparam name="TFrom">The type of the input vector.</typeparam> /// <typeparam name="TTo">The type to reinterpret the vector as.</typeparam> /// <param name="vector">The vector to reinterpret.</param> /// <returns><paramref name="vector"/> reinterpreted as a new <see cref="Vector{T}"/>.</returns> /// <exception cref="NotSupportedException"> /// The type of <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> is not supported. /// </exception> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<TTo> As<TFrom, TTo>(this Vector<TFrom> vector) where TFrom : struct where TTo : struct { ThrowHelper.ThrowForUnsupportedVectorBaseType<TFrom>(); ThrowHelper.ThrowForUnsupportedVectorBaseType<TTo>(); return Unsafe.As<Vector<TFrom>, Vector<TTo>>(ref vector); } } }
45.586703
164
0.594819
[ "MIT" ]
AndyAyersMS/runtime
src/libraries/System.Private.CoreLib/src/System/Numerics/Vector.cs
66,511
C#
using Havit.Blazor.Components.Web.Bootstrap.Internal; namespace Havit.Blazor.Components.Web.Bootstrap { /// <summary> /// A base class for form input components. This base class automatically integrates /// with an Microsoft.AspNetCore.Components.Forms.EditContext, which must be supplied /// as a cascading parameter. /// Extends <seealso cref="HxInputBase{TValue}" /> class. /// Adds support for input groups, <a href="https://v5.getbootstrap.com/docs/5.0/forms/input-group/" /> /// </summary> public abstract class HxInputBaseWithInputGroups<TValue> : HxInputBase<TValue>, IFormValueComponentWithInputGroups { /// <summary> /// Input-group at the beginning of the input. /// </summary> [Parameter] public string InputGroupStartText { get; set; } /// <summary> /// Input-group at the beginning of the input. /// </summary> [Parameter] public RenderFragment InputGroupStartTemplate { get; set; } /// <summary> /// Input-group at the end of the input. /// </summary> [Parameter] public string InputGroupEndText { get; set; } /// <summary> /// Input-group at the end of the input. /// </summary> [Parameter] public RenderFragment InputGroupEndTemplate { get; set; } } }
35.735294
115
0.707819
[ "MIT" ]
HybridSolutions/Havit.Blazor
Havit.Blazor.Components.Web.Bootstrap/Forms/HxInputBaseWithInputGroups.cs
1,217
C#
#pragma checksum "..\..\App.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "2A9BEBBE105E41965AF0696E6747FA94454AA50D27BCCF455B1CA8B3262F5CB5" //------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ using ScrewingAround; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace ScrewingAround { /// <summary> /// App /// </summary> public partial class App : System.Windows.Application { /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { #line 5 "..\..\App.xaml" this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative); #line default #line hidden } /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public static void Main() { ScrewingAround.App app = new ScrewingAround.App(); app.InitializeComponent(); app.Run(); } } }
32.225352
142
0.621941
[ "MIT" ]
Hoorge/WIM-Witch
ScrewingAround/ScrewingAround/obj/Debug/App.g.i.cs
2,290
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ListaComParallel { class Program { static List<ParallelListTeste> listaDeitens = new List<ParallelListTeste>(); static void Main(string[] args) { var iniciDaoperacao = DateTime.Now; CarregaLista(); var tempoTotal = DateTime.Now - iniciDaoperacao; Console.WriteLine($"Tempo total para executar a operação: {tempoTotal}"); Console.ReadKey(); } public static void CarregaListaParallel() { Parallel.For(0,62000, i => { listaDeitens.Add(new ParallelListTeste() { Numero = i }); }); } public static void CarregaLista() { for (int i = 0; i < 62000; i++) { listaDeitens.Add(new ParallelListTeste() { Numero = i }); } } } public class ParallelListTeste { /// <summary> /// Número que indica a ordem de criação deste item; /// </summary> public long Numero { get; set; } = 0; /// <summary> /// Indicador booleano que mostra se foi atualizado ou não. /// </summary> public bool Atualizado { get; set; } = false; } }
25.842105
85
0.506449
[ "MIT" ]
HenocEtienne2512/Git
GitC-master/15-07-19_19-07-19/ListaComParallel/ListaComParallel/Program.cs
1,481
C#
using BusinessLayer.DataTransferObjects; using BusinessLayer.DataTransferObjects.Common; using System; namespace BusinessLayer.DataTransferObjects.Filters { public class UserFilterDto : FilterDtoBase { public string Username { get; set; } public string Email { get; set; } public Gender Gender { get; set; } public DateTime BornBefore { get; set; } public DateTime BornAfter { get; set; } public UserFilterDto() { Gender = Gender.NoInformation; BornBefore = DateTime.MinValue; BornAfter = DateTime.MinValue; } } }
28.545455
51
0.64172
[ "MIT" ]
mhamern/SocialNetwork-WhatCanIWearTonight
WCIWT/BusinessLayer/DataTransferObjects/Filters/UserFilterDto.cs
630
C#
/* * Domain Public API * * See https://developer.domain.com.au for more information * * The version of the OpenAPI document: v1 * Contact: api@domain.com.au * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Domain.Api.V1.Client.OpenAPIDateConverter; namespace Domain.Api.V1.Model { /// <summary> /// DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel /// </summary> [DataContract(Name = "Domain.APMService.v3.Model.APMAPIModelsTokenisedSearchV3ApmIdModel")] public partial class DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel : IEquatable<DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel>, IValidatableObject { /// <summary> /// Defines Level /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum LevelEnum { /// <summary> /// Enum Address for value: Address /// </summary> [EnumMember(Value = "Address")] Address = 1, /// <summary> /// Enum Street for value: Street /// </summary> [EnumMember(Value = "Street")] Street = 2, /// <summary> /// Enum Suburb for value: Suburb /// </summary> [EnumMember(Value = "Suburb")] Suburb = 3, /// <summary> /// Enum Postcode for value: Postcode /// </summary> [EnumMember(Value = "Postcode")] Postcode = 4, /// <summary> /// Enum State for value: State /// </summary> [EnumMember(Value = "State")] State = 5 } /// <summary> /// Gets or Sets Level /// </summary> [DataMember(Name = "level", EmitDefaultValue = false)] public LevelEnum? Level { get; set; } /// <summary> /// Initializes a new instance of the <see cref="DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel" /> class. /// </summary> /// <param name="level">level.</param> /// <param name="id">id.</param> public DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel(LevelEnum? level = default(LevelEnum?), int id = default(int)) { this.Level = level; this.Id = id; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public int Id { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel {\n"); sb.Append(" Level: ").Append(Level).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel); } /// <summary> /// Returns true if DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel instances are equal /// </summary> /// <param name="input">Instance of DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel to be compared</param> /// <returns>Boolean</returns> public bool Equals(DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel input) { if (input == null) return false; return ( this.Level == input.Level || this.Level.Equals(input.Level) ) && ( this.Id == input.Id || this.Id.Equals(input.Id) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; hashCode = hashCode * 59 + this.Level.GetHashCode(); hashCode = hashCode * 59 + this.Id.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
33.551136
184
0.576291
[ "MIT" ]
neildobson-au/InvestOz
src/Integrations/Domain/Domain.Api.V1/src/Domain.Api.V1/Model/DomainAPMServiceV3ModelAPMAPIModelsTokenisedSearchV3ApmIdModel.cs
5,905
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Rhino.DistributedHashTable.Client.Exceptions; using Rhino.DistributedHashTable.Client.Pooling; using Rhino.DistributedHashTable.Client.Util; using Rhino.DistributedHashTable.Exceptions; using Rhino.DistributedHashTable.Internal; using Rhino.DistributedHashTable.Parameters; using Rhino.PersistentHashTable; namespace Rhino.DistributedHashTable.Client { public class DistributedHashTable : IDistributedHashTable { private readonly IDistributedHashTableMaster master; private readonly IConnectionPool pool; private Topology topology; public DistributedHashTable(IDistributedHashTableMaster master, IConnectionPool pool) { this.master = master; this.pool = pool; topology = master.GetTopology(); } public PutResult[] Put(params PutRequest[] valuesToAdd) { return PutInternal(valuesToAdd, 0); } private PutResult[] PutInternal(PutRequest[] valuesToAdd, int backupIndex) { var results = new PutResult[valuesToAdd.Length]; var groupedByEndpoint = from req in valuesToAdd let er = new { OriginalIndex = Array.IndexOf(valuesToAdd, req), Put = new ExtendedPutRequest { Bytes = req.Bytes, ExpiresAt = req.ExpiresAt, IsReadOnly = req.IsReadOnly, Key = req.Key, OptimisticConcurrency = req.OptimisticConcurrency, ParentVersions = req.ParentVersions, Segment = GetSegmentFromKey(req.Key), } } group er by GetEndpointByBackupIndex(topology.Segments[er.Put.Segment], backupIndex) into g select g; foreach (var endpoint in groupedByEndpoint) { if (endpoint.Key == null) throw new NoMoreBackupsException(); var requests = endpoint.ToArray(); var putRequests = requests.Select(x => x.Put).ToArray(); var putsResults = GetPutsResults(endpoint.Key, putRequests, backupIndex); for (var i = 0; i < putsResults.Length; i++) { results[requests[i].OriginalIndex] = putsResults[i]; } } return results; } private static NodeEndpoint GetEndpointByBackupIndex(Segment segment, int backupIndex) { if (backupIndex == 0) return segment.AssignedEndpoint; return segment.Backups.ElementAtOrDefault(backupIndex - 1); } private PutResult[] GetPutsResults(NodeEndpoint endpoint, ExtendedPutRequest[] putRequests, int backupIndex) { try { using (var client = pool.Create(endpoint)) { return client.Put(topology.Version, putRequests); } } catch (SeeOtherException soe) { return GetPutsResults(soe.Endpoint, putRequests, backupIndex); } catch (TopologyVersionDoesNotMatchException) { RefreshTopology(); return PutInternal(putRequests, backupIndex); } catch (Exception) { try { return PutInternal(putRequests, backupIndex + 1); } catch (NoMoreBackupsException) { } throw; } } private void RefreshTopology() { topology = master.GetTopology(); } private static int GetSegmentFromKey(string key) { // we use @ as a locality separator, that is: // foo@5 and bar@5 are both going to reside in the same // segment, ensuring locality & one shot calls var partialKey = key.Split('@').Last(); var crc32 = (int)Crc32.Compute(Encoding.Unicode.GetBytes(partialKey)); return Math.Abs(crc32 % Constants.NumberOfSegments); } public Value[][] Get(params GetRequest[] valuesToGet) { return GetInternal(valuesToGet, 0); } private Value[][] GetInternal(GetRequest[] valuesToGet, int backupIndex) { var results = new Value[valuesToGet.Length][]; var groupedByEndpoint = from req in valuesToGet let er = new { OriginalIndex = Array.IndexOf(valuesToGet, req), Get = new ExtendedGetRequest { Key = req.Key, SpecifiedVersion = req.SpecifiedVersion, Segment = GetSegmentFromKey(req.Key), } } group er by GetEndpointByBackupIndex(topology.Segments[er.Get.Segment], backupIndex) into g select g; foreach (var endpoint in groupedByEndpoint) { if (endpoint.Key == null) throw new NoMoreBackupsException(); var requests = endpoint.ToArray(); var getRequests = requests.Select(x => x.Get).ToArray(); var putsResults = GetGetsResults(endpoint.Key, getRequests, backupIndex); for (var i = 0; i < putsResults.Length; i++) { results[requests[i].OriginalIndex] = putsResults[i]; } } return results; } private Value[][] GetGetsResults(NodeEndpoint endpoint, ExtendedGetRequest[] getRequests, int backupIndex) { try { using (var client = pool.Create(endpoint)) { return client.Get(topology.Version, getRequests); } } catch (SeeOtherException soe) { return GetGetsResults(soe.Endpoint, getRequests, backupIndex); } catch (TopologyVersionDoesNotMatchException) { RefreshTopology(); return GetInternal(getRequests, backupIndex); } catch (Exception) { try { return GetInternal(getRequests, backupIndex + 1); } catch (NoMoreBackupsException) { } throw; } } public bool[] Remove(params RemoveRequest[] valuesToRemove) { return RemoveInternal(valuesToRemove, 0); } private bool[] RemoveInternal(RemoveRequest[] valuesToRemove, int backupIndex) { var results = new bool[valuesToRemove.Length]; var groupedByEndpoint = from req in valuesToRemove let er = new { OriginalIndex = Array.IndexOf(valuesToRemove, req), Remove = new ExtendedRemoveRequest { Key = req.Key, SpecificVersion = req.SpecificVersion, Segment = GetSegmentFromKey(req.Key), } } group er by GetEndpointByBackupIndex(topology.Segments[er.Remove.Segment], backupIndex) into g select g; foreach (var endpoint in groupedByEndpoint) { if (endpoint.Key == null) throw new NoMoreBackupsException(); var requests = endpoint.ToArray(); var removeRequests = requests.Select(x => x.Remove).ToArray(); var removesResults = GetRemovesResults(endpoint.Key, removeRequests, backupIndex); for (var i = 0; i < removesResults.Length; i++) { results[requests[i].OriginalIndex] = removesResults[i]; } } return results; } private bool[] GetRemovesResults(NodeEndpoint endpoint, ExtendedRemoveRequest[] removeRequests, int backupIndex) { try { using (var client = pool.Create(endpoint)) { return client.Remove(topology.Version, removeRequests); } } catch (SeeOtherException soe) { return GetRemovesResults(soe.Endpoint, removeRequests, backupIndex); } catch (TopologyVersionDoesNotMatchException) { RefreshTopology(); return RemoveInternal(removeRequests, backupIndex); } catch (Exception) { try { return RemoveInternal(removeRequests, backupIndex + 1); } catch (NoMoreBackupsException) { } throw; } } public int[] AddItems(params AddItemRequest[] itemsToAdd) { throw new NotImplementedException(); } public void RemoteItems(params RemoveItemRequest[] itemsToRemove) { throw new NotImplementedException(); } public KeyValuePair<int, byte[]>[] GetItems(GetItemsRequest request) { throw new NotImplementedException(); } } }
27.058219
104
0.64245
[ "BSD-3-Clause" ]
Diqiguoji008/dht
Rhino.DistributedHashTable.Client/DistributedHashTable.cs
7,901
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the monitoring-2010-08-01.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.CloudWatch.Model { /// <summary> /// Container for the parameters to the DeleteMetricStream operation. /// Permanently deletes the metric stream that you specify. /// </summary> public partial class DeleteMetricStreamRequest : AmazonCloudWatchRequest { private string _name; /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the metric stream to delete. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=255)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } } }
29.169492
108
0.653109
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CloudWatch/Generated/Model/DeleteMetricStreamRequest.cs
1,721
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("ServiceStack")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Service Stack LLC")] [assembly: AssemblyProduct("ServiceStack")] [assembly: AssemblyCopyright("Copyright (c) ServiceStack 2013")] [assembly: AssemblyTrademark("Service Stack")] [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("d6637dcd-f6e8-46b0-a1a7-ad323e1f199e")] // 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("4.0.0.0")] [assembly: AssemblyFileVersion("4.0.0.0")]
39.891892
85
0.732385
[ "Apache-2.0" ]
FernandoPinheiro/ServiceStack
src/ServiceStack.Caching.Memcached/Properties/AssemblyInfo.cs
1,440
C#
// GTKSharpDemo (c) 2015-17 MIT License <baltasarq@gmail.com> namespace GTKSharpDemo { public class Ppal { public static void Main() { var wMain = new MainWindow(); Gtk.Application.Init(); wMain.ShowAll(); Gtk.Application.Run(); } } }
18.285714
62
0.664063
[ "MIT" ]
Baltasarq/GTKSharpDemo
Ppal.cs
258
C#
// Fill out your copyright notice in the Description page of Project Settings. using UnrealBuildTool; public class UnrealTest418 : ModuleRules { public UnrealTest418(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" }); PrivateDependencyModuleNames.AddRange(new string[] { }); // Uncomment if you are using Slate UI // PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" }); // Uncomment if you are using online features // PrivateDependencyModuleNames.Add("OnlineSubsystem"); // To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true } }
33.375
128
0.757803
[ "MIT" ]
donll8999/SDKs
tests/UnrealTest-4.18/Source/UnrealTest418/UnrealTest418.Build.cs
801
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using BESSy.Json.Bson; namespace BESSy.Json.Tests.Documentation.Samples.Bson { public class DeserializeFromBson { #region Types public class Event { public string Name { get; set; } public DateTime StartDate { get; set; } } #endregion public void Example() { #region Usage byte[] data = Convert.FromBase64String("MQAAAAJOYW1lAA8AAABNb3ZpZSBQcmVtaWVyZQAJU3RhcnREYXRlAMDgKWE8AQAAAA=="); MemoryStream ms = new MemoryStream(data); using (BsonReader reader = new BsonReader(ms)) { JsonSerializer serializer = new JsonSerializer(); Event e = serializer.Deserialize<Event>(reader); Console.WriteLine(e.Name); // Movie Premiere } #endregion } } }
26.184211
123
0.58392
[ "MIT" ]
thehexgod/BESSy.JSON
Src/BESSy.Json.Tests/Documentation/Samples/Bson/DeserializeFromBson.cs
997
C#
using Sitecore.Data.Fields; using Sitecore.Resources.Media; namespace Constellation.Foundation.ModelMapping.FieldMappers { /// <inheritdoc /> /// <summary> /// Maps the MediaManager URL of an Image field to a Model Property suffixed with the word "Src". /// </summary> public class ImageSrcMapper : FieldAttributeMapper { /// <inheritdoc /> protected override string GetPropertyName() { return base.GetPropertyName() + "Src"; } /// <inheritdoc /> protected override object GetValueToAssign() { return GetUrlFromField(); } private string GetUrlFromField() { ImageField field = Field; var targetImage = field.MediaItem; if (targetImage != null) { var options = new MediaUrlOptions() { Language = targetImage.Language }; int width; if (int.TryParse(field.Width, out width) && width > 0) { options.Width = width; } int height; if (int.TryParse(field.Height, out height) && height > 0) { options.Height = height; } var innerUrl = MediaManager.GetMediaUrl(targetImage, options); var url = HashingUtils.ProtectAssetUrl(innerUrl); return url; } return string.Empty; } } }
21.305085
99
0.630072
[ "MIT" ]
verndale/constellation-sitecore9
Constellation.Foundation.ModelMapping/FieldMappers/ImageSrcMapper.cs
1,259
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 NProcessing.Properties { 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", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NProcessing.Properties.Resources", typeof(Resources).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)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap glyphicons_114_justify { get { object obj = ResourceManager.GetObject("glyphicons_114_justify", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap glyphicons_137_cogwheel { get { object obj = ResourceManager.GetObject("glyphicons_137_cogwheel", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap glyphicons_174_play { get { object obj = ResourceManager.GetObject("glyphicons_174_play", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap glyphicons_195_question_sign { get { object obj = ResourceManager.GetObject("glyphicons_195_question_sign", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap glyphicons_327_piano { get { object obj = ResourceManager.GetObject("glyphicons_327_piano", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap glyphicons_366_restart { get { object obj = ResourceManager.GetObject("glyphicons_366_restart", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap glyphicons_551_erase { get { object obj = ResourceManager.GetObject("glyphicons_551_erase", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> internal static System.Drawing.Icon Goupil { get { object obj = ResourceManager.GetObject("Goupil", resourceCulture); return ((System.Drawing.Icon)(obj)); } } } }
41.208333
177
0.580384
[ "MIT" ]
archive-for-processing/NProcessing
Properties/Resources.Designer.cs
5,936
C#
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.4 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ namespace libsbmlcs { using System; using System.Runtime.InteropServices; /** * @sbmlpackage{core} * @htmlinclude pkg-marker-core.html Implementation of SBML's %Event construct. * * An SBML Event object defines when the event can occur, the variables * that are affected by it, how the variables are affected, and the event's * relationship to other events. The effect of the event can optionally be * delayed after the occurrence of the condition which invokes it. * * The operation of Event is divided into two phases (even when the event * is not delayed): one when the event is @em triggered, and the other when * the event is @em executed. Trigger objects define the conditions for * triggering an event, Delay objects define when the event is actually * executed, EventAssignment objects define the effects of executing the * event, and (in SBML Level&nbsp;3) Priority objects influence the order * of EventAssignment performance in cases of simultaneous events. Please * consult the descriptions of Trigger, Delay, EventAssignment and Priority * for more information. * * @section version-diffs SBML Level/Version differences * * @subsection sbml-l3 SBML Level 3 * * SBML Level 3 introduces several changes to the structure and components * of Events compared to SBML Level&nbsp;2. These changes fall into two * main categories: changes to what is optional or required, and additions * of new attributes and elements. * <ul> * <li> The attribute 'useValuesFromTriggerTime' on Event is mandatory (it * was optional in Level&nbsp;2); * <li> Event's 'listOfEventAssignments' element (of class * ListOfEventAssignments) is optional (it was mandatory in Level&nbsp;2); * <li> Event's 'priority' element (of class Priority) is new in * Level&nbsp;3; and * <li> The Trigger object gains new mandatory attributes (described as part * of the definition of Trigger). * </ul> * * The changes to the attributes of Event are described below; the changes * to Trigger and Priority are described in their respective sections. * * @subsection sbml-l2 SBML Level 2 * * In SBML Level&nbsp;2 versions before Version&nbsp;4, the semantics of * Event time delays were defined such that the expressions in the event's * assignments were always evaluated at the time the event was * <em>triggered</em>. This definition made it difficult to define an event * whose assignment formulas were meant to be evaluated at the time the * event was <em>executed</em> (i.e., after the time period defined by the * value of the Delay element). In SBML Level&nbsp;2 Version&nbsp;4 and in * Level&nbsp;3, the attribute 'useValuesFromTriggerTime' on Event allows a * model to indicate the time at which the event's assignments are intended * the values of the assignment formulas are computed at the moment the * event is triggered, not after the delay. If 'useValuesFromTriggerTime'=@c * false, it means that the formulas in the event's assignments are to be * computed @em after the delay, at the time the event is executed. * * The definition of Event in SBML Level&nbsp;2 Versions 1 and 2 includes * an additional attribute called 'timeUnits', which allowed the time units * of the Delay to be set explicitly. Later Versions of SBML Level&nbsp;2 * as well as SBML Level&nbsp;3 do not define this attribute. LibSBML * supports this attribute for compatibility with previous versions of SBML * Level&nbsp;2; however, if a model in SBML Level&nbsp;3 or Level&nbsp;2 * Versions&nbsp;3&ndash;4 format sets the attribute, the * consistency-checking method SBMLDocument::checkConsistency() will report * an error. * * The attribute 'useValuesFromTriggerTime' was introduced in SBML * Level&nbsp;2 Version&nbsp;4. Models defined in prior Versions of SBML * Level&nbsp;2 cannot use this attribute, and * SBMLDocument::checkConsistency() will report an error if they do. * * @section semantics Semantics of events in SBML Level 3 Version&nbsp;1 * * The detailed semantics of events are described in the specification * documents for each SBML Level/Version. Here we include the description * from the SBML Level&nbsp;1 Version&nbsp;1. * Any transition of a Trigger object's 'math' formula from the value @c * false to @c true will cause the enclosing Event object to * <em>trigger</em>. Such a transition is not possible at the very start * of a simulation (i.e., at time <em>t = 0</em>) unless the Trigger * object's 'initialValue' attribute has a value of @c false; this defines * the value of the trigger formula to be @c false immediately prior to the * start of simulation, thereby giving it the potential to change in value * from @c false to @c true when the formula is evaluated at <em>t = * 0</em>. If 'initialValue'=@c true, then the trigger expression cannot * transition from @c false to @c true at <em>t = 0</em> but may do so at * some time <em>t > 0</em>. * * Consider an Event object definition <EM>E</EM> with delay <em>d</em> in * which the Trigger object's 'math' formula makes a transition in value * from @c false to @c true at times <em>t<sub>1</sub></em> and * <em>t<sub>2</sub></em>. The EventAssignment within the Event object * will have effect at <em>t<sub>1</sub> + d</em> and * <em>t<sub>2</sub> + d</em> irrespective of the relative times of * <em>t<sub>1</sub></em> and <em>t<sub>2</sub></em>. For example, events * can 'overlap' so that <em>t<sub>1</sub> < t<sub>2</sub> < * t<sub>1</sub> + d</em> still causes an event assignments to occur at * <em>t<sub>1</sub> + d</em> and <em>t<sub>2</sub> + d</em>. * * It is entirely possible for two events to be executed simultaneously, * and it is possible for events to trigger other events (i.e., an event * assignment can cause an event to trigger). This leads to several * points: * <ul> * * <li> A software package should retest all event triggers after executing * an event assignment in order to account for the possibility that the * assignment causes another event trigger to transition from @c false to * @c true. This check should be made after each individual Event object's * execution, even when several events are to be executed simultaneously. * * <li> Any Event object whose Trigger 'persistent' attribute has the value * @c false must have its trigger expression reevaluated continuously * between when the event is triggered and when it is executed. If * its trigger expression ever evaluates to @c false, it must be removed * from the queue of events pending execution and treated as any other * event whose trigger expression evaluates to @c false. * * <li> Although the precise time at which events are executed is not * resolved beyond the given execution point in simulated time, it is * assumed that the order in which the events occur <em>is</em> resolved. * This order can be significant in determining the overall outcome of a * given simulation. When an event <EM>X</EM> <em>triggers</em> another * event <EM>Y</EM> and event <EM>Y</EM> has zero delay, then event * <EM>Y</EM> is added to the existing set of simultaneous events that are * pending <em>execution</em>. Events <EM>X</EM> and <EM>Y</EM> form a * cascade of events at the same point in simulation time. An event such * as <EM>Y</EM> may have a special priority if it contains a Priority * subobject. * * <li> All events in a model are open to being in a cascade. The position * of an event in the event queue does not affect whether it can be in the * cascade: event <EM>Y</EM> can be triggered whether it is before or after * <EM>X</EM> in the queue of events pending execution. A cascade of * events can be potentially infinite (never terminate); when this occurs a * simulator should indicate this has occurred&mdash;it is incorrect for a * simulator to break a cascade arbitrarily and continue the simulation * without at least indicating that the infinite cascade occurred. * * <li> Simultaneous events having no defined priorities are executed in an * undefined order. This does not mean that the behavior of the simulation * is completely undefined; merely that the <em>order</em> of execution of * these particular events is undefined. A given simulator may use any * algorithm to choose an order as long as every event is executed exactly * once. * * <li> Events with defined priorities are executed in the order implied by * their Priority 'math' formula values, with events having higher * priorities being executed ahead of events with lower priorities, and * events with identical priorities being executed in a random order with * respect to one another (as determined at run-time by some random * algorithm equivalent to coin-flipping). Newly-triggered events that are * to be executed immediately (i.e., if they define no delays) should be * inserted into the queue of events pending execution according to their * priorities: events with higher priority values value must be inserted * ahead of events with lower priority values and after any pending events * with even higher priorities, and inserted randomly among pending events * with the same priority values. Events without Priority objects must be * inserted into the queue in some fashion, but the algorithm used to place * it in the queue is undefined. Similarly, there is no restriction on the * order of a newly-inserted event with a defined Priority with respect to * any other pending Event without a defined Priority. * * <li> A model variable that is the target of one or more event * assignments can change more than once when simultaneous events are * processed at some time point <em>t</em>. The model's behavior (output) * for such a variable is the value of the variable at the end of * processing all the simultaneous events at time <em>t</em>. * * </ul> * * @see Trigger * @see Priority * @see Delay * @see EventAssignment * * * */ public class Event : SBase { private HandleRef swigCPtr; internal Event(IntPtr cPtr, bool cMemoryOwn) : base(libsbmlPINVOKE.Event_SWIGUpcast(cPtr), cMemoryOwn) { //super(libsbmlPINVOKE.EventUpcast(cPtr), cMemoryOwn); swigCPtr = new HandleRef(this, cPtr); } internal static HandleRef getCPtr(Event obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } internal static HandleRef getCPtrAndDisown (Event obj) { HandleRef ptr = new HandleRef(null, IntPtr.Zero); if (obj != null) { ptr = obj.swigCPtr; obj.swigCMemOwn = false; } return ptr; } ~Event() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; libsbmlPINVOKE.delete_Event(swigCPtr); } swigCPtr = new HandleRef(null, IntPtr.Zero); } GC.SuppressFinalize(this); base.Dispose(); } } /** * Creates a new Event using the given SBML @p level and @p version * values. * * @param level a long integer, the SBML Level to assign to this Event * * @param version a long integer, the SBML Version to assign to this * Event * * @throws @if python ValueError @else SBMLConstructorException @endif * Thrown if the given @p level and @p version combination, or this kind * of SBML object, are either invalid or mismatched with respect to the * parent SBMLDocument object. * * * * @note Upon the addition of an Event object to an SBMLDocument (e.g., using * Model::addEvent(@if java Event e@endif)), the SBML Level, SBML Version and * XML namespace of the document @em override the values used when creating * the Event object via this constructor. This is necessary to ensure that * an SBML document is a consistent structure. Nevertheless, the ability to * supply the values at the time of creation of an Event is an important aid * to producing valid SBML. Knowledge of the intented SBML Level and Version * determine whether it is valid to assign a particular value to an * attribute, or whether it is valid to add an object to an existing * SBMLDocument. * */ public Event(long level, long version) : this(libsbmlPINVOKE.new_Event__SWIG_0(level, version), true) { if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Creates a new Event using the given SBMLNamespaces object * @p sbmlns. * * * * * The SBMLNamespaces object encapsulates SBML Level/Version/namespaces * information. It is used to communicate the SBML Level, Version, and (in * Level&nbsp;3) packages used in addition to SBML Level&nbsp;3 Core. A * common approach to using libSBML's SBMLNamespaces facilities is to create an * SBMLNamespaces object somewhere in a program once, then hand that object * as needed to object constructors that accept SBMLNamespaces as arguments. * * * * @param sbmlns an SBMLNamespaces object. * * @throws @if python ValueError @else SBMLConstructorException @endif * Thrown if the given @p level and @p version combination, or this kind * of SBML object, are either invalid or mismatched with respect to the * parent SBMLDocument object. * * * * @note Upon the addition of an Event object to an SBMLDocument (e.g., using * Model::addEvent(@if java Event e@endif)), the SBML Level, SBML Version and * XML namespace of the document @em override the values used when creating * the Event object via this constructor. This is necessary to ensure that * an SBML document is a consistent structure. Nevertheless, the ability to * supply the values at the time of creation of an Event is an important aid * to producing valid SBML. Knowledge of the intented SBML Level and Version * determine whether it is valid to assign a particular value to an * attribute, or whether it is valid to add an object to an existing * SBMLDocument. * */ public Event(SBMLNamespaces sbmlns) : this(libsbmlPINVOKE.new_Event__SWIG_1(SBMLNamespaces.getCPtr(sbmlns)), true) { if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Copy constructor; creates a copy of this Event. * * @param orig the object to copy. * * @throws @if python ValueError @else SBMLConstructorException @endif * Thrown if the argument @p orig is @c null. */ public Event(Event orig) : this(libsbmlPINVOKE.new_Event__SWIG_2(Event.getCPtr(orig)), true) { if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Creates and returns a deep copy of this Event. * * @return a (deep) copy of this Event. */ public new Event clone() { IntPtr cPtr = libsbmlPINVOKE.Event_clone(swigCPtr); Event ret = (cPtr == IntPtr.Zero) ? null : new Event(cPtr, true); return ret; } /** * Returns the first child element found that has the given @p id in the * model-wide SId namespace, or @c null if no such object is found. * * @param id string representing the id of objects to find * * @return pointer to the first element found with the given @p id. */ public SBase getElementBySId(string id) { SBase ret = (SBase) libsbml.DowncastSBase(libsbmlPINVOKE.Event_getElementBySId(swigCPtr, id), false); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); return ret; } /** * Returns the first child element it can find with the given @p metaid, or * @c null if no such object is found. * * @param metaid string representing the metaid of objects to find * * @return pointer to the first element found with the given @p metaid. */ public SBase getElementByMetaId(string metaid) { SBase ret = (SBase) libsbml.DowncastSBase(libsbmlPINVOKE.Event_getElementByMetaId(swigCPtr, metaid), false); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); return ret; } /** * Returns the value of the 'id' attribute of this Event. * * @return the id of this Event. */ public new string getId() { string ret = libsbmlPINVOKE.Event_getId(swigCPtr); return ret; } /** * Returns the value of the 'name' attribute of this Event. * * @return the name of this Event. */ public new string getName() { string ret = libsbmlPINVOKE.Event_getName(swigCPtr); return ret; } /** * Get the event trigger portion of this Event. * * @return the Trigger object of this Event. */ public Trigger getTrigger() { IntPtr cPtr = libsbmlPINVOKE.Event_getTrigger__SWIG_0(swigCPtr); Trigger ret = (cPtr == IntPtr.Zero) ? null : new Trigger(cPtr, false); return ret; } /** * Get the assignment delay portion of this Event, if there is one. * * @return the delay of this Event if one is defined, or @c null if none * is defined. */ public Delay getDelay() { IntPtr cPtr = libsbmlPINVOKE.Event_getDelay__SWIG_0(swigCPtr); Delay ret = (cPtr == IntPtr.Zero) ? null : new Delay(cPtr, false); return ret; } /** * (SBML Level&nbsp;3 only) Get the event priority portion of this * Event. * * @return the Priority object of this Event. * * @note The element 'priority' is available in SBML Level&nbsp;3 * Version&nbsp;1 Core, but is not present in lower Levels of SBML. */ public Priority getPriority() { IntPtr cPtr = libsbmlPINVOKE.Event_getPriority__SWIG_0(swigCPtr); Priority ret = (cPtr == IntPtr.Zero) ? null : new Priority(cPtr, false); return ret; } /** * Get the value of the 'timeUnits' attribute of this Event, if it has one. * * @return the value of the attribute 'timeUnits' as a string. * * * * @warning <span class='warning'>Definitions of Event in SBML Level 2 * Versions&nbsp;1 and&nbsp;2 included the additional attribute called * 'timeUnits', but it was removed in SBML Level&nbsp;2 Version&nbsp;3. * LibSBML supports this attribute for compatibility with previous versions * of SBML Level&nbsp;2, but its use is discouraged since models in * Level&nbsp;2 Versions&nbsp;3 and&nbsp;4 cannot contain it. If a * Version&nbsp;3 or&nbsp;4 model sets the attribute, the * consistency-checking method SBMLDocument::checkConsistency() will report * an error.</span> * */ public string getTimeUnits() { string ret = libsbmlPINVOKE.Event_getTimeUnits(swigCPtr); return ret; } /** * Get the value of the 'useValuesFromTriggerTime' attribute of this Event. * * * * * The optional Delay on Event means there are two times to consider when * computing the results of an event: the time at which the event is * <em>triggered</em>, and the time at which assignments are * <em>executed</em>. It is also possible to distinguish between the * time at which the EventAssignment's expression is calculated, and the * time at which the assignment is made: the expression could be * evaluated at the same time the assignments are performed, i.e., when * the event is <em>executed</em>, but it could also be defined to be * evaluated at the time the event is <em>triggered</em>. * * In SBML Level&nbsp;2 versions prior to Version&nbsp;4, the semantics * of Event time delays were defined such that the expressions in the * event's assignments were always evaluated at the time the event was * <em>triggered</em>. This definition made it difficult to define an * event whose assignment formulas were meant to be evaluated at the time * the event was <em>executed</em> (i.e., after the time period defined * by the value of the Delay element). In SBML Level&nbsp;2 * Version&nbsp;4, the attribute 'useValuesFromTriggerTime' on Event * allows a model to indicate the time at which the event's assignments * are intended to be evaluated. In SBML Level&nbsp;2, the attribute has * a default value of @c true, which corresponds to the interpretation of * event assignments prior to Version&nbsp;4: the values of the * assignment formulas are computed at the moment the event is triggered, * not after the delay. If 'useValuesFromTriggerTime'=@c false, it means * that the formulas in the event's assignments are to be computed after * the delay, at the time the event is executed. In SBML Level&nbsp;3, * the attribute is mandatory, not optional, and all events must specify * a value for it. * * * @return the value of the attribute 'useValuesFromTriggerTime' as a bool. * * * * @warning <span class='warning'>The attribute 'useValuesFromTriggerTime' * was introduced in SBML Level&nbsp;2 Version&nbsp;4. It is not valid in * models defined using SBML Level&nbsp;2 versions prior to Version&nbsp;4. * If a Level&nbsp;2 Version&nbsp;1&ndash;3 model sets the attribute, the * consistency-checking method SBMLDocument::checkConsistency() will report * an error.</span> * */ public bool getUseValuesFromTriggerTime() { bool ret = libsbmlPINVOKE.Event_getUseValuesFromTriggerTime(swigCPtr); return ret; } /** * Predicate returning @c true if this * Event's 'id' attribute is set. * * @return @c true if the 'id' attribute of this Event is * set, @c false otherwise. */ public new bool isSetId() { bool ret = libsbmlPINVOKE.Event_isSetId(swigCPtr); return ret; } /** * Predicate returning @c true if this * Event's 'name' attribute is set. * * @return @c true if the 'name' attribute of this Event is * set, @c false otherwise. */ public new bool isSetName() { bool ret = libsbmlPINVOKE.Event_isSetName(swigCPtr); return ret; } /** * Predicate for testing whether the trigger for this Event is set. * * @return @c true if the trigger of this Event is set, @c false * otherwise. */ public bool isSetTrigger() { bool ret = libsbmlPINVOKE.Event_isSetTrigger(swigCPtr); return ret; } /** * Predicate for testing whether the delay for this Event is set. * * @return @c true if the delay of this Event is set, @c false * otherwise. */ public bool isSetDelay() { bool ret = libsbmlPINVOKE.Event_isSetDelay(swigCPtr); return ret; } /** * (SBML Level&nbsp;3 only) Predicate for testing whether the priority * for this Event is set. * * @return @c true if the priority of this Event is set, @c false * otherwise. * * @note The element 'priority' is available in SBML Level&nbsp;3 * Version&nbsp;1 Core, but is not present in lower Levels of SBML. */ public bool isSetPriority() { bool ret = libsbmlPINVOKE.Event_isSetPriority(swigCPtr); return ret; } /** * Predicate for testing whether the 'timeUnits' attribute of this Event * is set. * * @return @c true if the 'timeUnits' attribute of this Event is * set, @c false otherwise. * * * * @warning <span class='warning'>Definitions of Event in SBML Level 2 * Versions&nbsp;1 and&nbsp;2 included the additional attribute called * 'timeUnits', but it was removed in SBML Level&nbsp;2 Version&nbsp;3. * LibSBML supports this attribute for compatibility with previous versions * of SBML Level&nbsp;2, but its use is discouraged since models in * Level&nbsp;2 Versions&nbsp;3 and&nbsp;4 cannot contain it. If a * Version&nbsp;3 or&nbsp;4 model sets the attribute, the * consistency-checking method SBMLDocument::checkConsistency() will report * an error.</span> * */ public bool isSetTimeUnits() { bool ret = libsbmlPINVOKE.Event_isSetTimeUnits(swigCPtr); return ret; } /** * Predicate for testing whether the 'useValuesFromTriggerTime' attribute of this Event * is set. * * @return @c true if the 'useValuesFromTriggerTime' attribute of this Event is * set, @c false otherwise. * * @note In SBML Level&nbsp;2, this attribute is optional and has a default value of * @c true, whereas in Level&nbsp;3 Version&nbsp;1, this optional is mandatory and * has no default value. */ public bool isSetUseValuesFromTriggerTime() { bool ret = libsbmlPINVOKE.Event_isSetUseValuesFromTriggerTime(swigCPtr); return ret; } /** * Sets the value of the 'id' attribute of this Event. * * The string @p sid is copied. * * * * * SBML has strict requirements for the syntax of identifiers, that is, the * values of the 'id' attribute present on most types of SBML objects. * The following is a summary of the definition of the SBML identifier type * <code>SId</code>, which defines the permitted syntax of identifiers. We * express the syntax using an extended form of BNF notation: * <pre style='margin-left: 2em; border: none; font-weight: bold; font-size: 13px; color: black'> * letter ::= 'a'..'z','A'..'Z' * digit ::= '0'..'9' * idChar ::= letter | digit | '_' * SId ::= ( letter | '_' ) idChar* * </pre> * The characters <code>(</code> and <code>)</code> are used for grouping, the * character <code>*</code> 'zero or more times', and the character * <code>|</code> indicates logical 'or'. The equality of SBML identifiers is * determined by an exact character sequence match; i.e., comparisons must be * performed in a case-sensitive manner. In addition, there are a few * conditions for the uniqueness of identifiers in an SBML model. Please * consult the SBML specifications for the exact details of the uniqueness * requirements. * * * * @param sid the string to use as the identifier of this Event * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE LIBSBML_INVALID_ATTRIBUTE_VALUE @endlink */ public new int setId(string sid) { int ret = libsbmlPINVOKE.Event_setId(swigCPtr, sid); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); return ret; } /** * Sets the value of the 'name' attribute of this Event. * * The string in @p name is copied. * * @param name the new name for the Event * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE LIBSBML_INVALID_ATTRIBUTE_VALUE @endlink */ public new int setName(string name) { int ret = libsbmlPINVOKE.Event_setName(swigCPtr, name); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); return ret; } /** * Sets the trigger definition of this Event to a copy of the given * Trigger object instance. * * @param trigger the Trigger object instance to use. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_LEVEL_MISMATCH LIBSBML_LEVEL_MISMATCH @endlink * @li @link libsbmlcs.libsbml.LIBSBML_VERSION_MISMATCH LIBSBML_VERSION_MISMATCH @endlink */ public int setTrigger(Trigger trigger) { int ret = libsbmlPINVOKE.Event_setTrigger(swigCPtr, Trigger.getCPtr(trigger)); return ret; } /** * Sets the delay definition of this Event to a copy of the given Delay * object instance. * * @param delay the Delay object instance to use * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_LEVEL_MISMATCH LIBSBML_LEVEL_MISMATCH @endlink * @li @link libsbmlcs.libsbml.LIBSBML_VERSION_MISMATCH LIBSBML_VERSION_MISMATCH @endlink */ public int setDelay(Delay delay) { int ret = libsbmlPINVOKE.Event_setDelay(swigCPtr, Delay.getCPtr(delay)); return ret; } /** * (SBML Level&nbsp;3 only) Sets the priority definition of this Event * to a copy of the given Priority object instance. * * @param priority the Priority object instance to use * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_LEVEL_MISMATCH LIBSBML_LEVEL_MISMATCH @endlink * @li @link libsbmlcs.libsbml.LIBSBML_VERSION_MISMATCH LIBSBML_VERSION_MISMATCH @endlink * @li @link libsbmlcs.libsbml.LIBSBML_UNEXPECTED_ATTRIBUTE LIBSBML_UNEXPECTED_ATTRIBUTE @endlink * * @note The element 'priority' is available in SBML Level&nbsp;3 * Version&nbsp;1 Core, but is not present in lower Levels of SBML. */ public int setPriority(Priority priority) { int ret = libsbmlPINVOKE.Event_setPriority(swigCPtr, Priority.getCPtr(priority)); return ret; } /** * Sets the 'timeUnits' attribute of this Event to a copy of @p sid. * * @param sid the identifier of the time units to use. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE LIBSBML_INVALID_ATTRIBUTE_VALUE @endlink * @li @link libsbmlcs.libsbml.LIBSBML_UNEXPECTED_ATTRIBUTE LIBSBML_UNEXPECTED_ATTRIBUTE @endlink * * * * @warning <span class='warning'>Definitions of Event in SBML Level 2 * Versions&nbsp;1 and&nbsp;2 included the additional attribute called * 'timeUnits', but it was removed in SBML Level&nbsp;2 Version&nbsp;3. * LibSBML supports this attribute for compatibility with previous versions * of SBML Level&nbsp;2, but its use is discouraged since models in * Level&nbsp;2 Versions&nbsp;3 and&nbsp;4 cannot contain it. If a * Version&nbsp;3 or&nbsp;4 model sets the attribute, the * consistency-checking method SBMLDocument::checkConsistency() will report * an error.</span> * * */ public int setTimeUnits(string sid) { int ret = libsbmlPINVOKE.Event_setTimeUnits(swigCPtr, sid); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); return ret; } /** * Sets the 'useValuesFromTriggerTime' attribute of this Event to a @p value. * * * * * The optional Delay on Event means there are two times to consider when * computing the results of an event: the time at which the event is * <em>triggered</em>, and the time at which assignments are * <em>executed</em>. It is also possible to distinguish between the * time at which the EventAssignment's expression is calculated, and the * time at which the assignment is made: the expression could be * evaluated at the same time the assignments are performed, i.e., when * the event is <em>executed</em>, but it could also be defined to be * evaluated at the time the event is <em>triggered</em>. * * In SBML Level&nbsp;2 versions prior to Version&nbsp;4, the semantics * of Event time delays were defined such that the expressions in the * event's assignments were always evaluated at the time the event was * <em>triggered</em>. This definition made it difficult to define an * event whose assignment formulas were meant to be evaluated at the time * the event was <em>executed</em> (i.e., after the time period defined * by the value of the Delay element). In SBML Level&nbsp;2 * Version&nbsp;4, the attribute 'useValuesFromTriggerTime' on Event * allows a model to indicate the time at which the event's assignments * are intended to be evaluated. In SBML Level&nbsp;2, the attribute has * a default value of @c true, which corresponds to the interpretation of * event assignments prior to Version&nbsp;4: the values of the * assignment formulas are computed at the moment the event is triggered, * not after the delay. If 'useValuesFromTriggerTime'=@c false, it means * that the formulas in the event's assignments are to be computed after * the delay, at the time the event is executed. In SBML Level&nbsp;3, * the attribute is mandatory, not optional, and all events must specify * a value for it. * * * @param value the value of useValuesFromTriggerTime to use. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_UNEXPECTED_ATTRIBUTE LIBSBML_UNEXPECTED_ATTRIBUTE @endlink * * * * @warning <span class='warning'>The attribute 'useValuesFromTriggerTime' * was introduced in SBML Level&nbsp;2 Version&nbsp;4. It is not valid in * models defined using SBML Level&nbsp;2 versions prior to Version&nbsp;4. * If a Level&nbsp;2 Version&nbsp;1&ndash;3 model sets the attribute, the * consistency-checking method SBMLDocument::checkConsistency() will report * an error.</span> * */ public int setUseValuesFromTriggerTime(bool value) { int ret = libsbmlPINVOKE.Event_setUseValuesFromTriggerTime(swigCPtr, value); return ret; } /** * Unsets the value of the 'id' attribute of this Event. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink */ public new int unsetId() { int ret = libsbmlPINVOKE.Event_unsetId(swigCPtr); return ret; } /** * Unsets the value of the 'name' attribute of this Event. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink */ public new int unsetName() { int ret = libsbmlPINVOKE.Event_unsetName(swigCPtr); return ret; } /** * Unsets the Delay of this Event. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink */ public int unsetDelay() { int ret = libsbmlPINVOKE.Event_unsetDelay(swigCPtr); return ret; } /** * (SBML Level&nbsp;3 only) Unsets the Priority of this Event. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink * * @note The element 'priority' is available in SBML Level&nbsp;3 * Version&nbsp;1 Core, but is not present in lower Levels of SBML. */ public int unsetPriority() { int ret = libsbmlPINVOKE.Event_unsetPriority(swigCPtr); return ret; } /** * Unsets the Trigger of this Event. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink * * @note The element 'priority' is available in SBML Level&nbsp;3 * Version&nbsp;1 Core, but is not present in lower Levels of SBML. */ public int unsetTrigger() { int ret = libsbmlPINVOKE.Event_unsetTrigger(swigCPtr); return ret; } /** * Unsets the 'timeUnits' attribute of this Event. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_UNEXPECTED_ATTRIBUTE LIBSBML_UNEXPECTED_ATTRIBUTE @endlink * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink * * * * @warning <span class='warning'>Definitions of Event in SBML Level 2 * Versions&nbsp;1 and&nbsp;2 included the additional attribute called * 'timeUnits', but it was removed in SBML Level&nbsp;2 Version&nbsp;3. * LibSBML supports this attribute for compatibility with previous versions * of SBML Level&nbsp;2, but its use is discouraged since models in * Level&nbsp;2 Versions&nbsp;3 and&nbsp;4 cannot contain it. If a * Version&nbsp;3 or&nbsp;4 model sets the attribute, the * consistency-checking method SBMLDocument::checkConsistency() will report * an error.</span> * */ public int unsetTimeUnits() { int ret = libsbmlPINVOKE.Event_unsetTimeUnits(swigCPtr); return ret; } /** * Appends a copy of the given EventAssignment to this Event. * * @param ea the EventAssignment object to add. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_LEVEL_MISMATCH LIBSBML_LEVEL_MISMATCH @endlink * @li @link libsbmlcs.libsbml.LIBSBML_VERSION_MISMATCH LIBSBML_VERSION_MISMATCH @endlink * @li @link libsbmlcs.libsbml.LIBSBML_DUPLICATE_OBJECT_ID LIBSBML_DUPLICATE_OBJECT_ID @endlink * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink * * * * @note This method should be used with some caution. The fact that this * method @em copies the object passed to it means that the caller will be * left holding a physically different object instance than the one contained * inside this object. Changes made to the original object instance (such as * resetting attribute values) will <em>not affect the instance in this * object</em>. In addition, the caller should make sure to free the * original object if it is no longer being used, or else a memory leak will * result. Please see other methods on this class (particularly a * corresponding method whose name begins with the word <code>create</code>) * for alternatives that do not lead to these issues. * * * * @see createEventAssignment() */ public int addEventAssignment(EventAssignment ea) { int ret = libsbmlPINVOKE.Event_addEventAssignment(swigCPtr, EventAssignment.getCPtr(ea)); return ret; } /** * Creates a new, empty EventAssignment, adds it to this Event's list of * event assignments and returns the EventAssignment. * * @return the newly created EventAssignment object instance * * @see addEventAssignment(EventAssignment ea) */ public EventAssignment createEventAssignment() { IntPtr cPtr = libsbmlPINVOKE.Event_createEventAssignment(swigCPtr); EventAssignment ret = (cPtr == IntPtr.Zero) ? null : new EventAssignment(cPtr, false); return ret; } /** * Creates a new, empty Trigger, adds it to this Event and * returns the Trigger. * * @return the newly created Trigger object instance */ public Trigger createTrigger() { IntPtr cPtr = libsbmlPINVOKE.Event_createTrigger(swigCPtr); Trigger ret = (cPtr == IntPtr.Zero) ? null : new Trigger(cPtr, false); return ret; } /** * Creates a new, empty Delay, adds it to this Event and * returns the Delay. * * @return the newly created Delay object instance */ public Delay createDelay() { IntPtr cPtr = libsbmlPINVOKE.Event_createDelay(swigCPtr); Delay ret = (cPtr == IntPtr.Zero) ? null : new Delay(cPtr, false); return ret; } /** * (SBML Level&nbsp;3 only) Creates a new, empty Priority, adds it to this * Event and returns the Priority. * * @return the newly created Priority object instance * * @note The element 'priority' is available in SBML Level&nbsp;3 * Version&nbsp;1 Core, but is not present in lower Levels of SBML. */ public Priority createPriority() { IntPtr cPtr = libsbmlPINVOKE.Event_createPriority(swigCPtr); Priority ret = (cPtr == IntPtr.Zero) ? null : new Priority(cPtr, false); return ret; } /** * Returns the list of event assignments for this Event. * * @return the list of EventAssignments for this Event. */ public ListOfEventAssignments getListOfEventAssignments() { IntPtr cPtr = libsbmlPINVOKE.Event_getListOfEventAssignments__SWIG_0(swigCPtr); ListOfEventAssignments ret = (cPtr == IntPtr.Zero) ? null : new ListOfEventAssignments(cPtr, false); return ret; } /** * Return a specific EventAssignment object of this Event. * * @param n an integer, the index of the EventAssignment object to return * * @return the <code>n</code>th EventAssignment of this Event. */ public EventAssignment getEventAssignment(long n) { IntPtr cPtr = libsbmlPINVOKE.Event_getEventAssignment__SWIG_0(swigCPtr, n); EventAssignment ret = (cPtr == IntPtr.Zero) ? null : new EventAssignment(cPtr, false); return ret; } /** * Return the event assignment indicated by the given @p variable. * * @param variable a string, the identifier of the variable whose * EventAssignment is being sought. * * @return the EventAssignment for the given @p variable, or @c null if * no such EventAssignment exits. */ public EventAssignment getEventAssignment(string variable) { IntPtr cPtr = libsbmlPINVOKE.Event_getEventAssignment__SWIG_2(swigCPtr, variable); EventAssignment ret = (cPtr == IntPtr.Zero) ? null : new EventAssignment(cPtr, false); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); return ret; } /** * Returns the number of EventAssignment objects attached to this * Event. * * @return the number of EventAssignments in this Event. */ public long getNumEventAssignments() { return (long)libsbmlPINVOKE.Event_getNumEventAssignments(swigCPtr); } /** * Removes the nth EventAssignment object from this Event object and * returns a pointer to it. * * The caller owns the returned object and is responsible for deleting it. * * @param n the index of the EventAssignment object to remove * * @return the EventAssignment object removed. As mentioned above, * the caller owns the returned item. @c null is returned if the given index * is out of range. * */ public EventAssignment removeEventAssignment(long n) { IntPtr cPtr = libsbmlPINVOKE.Event_removeEventAssignment__SWIG_0(swigCPtr, n); EventAssignment ret = (cPtr == IntPtr.Zero) ? null : new EventAssignment(cPtr, true); return ret; } /** * Removes the EventAssignment object with the given 'variable' attribute * from this Event object and returns a pointer to it. * * The caller owns the returned object and is responsible for deleting it. * If none of the EventAssignment objects in this Event object have the * 'variable' attribute @p variable, then @c null is returned. * * @param variable the 'variable' attribute of the EventAssignment object * to remove * * @return the EventAssignment object removed. As mentioned above, the * caller owns the returned object. @c null is returned if no EventAssignment * object with the 'variable' attribute exists in this Event object. */ public EventAssignment removeEventAssignment(string variable) { IntPtr cPtr = libsbmlPINVOKE.Event_removeEventAssignment__SWIG_1(swigCPtr, variable); EventAssignment ret = (cPtr == IntPtr.Zero) ? null : new EventAssignment(cPtr, true); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); return ret; } /** * Sets this SBML object to child SBML objects (if any). * (Creates a child-parent relationship by the parent) * * Subclasses must override this function if they define * one ore more child elements. * Basically, this function needs to be called in * constructor, copy constructor and assignment operator. * * @see setSBMLDocument * @see enablePackageInternal */ /* libsbml-internal */ public new void connectToChild() { libsbmlPINVOKE.Event_connectToChild(swigCPtr); } /** * Enables/Disables the given package with this element and child * elements (if any). * (This is an internal implementation for enablePackage function) * * @note Subclasses of the SBML Core package in which one or more child * elements are defined must override this function. */ /* libsbml-internal */ public new void enablePackageInternal(string pkgURI, string pkgPrefix, bool flag) { libsbmlPINVOKE.Event_enablePackageInternal(swigCPtr, pkgURI, pkgPrefix, flag); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Returns the libSBML type code of this object instance. * * * * * LibSBML attaches an identifying code to every kind of SBML object. These * are integer constants known as <em>SBML type codes</em>. The names of all * the codes begin with the characters &ldquo;<code>SBML_</code>&rdquo;. * @if clike The set of possible type codes for core elements is defined in * the enumeration #SBMLTypeCode_t, and in addition, libSBML plug-ins for * SBML Level&nbsp;3 packages define their own extra enumerations of type * codes (e.g., #SBMLLayoutTypeCode_t for the Level&nbsp;3 Layout * package).@endif@if java In the Java language interface for libSBML, the * type codes are defined as static integer constants in the interface class * {@link libsbmlConstants}. @endif@if python In the Python language * interface for libSBML, the type codes are defined as static integer * constants in the interface class @link libsbml@endlink.@endif@if csharp In * the C# language interface for libSBML, the type codes are defined as * static integer constants in the interface class * @link libsbmlcs.libsbml@endlink.@endif Note that different Level&nbsp;3 * package plug-ins may use overlapping type codes; to identify the package * to which a given object belongs, call the <code>getPackageName()</code> * method on the object. * * * * @return the SBML type code for this object: * @link libsbmlcs.libsbml.SBML_EVENT SBML_EVENT@endlink (default). * * * * @warning <span class='warning'>The specific integer values of the possible * type codes may be reused by different Level&nbsp;3 package plug-ins. * Thus, to identifiy the correct code, <strong>it is necessary to invoke * both getTypeCode() and getPackageName()</strong>.</span> * * * * @see getElementName() * @see getPackageName() */ public new int getTypeCode() { int ret = libsbmlPINVOKE.Event_getTypeCode(swigCPtr); return ret; } /** * Returns the XML element name of this object, which for Event, is * always @c 'event'. * * @return the name of this element, i.e., @c 'event'. */ public new string getElementName() { string ret = libsbmlPINVOKE.Event_getElementName(swigCPtr); return ret; } /** * Predicate returning @c true if all the required attributes for this * Event object have been set. * * @note The required attributes for an Event object are: * @li 'useValuesfromTriggerTime' (required in SBML Level&nbsp;3) */ public new bool hasRequiredAttributes() { bool ret = libsbmlPINVOKE.Event_hasRequiredAttributes(swigCPtr); return ret; } /** * Predicate returning @c true if * all the required elements for the given Event_t structure * have been set. * * @note The required elements for an Event object are: * @li 'trigger' * @li 'listOfEventAssignments' (required in SBML Level&nbsp;2, optional in Level&nbsp;3) */ public new bool hasRequiredElements() { bool ret = libsbmlPINVOKE.Event_hasRequiredElements(swigCPtr); return ret; } } }
40.074603
110
0.722462
[ "Apache-2.0" ]
0u812/roadrunner
third_party/libSBML-5.10.0-Source/src/bindings/csharp/csharp-files/Event.cs
50,494
C#
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; public class LevelSelect : MonoBehaviour { void Start(){ Button btn = gameObject.GetComponent<Button> (); btn.onClick.AddListener (TaskOnClick); } void TaskOnClick(){ SceneManager.LoadScene ("LevelSelectScreen"); } }
19.588235
50
0.75976
[ "MIT" ]
alexlo94/BulletHellGames
Vertical Bullet Hell/Assets/Scripts/LevelSelect.cs
335
C#
using System; using System.Collections.Generic; using ThreatsManager.Interfaces.ObjectModel.Entities; namespace ThreatsManager.Interfaces.ObjectModel.Diagrams { /// <summary> /// Interface implemented by the containers of Diagrams. /// </summary> public interface IDiagramsContainer { /// <summary> /// Event raised when an Entity Shape is added to a Diagram. /// </summary> event Action<IEntityShapesContainer, IEntityShape> EntityShapeAdded; /// <summary> /// Event raised when an Entity Shape is removed from a Diagram. /// </summary> event Action<IEntityShapesContainer, IEntity> EntityShapeRemoved; /// <summary> /// Event raised when a Group Shape is added to a Diagram. /// </summary> event Action<IGroupShapesContainer, IGroupShape> GroupShapeAdded; /// <summary> /// Event raised when a Group Shape is removed from a Diagram. /// </summary> event Action<IGroupShapesContainer, IGroup> GroupShapeRemoved; /// <summary> /// Event raised when a Link is added to a Diagram. /// </summary> event Action<ILinksContainer, ILink> LinkAdded; /// <summary> /// Event raised when a Link is removed from a Diagram. /// </summary> event Action<ILinksContainer, IDataFlow> LinkRemoved; /// <summary> /// Enumeration of the Diagrams. /// </summary> IEnumerable<IDiagram> Diagrams { get; } /// <summary> /// Get an enumeration of Diagrams by name. /// </summary> /// <param name="name">Name of the Diagram.</param> /// <returns>Enumeration of all the Diagrams with the specified name.</returns> IEnumerable<IDiagram> GetDiagrams(string name); /// <summary> /// Get a Diagram by ID. /// </summary> /// <param name="id">Identifier of the Diagram.</param> /// <returns>Object representing the Diagram, if found.</returns> IDiagram GetDiagram(Guid id); /// <summary> /// Adds the Diagram passed as argument to the container. /// </summary> /// <param name="diagram">Diagram to be added to the container.</param> /// <exception cref="ArgumentException">The argument is not associated to the same Threat Model of the Container.</exception> void Add(IDiagram diagram); /// <summary> /// Add a Diagram, assigning the name automatically. /// </summary> /// <returns>New instance of the Diagram.</returns> IDiagram AddDiagram(); /// <summary> /// Add a Diagram. /// </summary> /// <param name="name">Name of the Diagram.</param> /// <returns>New instance of the Diagram.</returns> /// <remarks>The Name of the Diagram can be changed.</remarks> IDiagram AddDiagram(string name); /// <summary> /// Remove the Diagram whose ID is passed as argument. /// </summary> /// <param name="id">Identifier of the Diagram.</param> /// <returns>True if the Diagram has been found and removed, false otherwise.</returns> bool RemoveDiagram(Guid id); } }
36.752809
133
0.603791
[ "MIT" ]
simonec73/threatsmanager
Sources/ThreatsManager.Interfaces/ObjectModel/Diagrams/IDiagramsContainer.cs
3,273
C#
namespace AbstractFactoryImpl { public class TeleCallerFactory : ChannelFactory { public override Order CreateElectronicOrder() { return new ElectronicOrder(); } public override Order CreateFurnitureOrder() { return new FurnitureOrder(); } public override Order CreateToysOrder() { return new ToysOrder(); } } }
21.7
53
0.571429
[ "MIT" ]
sounakofficial/ADMDF
SOLID_HandsOn/SOLID_Final_Check/AbstractFactoryImpl/TeleCallerFactory.cs
436
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using StackifyLib.Models; using log4net.Core; using log4net; using StackifyLib; namespace StackifyLib { public static class Extensions { private static LogMessage GetMessage(string message, object debugData) { return new LogMessage() { message = message, json = debugData }; } public static void Debug(this ILog log, string message, object debugData) { log.Debug(GetMessage(message, debugData)); } public static void Info(this ILog log, string message, object debugData) { log.Info(GetMessage(message, debugData)); } public static void Warn(this ILog log, string message, object debugData) { log.Warn(GetMessage(message, debugData)); } public static void Warn(this ILog log, string message, object debugData, Exception exception) { log.Warn(GetMessage(message, debugData), exception); } public static void Error(this ILog log, string message, object debugData) { log.Error(GetMessage(message, debugData)); } public static void Error(this ILog log, string message, object debugData, Exception exception) { log.Error(GetMessage(message, debugData), exception); } public static void Fatal(this ILog log, string message, object debugData) { log.Fatal(GetMessage(message, debugData)); } public static void Fatal(this ILog log, string message, object debugData, Exception exception) { log.Fatal(GetMessage(message, debugData), exception); } } }
29.459016
102
0.633834
[ "Apache-2.0" ]
homiedopie/stackify-api-dotnet
Src/StackifyLib.log4net.v1_2_10/Log4NetExtensions.cs
1,799
C#
using UnityEngine; using UnityEngine.UI; public class ArrowButton : MonoBehaviour { [SerializeField] private bool _isRight; private Button _button; void Awake() { _button = gameObject.GetComponent<Button>(); _button.onClick.AddListener(Click); } void Click() { if (_isRight) ChairSliderEvents.Slide(Vector2.left, AnimationDurations.current.itemAnimationDuration); else ChairSliderEvents.Slide(Vector2.right, AnimationDurations.current.itemAnimationDuration); } private void OnDestroy() { _button.onClick.RemoveAllListeners(); } }
21.633333
101
0.662558
[ "MIT" ]
Liquid-ART/VR-color-selector-and-slider-experiment
Assets/ChairSlider/Scripts/ArrowButton.cs
651
C#
using System; namespace Trivadis.AzureBootcamp.CrossCutting.Logging.Null { internal class NullLoggerFactory : LoggerFactory { public override ILogger CreateLogger(string name) { return new NullLogger(); } public override ILogger CreateLogger(Type type) { return new NullLogger(); } } }
20.722222
58
0.613941
[ "MIT" ]
Trivadis/AzureDeveloperBootcamp-Lab
Trivadis.AzureBootcamp.CrossCutting/Logging/Null/NullLoggerFactory.cs
375
C#
using System; namespace TicketApp.Api { public class TicketDetails { public int Code{get;set;} public DateTime Creation{get;set;} public String Account{get;set;} public int Priority{get;set;} } }
17.357143
42
0.621399
[ "MIT" ]
wallymathieu/lab-hexagon-chsarp
TicketApp.Api/Objects/TicketDetails.cs
245
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kendra-2019-02-03.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Kendra.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Kendra.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ProxyConfiguration Object /// </summary> public class ProxyConfigurationUnmarshaller : IUnmarshaller<ProxyConfiguration, XmlUnmarshallerContext>, IUnmarshaller<ProxyConfiguration, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ProxyConfiguration IUnmarshaller<ProxyConfiguration, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ProxyConfiguration Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ProxyConfiguration unmarshalledObject = new ProxyConfiguration(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Credentials", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Credentials = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Host", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Host = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Port", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Port = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ProxyConfigurationUnmarshaller _instance = new ProxyConfigurationUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ProxyConfigurationUnmarshaller Instance { get { return _instance; } } } }
35.336538
167
0.622041
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Kendra/Generated/Model/Internal/MarshallTransformations/ProxyConfigurationUnmarshaller.cs
3,675
C#
using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using stellar_dotnet_sdk; using stellar_dotnet_sdk.responses; using stellar_dotnet_sdk.responses.page; namespace stellar_dotnet_sdk_test.responses { [TestClass] public class PathsPageDeserializerTest { [TestMethod] public void TestDeserialize() { var json = File.ReadAllText(Path.Combine("testdata", "pathsPage.json")); var pathsPage = JsonSingleton.GetInstance<Page<PathResponse>>(json); AssertTestData(pathsPage); } public static void AssertTestData(Page<PathResponse> pathsPage) { Assert.IsNotNull(pathsPage.NextPage()); Assert.AreEqual(pathsPage.Records[0].DestinationAmount, "20.0000000"); Assert.AreEqual(pathsPage.Records[0].DestinationAsset, Asset.CreateNonNativeAsset("EUR", KeyPair.FromAccountId("GDSBCQO34HWPGUGQSP3QBFEXVTSR2PW46UIGTHVWGWJGQKH3AFNHXHXN"))); Assert.AreEqual(pathsPage.Records[0].Path.Count, 0); Assert.AreEqual(pathsPage.Records[0].SourceAmount, "30.0000000"); Assert.AreEqual(pathsPage.Records[0].SourceAsset, Asset.CreateNonNativeAsset("USD", KeyPair.FromAccountId("GDSBCQO34HWPGUGQSP3QBFEXVTSR2PW46UIGTHVWGWJGQKH3AFNHXHXN"))); Assert.AreEqual(pathsPage.Records[1].DestinationAmount, "50.0000000"); Assert.AreEqual(pathsPage.Records[1].DestinationAsset, Asset.CreateNonNativeAsset("EUR", KeyPair.FromAccountId("GBFMFKDUFYYITWRQXL4775CVUV3A3WGGXNJUAP4KTXNEQ2HG7JRBITGH"))); Assert.AreEqual(pathsPage.Records[1].Path.Count, 1); Assert.AreEqual(pathsPage.Records[1].Path[0], Asset.CreateNonNativeAsset("GBP", KeyPair.FromAccountId("GDSBCQO34HWPGUGQSP3QBFEXVTSR2PW46UIGTHVWGWJGQKH3AFNHXHXN"))); Assert.AreEqual(pathsPage.Records[1].SourceAmount, "60.0000000"); Assert.AreEqual(pathsPage.Records[1].SourceAsset, Asset.CreateNonNativeAsset("USD", KeyPair.FromAccountId("GBRAOXQDNQZRDIOK64HZI4YRDTBFWNUYH3OIHQLY4VEK5AIGMQHCLGXI"))); Assert.AreEqual(pathsPage.Records[2].DestinationAmount, "200.0000000"); Assert.AreEqual(pathsPage.Records[2].DestinationAsset, Asset.CreateNonNativeAsset("EUR", KeyPair.FromAccountId("GBRCOBK7C7UE72PB5JCPQU3ZI45ZCEM7HKQ3KYV3YD3XB7EBOPBEDN2G"))); Assert.AreEqual(pathsPage.Records[2].Path.Count, 2); Assert.AreEqual(pathsPage.Records[2].Path[0], Asset.CreateNonNativeAsset("GBP", KeyPair.FromAccountId("GAX7B3ZT3EOZW5POAMV4NGPPKCYUOYW2QQDIAF23JAXF72NMGRYPYOPM"))); Assert.AreEqual(pathsPage.Records[2].Path[1], Asset.CreateNonNativeAsset("PLN", KeyPair.FromAccountId("GACWIA2XGDFWWN3WKPX63JTK4S2J5NDPNOIVYMZY6RVTS7LWF2VHZLV3"))); Assert.AreEqual(pathsPage.Records[2].SourceAmount, "300.0000000"); Assert.AreEqual(pathsPage.Records[2].SourceAsset, Asset.CreateNonNativeAsset("USD", KeyPair.FromAccountId("GC7J5IHS3GABSX7AZLRINXWLHFTL3WWXLU4QX2UGSDEAIAQW2Q72U3KH"))); } } }
65.595745
186
0.731106
[ "Apache-2.0" ]
bazooka70/dotnet-stellar-sdk
stellar-dotnet-sdk-test/responses/PathsPageDeserializerTest.cs
3,085
C#
using JetBrains.Annotations; using JsonApiDotNetCore.Resources; // ReSharper disable UnusedTypeParameter namespace JsonApiDotNetCore.AtomicOperations.Processors { /// <summary> /// Processes a single operation to perform a complete replacement of a relationship on an existing resource. /// </summary> /// <typeparam name="TResource">The resource type.</typeparam> /// <typeparam name="TId">The resource identifier type.</typeparam> [PublicAPI] public interface ISetRelationshipProcessor<TResource, TId> : IOperationProcessor where TResource : class, IIdentifiable<TId> { } }
32.736842
113
0.734727
[ "MIT" ]
jlits/JsonApiDotNetCore
src/JsonApiDotNetCore/AtomicOperations/Processors/ISetRelationshipProcessor.cs
622
C#