content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Linq;
namespace Open_Lab_03._10
{
public class Checker
{
public int GetNumberOfCharsInString(char letter, string str)
{
var count = str.Count(x => x == letter);
return count;
}
}
}
| 17.4375
| 68
| 0.551971
|
[
"MIT"
] |
Grazog666/Open-Lab-03.10
|
Open-Lab-03.10/Checker.cs
| 281
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Mirror.RemoteCalls;
using UnityEngine;
namespace Mirror
{
/// <summary>NetworkServer handles remote connections and has a local connection for a local client.</summary>
public static class NetworkServer
{
static bool initialized;
public static int maxConnections;
/// <summary>Connection to host mode client (if any)</summary>
public static NetworkConnectionToClient localConnection { get; private set; }
/// <summary>True is a local client is currently active on the server</summary>
public static bool localClientActive => localConnection != null;
/// <summary>Dictionary of all server connections, with connectionId as key</summary>
public static Dictionary<int, NetworkConnectionToClient> connections =
new Dictionary<int, NetworkConnectionToClient>();
/// <summary>Message Handlers dictionary, with mesageId as key</summary>
internal static Dictionary<ushort, NetworkMessageDelegate> handlers =
new Dictionary<ushort, NetworkMessageDelegate>();
/// <summary>All spawned NetworkIdentities by netId.</summary>
// server sees ALL spawned ones.
public static readonly Dictionary<uint, NetworkIdentity> spawned =
new Dictionary<uint, NetworkIdentity>();
/// <summary>Single player mode can use dontListen to not accept incoming connections</summary>
// see also: https://github.com/vis2k/Mirror/pull/2595
public static bool dontListen;
/// <summary>active checks if the server has been started</summary>
public static bool active { get; internal set; }
// scene loading
public static bool isLoadingScene;
// interest management component (optional)
// by default, everyone observes everyone
public static InterestManagement aoi;
// OnConnected / OnDisconnected used to be NetworkMessages that were
// invoked. this introduced a bug where external clients could send
// Connected/Disconnected messages over the network causing undefined
// behaviour.
// => public so that custom NetworkManagers can hook into it
public static Action<NetworkConnection> OnConnectedEvent;
public static Action<NetworkConnection> OnDisconnectedEvent;
public static Action<NetworkConnection, Exception> OnErrorEvent;
// initialization / shutdown ///////////////////////////////////////////
static void Initialize()
{
if (initialized)
return;
initialized = true;
// Debug.Log($"NetworkServer Created version {Version.Current}");
//Make sure connections are cleared in case any old connections references exist from previous sessions
connections.Clear();
// reset NetworkTime
NetworkTime.Reset();
Debug.Assert(Transport.activeTransport != null, "There was no active transport when calling NetworkServer.Listen, If you are calling Listen manually then make sure to set 'Transport.activeTransport' first");
AddTransportHandlers();
}
static void AddTransportHandlers()
{
Transport.activeTransport.OnServerConnected = OnTransportConnected;
Transport.activeTransport.OnServerDataReceived = OnTransportData;
Transport.activeTransport.OnServerDisconnected = OnTransportDisconnected;
Transport.activeTransport.OnServerError = OnError;
}
// calls OnStartClient for all SERVER objects in host mode once.
// client doesn't get spawn messages for those, so need to call manually.
public static void ActivateHostScene()
{
foreach (NetworkIdentity identity in spawned.Values)
{
if (!identity.isClient)
{
// Debug.Log($"ActivateHostScene {identity.netId} {identity}");
identity.OnStartClient();
}
}
}
internal static void RegisterMessageHandlers()
{
RegisterHandler<ReadyMessage>(OnClientReadyMessage);
RegisterHandler<CommandMessage>(OnCommandMessage);
RegisterHandler<NetworkPingMessage>(NetworkTime.OnServerPing, false);
}
/// <summary>Starts server and listens to incoming connections with max connections limit.</summary>
public static void Listen(int maxConns)
{
Initialize();
maxConnections = maxConns;
// only start server if we want to listen
if (!dontListen)
{
Transport.activeTransport.ServerStart();
//Debug.Log("Server started listening");
}
active = true;
RegisterMessageHandlers();
}
// Note: NetworkClient.DestroyAllClientObjects does the same on client.
static void CleanupSpawned()
{
// iterate a COPY of spawned.
// DestroyObject removes them from the original collection.
// removing while iterating is not allowed.
foreach (NetworkIdentity identity in spawned.Values.ToList())
{
if (identity != null)
{
// scene object
if (identity.sceneId != 0)
{
// spawned scene objects are unspawned and reset.
// afterwards we disable them again.
// (they always stay in the scene, we don't destroy them)
DestroyObject(identity, DestroyMode.Reset);
identity.gameObject.SetActive(false);
}
// spawned prefabs
else
{
// spawned prefabs are unspawned and destroyed.
DestroyObject(identity, DestroyMode.Destroy);
}
}
}
spawned.Clear();
}
/// <summary>Shuts down the server and disconnects all clients</summary>
public static void Shutdown()
{
if (initialized)
{
DisconnectAll();
// stop the server.
// we do NOT call Transport.Shutdown, because someone only
// called NetworkServer.Shutdown. we can't assume that the
// client is supposed to be shut down too!
//
// NOTE: stop no matter what, even if 'dontListen':
// someone might enabled dontListen at runtime.
// but we still need to stop the server.
// fixes https://github.com/vis2k/Mirror/issues/2536
Transport.activeTransport.ServerStop();
initialized = false;
}
dontListen = false;
active = false;
handlers.Clear();
CleanupSpawned();
NetworkIdentity.ResetNextNetworkId();
// clear events. someone might have hooked into them before, but
// we don't want to use those hooks after Shutdown anymore.
OnConnectedEvent = null;
OnDisconnectedEvent = null;
}
// connections /////////////////////////////////////////////////////////
/// <summary>Add a connection and setup callbacks. Returns true if not added yet.</summary>
public static bool AddConnection(NetworkConnectionToClient conn)
{
if (!connections.ContainsKey(conn.connectionId))
{
// connection cannot be null here or conn.connectionId
// would throw NRE
connections[conn.connectionId] = conn;
return true;
}
// already a connection with this id
return false;
}
/// <summary>Removes a connection by connectionId. Returns true if removed.</summary>
public static bool RemoveConnection(int connectionId)
{
return connections.Remove(connectionId);
}
// called by LocalClient to add itself. don't call directly.
// TODO consider internal setter instead?
internal static void SetLocalConnection(LocalConnectionToClient conn)
{
if (localConnection != null)
{
Debug.LogError("Local Connection already exists");
return;
}
localConnection = conn;
}
// removes local connection to client
internal static void RemoveLocalConnection()
{
if (localConnection != null)
{
localConnection.Disconnect();
localConnection = null;
}
RemoveConnection(0);
}
/// <summary>True if we have no external connections (host is allowed)</summary>
public static bool NoExternalConnections()
{
return connections.Count == 0 ||
(connections.Count == 1 && localConnection != null);
}
// send ////////////////////////////////////////////////////////////////
/// <summary>Send a message to all clients, even those that haven't joined the world yet (non ready)</summary>
public static void SendToAll<T>(T message, int channelId = Channels.Reliable, bool sendToReadyOnly = false)
where T : struct, NetworkMessage
{
if (!active)
{
Debug.LogWarning("Can not send using NetworkServer.SendToAll<T>(T msg) because NetworkServer is not active");
return;
}
// Debug.Log($"Server.SendToAll {typeof(T)}");
using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
{
// pack message only once
MessagePacking.Pack(message, writer);
ArraySegment<byte> segment = writer.ToArraySegment();
// filter and then send to all internet connections at once
// -> makes code more complicated, but is HIGHLY worth it to
// avoid allocations, allow for multicast, etc.
int count = 0;
foreach (NetworkConnectionToClient conn in connections.Values)
{
if (sendToReadyOnly && !conn.isReady)
continue;
count++;
conn.Send(segment, channelId);
}
NetworkDiagnostics.OnSend(message, channelId, segment.Count, count);
}
}
/// <summary>Send a message to all clients which have joined the world (are ready).</summary>
// TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady!
public static void SendToReady<T>(T message, int channelId = Channels.Reliable)
where T : struct, NetworkMessage
{
if (!active)
{
Debug.LogWarning("Can not send using NetworkServer.SendToReady<T>(T msg) because NetworkServer is not active");
return;
}
SendToAll(message, channelId, true);
}
// this is like SendToReadyObservers - but it doesn't check the ready flag on the connection.
// this is used for ObjectDestroy messages.
static void SendToObservers<T>(NetworkIdentity identity, T message, int channelId = Channels.Reliable)
where T : struct, NetworkMessage
{
// Debug.Log($"Server.SendToObservers {typeof(T)}");
if (identity == null || identity.observers == null || identity.observers.Count == 0)
return;
using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
{
// pack message into byte[] once
MessagePacking.Pack(message, writer);
ArraySegment<byte> segment = writer.ToArraySegment();
foreach (NetworkConnection conn in identity.observers.Values)
{
conn.Send(segment, channelId);
}
NetworkDiagnostics.OnSend(message, channelId, segment.Count, identity.observers.Count);
}
}
/// <summary>Send a message to only clients which are ready with option to include the owner of the object identity</summary>
// TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady!
public static void SendToReadyObservers<T>(NetworkIdentity identity, T message, bool includeOwner = true, int channelId = Channels.Reliable)
where T : struct, NetworkMessage
{
// Debug.Log($"Server.SendToReady {typeof(T)}");
if (identity == null || identity.observers == null || identity.observers.Count == 0)
return;
using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
{
// pack message only once
MessagePacking.Pack(message, writer);
ArraySegment<byte> segment = writer.ToArraySegment();
int count = 0;
foreach (NetworkConnection conn in identity.observers.Values)
{
bool isOwner = conn == identity.connectionToClient;
if ((!isOwner || includeOwner) && conn.isReady)
{
count++;
conn.Send(segment, channelId);
}
}
NetworkDiagnostics.OnSend(message, channelId, segment.Count, count);
}
}
// Deprecated 2021-09-19
[Obsolete("SendToReady(identity, message, ...) was renamed to SendToReadyObservers because that's what it does.")]
public static void SendToReady<T>(NetworkIdentity identity, T message, bool includeOwner = true, int channelId = Channels.Reliable)
where T : struct, NetworkMessage =>
SendToReadyObservers(identity, message, includeOwner, channelId);
/// <summary>Send a message to only clients which are ready including the owner of the NetworkIdentity</summary>
// TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady!
public static void SendToReadyObservers<T>(NetworkIdentity identity, T message, int channelId)
where T : struct, NetworkMessage
{
SendToReadyObservers(identity, message, true, channelId);
}
// Deprecated 2021-09-19
[Obsolete("SendToReady(identity, message, ...) was renamed to SendToReadyObservers because that's what it does.")]
public static void SendToReady<T>(NetworkIdentity identity, T message, int channelId)
where T : struct, NetworkMessage =>
SendToReadyObservers(identity, message, channelId);
// transport events ////////////////////////////////////////////////////
// called by transport
static void OnTransportConnected(int connectionId)
{
// Debug.Log($"Server accepted client:{connectionId}");
// connectionId needs to be != 0 because 0 is reserved for local player
// note that some transports like kcp generate connectionId by
// hashing which can be < 0 as well, so we need to allow < 0!
if (connectionId == 0)
{
Debug.LogError($"Server.HandleConnect: invalid connectionId: {connectionId} . Needs to be != 0, because 0 is reserved for local player.");
Transport.activeTransport.ServerDisconnect(connectionId);
return;
}
// connectionId not in use yet?
if (connections.ContainsKey(connectionId))
{
Transport.activeTransport.ServerDisconnect(connectionId);
// Debug.Log($"Server connectionId {connectionId} already in use...kicked client");
return;
}
// are more connections allowed? if not, kick
// (it's easier to handle this in Mirror, so Transports can have
// less code and third party transport might not do that anyway)
// (this way we could also send a custom 'tooFull' message later,
// Transport can't do that)
if (connections.Count < maxConnections)
{
// add connection
NetworkConnectionToClient conn = new NetworkConnectionToClient(connectionId);
OnConnected(conn);
}
else
{
// kick
Transport.activeTransport.ServerDisconnect(connectionId);
// Debug.Log($"Server full, kicked client {connectionId}");
}
}
internal static void OnConnected(NetworkConnectionToClient conn)
{
// Debug.Log($"Server accepted client:{conn}");
// add connection and invoke connected event
AddConnection(conn);
OnConnectedEvent?.Invoke(conn);
}
static bool UnpackAndInvoke(NetworkConnectionToClient connection, NetworkReader reader, int channelId)
{
if (MessagePacking.Unpack(reader, out ushort msgType))
{
// try to invoke the handler for that message
if (handlers.TryGetValue(msgType, out NetworkMessageDelegate handler))
{
handler.Invoke(connection, reader, channelId);
connection.lastMessageTime = Time.time;
return true;
}
else
{
// message in a batch are NOT length prefixed to save bandwidth.
// every message needs to be handled and read until the end.
// otherwise it would overlap into the next message.
// => need to warn and disconnect to avoid undefined behaviour.
// => WARNING, not error. can happen if attacker sends random data.
Debug.LogWarning($"Unknown message id: {msgType} for connection: {connection}. This can happen if no handler was registered for this message.");
// simply return false. caller is responsible for disconnecting.
//connection.Disconnect();
return false;
}
}
else
{
// => WARNING, not error. can happen if attacker sends random data.
Debug.LogWarning($"Invalid message header for connection: {connection}.");
// simply return false. caller is responsible for disconnecting.
//connection.Disconnect();
return false;
}
}
// called by transport
internal static void OnTransportData(int connectionId, ArraySegment<byte> data, int channelId)
{
if (connections.TryGetValue(connectionId, out NetworkConnectionToClient connection))
{
// client might batch multiple messages into one packet.
// feed it to the Unbatcher.
// NOTE: we don't need to associate a channelId because we
// always process all messages in the batch.
if (!connection.unbatcher.AddBatch(data))
{
Debug.LogWarning($"NetworkServer: received Message was too short (messages should start with message id)");
connection.Disconnect();
return;
}
// process all messages in the batch.
// only while NOT loading a scene.
// if we get a scene change message, then we need to stop
// processing. otherwise we might apply them to the old scene.
// => fixes https://github.com/vis2k/Mirror/issues/2651
//
// NOTE: if scene starts loading, then the rest of the batch
// would only be processed when OnTransportData is called
// the next time.
// => consider moving processing to NetworkEarlyUpdate.
while (!isLoadingScene &&
connection.unbatcher.GetNextMessage(out NetworkReader reader, out double remoteTimestamp))
{
// enough to read at least header size?
if (reader.Remaining >= MessagePacking.HeaderSize)
{
// make remoteTimeStamp available to the user
connection.remoteTimeStamp = remoteTimestamp;
// handle message
if (!UnpackAndInvoke(connection, reader, channelId))
{
// warn, disconnect and return if failed
// -> warning because attackers might send random data
// -> messages in a batch aren't length prefixed.
// failing to read one would cause undefined
// behaviour for every message afterwards.
// so we need to disconnect.
// -> return to avoid the below unbatches.count error.
// we already disconnected and handled it.
Debug.LogWarning($"NetworkServer: failed to unpack and invoke message. Disconnecting {connectionId}.");
connection.Disconnect();
return;
}
}
// otherwise disconnect
else
{
// WARNING, not error. can happen if attacker sends random data.
Debug.LogWarning($"NetworkServer: received Message was too short (messages should start with message id). Disconnecting {connectionId}");
connection.Disconnect();
return;
}
}
// if we weren't interrupted by a scene change,
// then all batched messages should have been processed now.
// otherwise batches would silently grow.
// we need to log an error to avoid debugging hell.
//
// EXAMPLE: https://github.com/vis2k/Mirror/issues/2882
// -> UnpackAndInvoke silently returned because no handler for id
// -> Reader would never be read past the end
// -> Batch would never be retired because end is never reached
//
// NOTE: prefixing every message in a batch with a length would
// avoid ever not reading to the end. for extra bandwidth.
//
// IMPORTANT: always keep this check to detect memory leaks.
// this took half a day to debug last time.
if (!isLoadingScene && connection.unbatcher.BatchesCount > 0)
{
Debug.LogError($"Still had {connection.unbatcher.BatchesCount} batches remaining after processing, even though processing was not interrupted by a scene change. This should never happen, as it would cause ever growing batches.\nPossible reasons:\n* A message didn't deserialize as much as it serialized\n*There was no message handler for a message id, so the reader wasn't read until the end.");
}
}
else Debug.LogError($"HandleData Unknown connectionId:{connectionId}");
}
// called by transport
// IMPORTANT: often times when disconnecting, we call this from Mirror
// too because we want to remove the connection and handle
// the disconnect immediately.
// => which is fine as long as we guarantee it only runs once
// => which we do by removing the connection!
internal static void OnTransportDisconnected(int connectionId)
{
// Debug.Log($"Server disconnect client:{connectionId}");
if (connections.TryGetValue(connectionId, out NetworkConnectionToClient conn))
{
RemoveConnection(connectionId);
// Debug.Log($"Server lost client:{connectionId}");
// NetworkManager hooks into OnDisconnectedEvent to make
// DestroyPlayerForConnection(conn) optional, e.g. for PvP MMOs
// where players shouldn't be able to escape combat instantly.
if (OnDisconnectedEvent != null)
{
OnDisconnectedEvent.Invoke(conn);
}
// if nobody hooked into it, then simply call DestroyPlayerForConnection
else
{
DestroyPlayerForConnection(conn);
}
}
}
static void OnError(int connectionId, Exception exception)
{
Debug.LogException(exception);
// try get connection. passes null otherwise.
connections.TryGetValue(connectionId, out NetworkConnectionToClient conn);
OnErrorEvent?.Invoke(conn, exception);
}
// message handlers ////////////////////////////////////////////////////
/// <summary>Register a handler for message type T. Most should require authentication.</summary>
public static void RegisterHandler<T>(Action<NetworkConnection, T> handler, bool requireAuthentication = true)
where T : struct, NetworkMessage
{
ushort msgType = MessagePacking.GetId<T>();
if (handlers.ContainsKey(msgType))
{
Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning.");
}
handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
}
/// <summary>Replace a handler for message type T. Most should require authentication.</summary>
public static void ReplaceHandler<T>(Action<NetworkConnection, T> handler, bool requireAuthentication = true)
where T : struct, NetworkMessage
{
ushort msgType = MessagePacking.GetId<T>();
handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
}
/// <summary>Replace a handler for message type T. Most should require authentication.</summary>
public static void ReplaceHandler<T>(Action<T> handler, bool requireAuthentication = true)
where T : struct, NetworkMessage
{
ReplaceHandler<T>((_, value) => { handler(value); }, requireAuthentication);
}
/// <summary>Unregister a handler for a message type T.</summary>
public static void UnregisterHandler<T>()
where T : struct, NetworkMessage
{
ushort msgType = MessagePacking.GetId<T>();
handlers.Remove(msgType);
}
/// <summary>Clears all registered message handlers.</summary>
public static void ClearHandlers() => handlers.Clear();
internal static bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity)
{
identity = go.GetComponent<NetworkIdentity>();
if (identity == null)
{
Debug.LogError($"GameObject {go.name} doesn't have NetworkIdentity.");
return false;
}
return true;
}
// disconnect //////////////////////////////////////////////////////////
/// <summary>Disconnect all connections, including the local connection.</summary>
// synchronous: handles disconnect events and cleans up fully before returning!
public static void DisconnectAll()
{
// disconnect and remove all connections.
// we can not use foreach here because if
// conn.Disconnect -> Transport.ServerDisconnect calls
// OnDisconnect -> NetworkServer.OnDisconnect(connectionId)
// immediately then OnDisconnect would remove the connection while
// we are iterating here.
// see also: https://github.com/vis2k/Mirror/issues/2357
// this whole process should be simplified some day.
// until then, let's copy .Values to avoid InvalidOperatinException.
// note that this is only called when stopping the server, so the
// copy is no performance problem.
foreach (NetworkConnectionToClient conn in connections.Values.ToList())
{
// disconnect via connection->transport
conn.Disconnect();
// we want this function to be synchronous: handle disconnect
// events and clean up fully before returning.
// -> OnTransportDisconnected can safely be called without
// waiting for the Transport's callback.
// -> it has checks to only run once.
// call OnDisconnected unless local player in host mod
// TODO unnecessary check?
if (conn.connectionId != NetworkConnection.LocalConnectionId)
OnTransportDisconnected(conn.connectionId);
}
// cleanup
connections.Clear();
localConnection = null;
active = false;
}
// add/remove/replace player ///////////////////////////////////////////
/// <summary>Called by server after AddPlayer message to add the player for the connection.</summary>
// When a player is added for a connection, the client for that
// connection is made ready automatically. The player object is
// automatically spawned, so you do not need to call NetworkServer.Spawn
// for that object. This function is used for "adding" a player, not for
// "replacing" the player on a connection. If there is already a player
// on this playerControllerId for this connection, this will fail.
public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player)
{
NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
if (identity == null)
{
Debug.LogWarning($"AddPlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}");
return false;
}
// cannot have a player object in "Add" version
if (conn.identity != null)
{
Debug.Log("AddPlayer: player object already exists");
return false;
}
// make sure we have a controller before we call SetClientReady
// because the observers will be rebuilt only if we have a controller
conn.identity = identity;
// Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
identity.SetClientOwner(conn);
// special case, we are in host mode, set hasAuthority to true so that all overrides see it
if (conn is LocalConnectionToClient)
{
identity.hasAuthority = true;
NetworkClient.InternalAddPlayer(identity);
}
// set ready if not set yet
SetClientReady(conn);
// Debug.Log($"Adding new playerGameObject object netId: {identity.netId} asset ID: {identity.assetId}");
Respawn(identity);
return true;
}
/// <summary>Called by server after AddPlayer message to add the player for the connection.</summary>
// When a player is added for a connection, the client for that
// connection is made ready automatically. The player object is
// automatically spawned, so you do not need to call NetworkServer.Spawn
// for that object. This function is used for "adding" a player, not for
// "replacing" the player on a connection. If there is already a player
// on this playerControllerId for this connection, this will fail.
public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player, Guid assetId)
{
if (GetNetworkIdentity(player, out NetworkIdentity identity))
{
identity.assetId = assetId;
}
return AddPlayerForConnection(conn, player);
}
/// <summary>Replaces connection's player object. The old object is not destroyed.</summary>
// This does NOT change the ready state of the connection, so it can
// safely be used while changing scenes.
public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, bool keepAuthority = false)
{
NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
if (identity == null)
{
Debug.LogError($"ReplacePlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}");
return false;
}
if (identity.connectionToClient != null && identity.connectionToClient != conn)
{
Debug.LogError($"Cannot replace player for connection. New player is already owned by a different connection{player}");
return false;
}
//NOTE: there can be an existing player
//Debug.Log("NetworkServer ReplacePlayer");
NetworkIdentity previousPlayer = conn.identity;
conn.identity = identity;
// Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
identity.SetClientOwner(conn);
// special case, we are in host mode, set hasAuthority to true so that all overrides see it
if (conn is LocalConnectionToClient)
{
identity.hasAuthority = true;
NetworkClient.InternalAddPlayer(identity);
}
// add connection to observers AFTER the playerController was set.
// by definition, there is nothing to observe if there is no player
// controller.
//
// IMPORTANT: do this in AddPlayerForConnection & ReplacePlayerForConnection!
SpawnObserversForConnection(conn);
//Debug.Log($"Replacing playerGameObject object netId:{player.GetComponent<NetworkIdentity>().netId} asset ID {player.GetComponent<NetworkIdentity>().assetId}");
Respawn(identity);
if (keepAuthority)
// This needs to be sent to clear isLocalPlayer on
// client while keeping hasAuthority true
SendChangeOwnerMessage(previousPlayer, conn);
else
// This clears both isLocalPlayer and hasAuthority on client
previousPlayer.RemoveClientAuthority();
return true;
}
/// <summary>Replaces connection's player object. The old object is not destroyed.</summary>
// This does NOT change the ready state of the connection, so it can
// safely be used while changing scenes.
public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, Guid assetId, bool keepAuthority = false)
{
if (GetNetworkIdentity(player, out NetworkIdentity identity))
{
identity.assetId = assetId;
}
return ReplacePlayerForConnection(conn, player, keepAuthority);
}
// ready ///////////////////////////////////////////////////////////////
/// <summary>Flags client connection as ready (=joined world).</summary>
// When a client has signaled that it is ready, this method tells the
// server that the client is ready to receive spawned objects and state
// synchronization updates. This is usually called in a handler for the
// SYSTEM_READY message. If there is not specific action a game needs to
// take for this message, relying on the default ready handler function
// is probably fine, so this call wont be needed.
public static void SetClientReady(NetworkConnection conn)
{
// Debug.Log($"SetClientReadyInternal for conn:{conn}");
// set ready
conn.isReady = true;
// client is ready to start spawning objects
if (conn.identity != null)
SpawnObserversForConnection(conn);
}
/// <summary>Marks the client of the connection to be not-ready.</summary>
// Clients that are not ready do not receive spawned objects or state
// synchronization updates. They client can be made ready again by
// calling SetClientReady().
public static void SetClientNotReady(NetworkConnection conn)
{
if (conn.isReady)
{
// Debug.Log($"PlayerNotReady {conn}");
conn.isReady = false;
conn.RemoveFromObservingsObservers();
conn.Send(new NotReadyMessage());
}
}
/// <summary>Marks all connected clients as no longer ready.</summary>
// All clients will no longer be sent state synchronization updates. The
// player's clients can call ClientManager.Ready() again to re-enter the
// ready state. This is useful when switching scenes.
public static void SetAllClientsNotReady()
{
foreach (NetworkConnectionToClient conn in connections.Values)
{
SetClientNotReady(conn);
}
}
// default ready handler.
static void OnClientReadyMessage(NetworkConnection conn, ReadyMessage msg)
{
// Debug.Log($"Default handler for ready message from {conn}");
SetClientReady(conn);
}
// show / hide for connection //////////////////////////////////////////
internal static void ShowForConnection(NetworkIdentity identity, NetworkConnection conn)
{
if (conn.isReady)
SendSpawnMessage(identity, conn);
}
internal static void HideForConnection(NetworkIdentity identity, NetworkConnection conn)
{
ObjectHideMessage msg = new ObjectHideMessage
{
netId = identity.netId
};
conn.Send(msg);
}
/// <summary>Removes the player object from the connection</summary>
// destroyServerObject: Indicates whether the server object should be destroyed
public static void RemovePlayerForConnection(NetworkConnection conn, bool destroyServerObject)
{
if (conn.identity != null)
{
if (destroyServerObject)
Destroy(conn.identity.gameObject);
else
UnSpawn(conn.identity.gameObject);
conn.identity = null;
}
//else Debug.Log($"Connection {conn} has no identity");
}
// remote calls ////////////////////////////////////////////////////////
// Handle command from specific player, this could be one of multiple
// players on a single client
static void OnCommandMessage(NetworkConnection conn, CommandMessage msg)
{
if (!spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
{
Debug.LogWarning($"Spawned object not found when handling Command message [netId={msg.netId}]");
return;
}
CommandInfo commandInfo = identity.GetCommandInfo(msg.componentIndex, msg.functionHash);
// Commands can be for player objects, OR other objects with client-authority
// -> so if this connection's controller has a different netId then
// only allow the command if clientAuthorityOwner
bool requiresAuthority = commandInfo.requiresAuthority;
if (requiresAuthority && identity.connectionToClient != conn)
{
Debug.LogWarning($"Command for object without authority [netId={msg.netId}]");
return;
}
// Debug.Log($"OnCommandMessage for netId:{msg.netId} conn:{conn}");
using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(msg.payload))
identity.HandleRemoteCall(msg.componentIndex, msg.functionHash, MirrorInvokeType.Command, networkReader, conn as NetworkConnectionToClient);
}
// spawning ////////////////////////////////////////////////////////////
static ArraySegment<byte> CreateSpawnMessagePayload(bool isOwner, NetworkIdentity identity, PooledNetworkWriter ownerWriter, PooledNetworkWriter observersWriter)
{
// Only call OnSerializeAllSafely if there are NetworkBehaviours
if (identity.NetworkBehaviours.Length == 0)
{
return default;
}
// serialize all components with initialState = true
// (can be null if has none)
identity.OnSerializeAllSafely(true, ownerWriter, observersWriter);
// convert to ArraySegment to avoid reader allocations
// if nothing was written, .ToArraySegment returns an empty segment.
ArraySegment<byte> ownerSegment = ownerWriter.ToArraySegment();
ArraySegment<byte> observersSegment = observersWriter.ToArraySegment();
// use owner segment if 'conn' owns this identity, otherwise
// use observers segment
ArraySegment<byte> payload = isOwner ? ownerSegment : observersSegment;
return payload;
}
internal static void SendSpawnMessage(NetworkIdentity identity, NetworkConnection conn)
{
if (identity.serverOnly) return;
//Debug.Log($"Server SendSpawnMessage: name:{identity.name} sceneId:{identity.sceneId:X} netid:{identity.netId}");
// one writer for owner, one for observers
using (PooledNetworkWriter ownerWriter = NetworkWriterPool.GetWriter(), observersWriter = NetworkWriterPool.GetWriter())
{
bool isOwner = identity.connectionToClient == conn;
ArraySegment<byte> payload = CreateSpawnMessagePayload(isOwner, identity, ownerWriter, observersWriter);
SpawnMessage message = new SpawnMessage
{
netId = identity.netId,
isLocalPlayer = conn.identity == identity,
isOwner = isOwner,
sceneId = identity.sceneId,
assetId = identity.assetId,
// use local values for VR support
position = identity.transform.localPosition,
rotation = identity.transform.localRotation,
scale = identity.transform.localScale,
payload = payload
};
conn.Send(message);
}
}
internal static void SendChangeOwnerMessage(NetworkIdentity identity, NetworkConnection conn)
{
// Don't send if identity isn't spawned or only exists on server
if (identity.netId == 0 || identity.serverOnly) return;
// Don't send if conn doesn't have the identity spawned yet
// May be excluded from the client by interest management
if (!conn.observing.Contains(identity)) return;
//Debug.Log($"Server SendChangeOwnerMessage: name={identity.name} netid={identity.netId}");
conn.Send(new ChangeOwnerMessage
{
netId = identity.netId,
isOwner = identity.connectionToClient == conn,
isLocalPlayer = conn.identity == identity
});
}
static void SpawnObject(GameObject obj, NetworkConnection ownerConnection)
{
// verify if we an spawn this
if (Utils.IsPrefab(obj))
{
Debug.LogError($"GameObject {obj.name} is a prefab, it can't be spawned. Instantiate it first.");
return;
}
if (!active)
{
Debug.LogError($"SpawnObject for {obj}, NetworkServer is not active. Cannot spawn objects without an active server.");
return;
}
NetworkIdentity identity = obj.GetComponent<NetworkIdentity>();
if (identity == null)
{
Debug.LogError($"SpawnObject {obj} has no NetworkIdentity. Please add a NetworkIdentity to {obj}");
return;
}
if (identity.SpawnedFromInstantiate)
{
// Using Instantiate on SceneObject is not allowed, so stop spawning here
// NetworkIdentity.Awake already logs error, no need to log a second error here
return;
}
identity.connectionToClient = (NetworkConnectionToClient)ownerConnection;
// special case to make sure hasAuthority is set
// on start server in host mode
if (ownerConnection is LocalConnectionToClient)
identity.hasAuthority = true;
identity.OnStartServer();
// Debug.Log($"SpawnObject instance ID {identity.netId} asset ID {identity.assetId}");
if (aoi)
{
// This calls user code which might throw exceptions
// We don't want this to leave us in bad state
try
{
aoi.OnSpawned(identity);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
RebuildObservers(identity, true);
}
/// <summary>Spawn the given game object on all clients which are ready.</summary>
// This will cause a new object to be instantiated from the registered
// prefab, or from a custom spawn function.
public static void Spawn(GameObject obj, NetworkConnection ownerConnection = null)
{
SpawnObject(obj, ownerConnection);
}
/// <summary>Spawns an object and also assigns Client Authority to the specified client.</summary>
// This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.
public static void Spawn(GameObject obj, GameObject ownerPlayer)
{
NetworkIdentity identity = ownerPlayer.GetComponent<NetworkIdentity>();
if (identity == null)
{
Debug.LogError("Player object has no NetworkIdentity");
return;
}
if (identity.connectionToClient == null)
{
Debug.LogError("Player object is not a player.");
return;
}
Spawn(obj, identity.connectionToClient);
}
/// <summary>Spawns an object and also assigns Client Authority to the specified client.</summary>
// This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.
public static void Spawn(GameObject obj, Guid assetId, NetworkConnection ownerConnection = null)
{
if (GetNetworkIdentity(obj, out NetworkIdentity identity))
{
identity.assetId = assetId;
}
SpawnObject(obj, ownerConnection);
}
internal static bool ValidateSceneObject(NetworkIdentity identity)
{
if (identity.gameObject.hideFlags == HideFlags.NotEditable ||
identity.gameObject.hideFlags == HideFlags.HideAndDontSave)
return false;
#if UNITY_EDITOR
if (UnityEditor.EditorUtility.IsPersistent(identity.gameObject))
return false;
#endif
// If not a scene object
return identity.sceneId != 0;
}
/// <summary>Spawns NetworkIdentities in the scene on the server.</summary>
// NetworkIdentity objects in a scene are disabled by default. Calling
// SpawnObjects() causes these scene objects to be enabled and spawned.
// It is like calling NetworkServer.Spawn() for each of them.
public static bool SpawnObjects()
{
// only if server active
if (!active)
return false;
NetworkIdentity[] identities = Resources.FindObjectsOfTypeAll<NetworkIdentity>();
// first pass: activate all scene objects
foreach (NetworkIdentity identity in identities)
{
if (ValidateSceneObject(identity))
{
// Debug.Log($"SpawnObjects sceneId:{identity.sceneId:X} name:{identity.gameObject.name}");
identity.gameObject.SetActive(true);
// fix https://github.com/vis2k/Mirror/issues/2778:
// -> SetActive(true) does NOT call Awake() if the parent
// is inactive
// -> we need Awake() to initialize NetworkBehaviours[] etc.
// because our second pass below spawns and works with it
// => detect this situation and manually call Awake for
// proper initialization
if (!identity.gameObject.activeInHierarchy)
identity.Awake();
}
}
// second pass: spawn all scene objects
foreach (NetworkIdentity identity in identities)
{
if (ValidateSceneObject(identity))
// pass connection so that authority is not lost when server loads a scene
// https://github.com/vis2k/Mirror/pull/2987
Spawn(identity.gameObject, identity.connectionToClient);
}
return true;
}
static void Respawn(NetworkIdentity identity)
{
if (identity.netId == 0)
{
// If the object has not been spawned, then do a full spawn and update observers
Spawn(identity.gameObject, identity.connectionToClient);
}
else
{
// otherwise just replace his data
SendSpawnMessage(identity, identity.connectionToClient);
}
}
static void SpawnObserversForConnection(NetworkConnection conn)
{
//Debug.Log($"Spawning {spawned.Count} objects for conn {conn}");
if (!conn.isReady)
{
// client needs to finish initializing before we can spawn objects
// otherwise it would not find them.
return;
}
// let connection know that we are about to start spawning...
conn.Send(new ObjectSpawnStartedMessage());
// add connection to each nearby NetworkIdentity's observers, which
// internally sends a spawn message for each one to the connection.
foreach (NetworkIdentity identity in spawned.Values)
{
// try with far away ones in ummorpg!
if (identity.gameObject.activeSelf) //TODO this is different
{
//Debug.Log($"Sending spawn message for current server objects name:{identity.name} netId:{identity.netId} sceneId:{identity.sceneId:X}");
// we need to support three cases:
// - legacy system (identity has .visibility)
// - new system (networkserver has .aoi)
// - default case: no .visibility and no .aoi means add all
// connections by default)
//
// ForceHidden/ForceShown overwrite all systems so check it
// first!
// ForceShown: add no matter what
if (identity.visible == Visibility.ForceShown)
{
identity.AddObserver(conn);
}
// ForceHidden: don't show no matter what
else if (identity.visible == Visibility.ForceHidden)
{
// do nothing
}
// default: legacy system / new system / no system support
else if (identity.visible == Visibility.Default)
{
// legacy system
#pragma warning disable 618
if (identity.visibility != null)
{
// call OnCheckObserver
if (identity.visibility.OnCheckObserver(conn))
identity.AddObserver(conn);
}
#pragma warning restore 618
// new system
else if (aoi != null)
{
// call OnCheckObserver
if (aoi.OnCheckObserver(identity, conn))
identity.AddObserver(conn);
}
// no system: add all observers by default
else
{
identity.AddObserver(conn);
}
}
}
}
// let connection know that we finished spawning, so it can call
// OnStartClient on each one (only after all were spawned, which
// is how Unity's Start() function works too)
conn.Send(new ObjectSpawnFinishedMessage());
}
/// <summary>This takes an object that has been spawned and un-spawns it.</summary>
// The object will be removed from clients that it was spawned on, or
// the custom spawn handler function on the client will be called for
// the object.
// Unlike when calling NetworkServer.Destroy(), on the server the object
// will NOT be destroyed. This allows the server to re-use the object,
// even spawn it again later.
public static void UnSpawn(GameObject obj) => DestroyObject(obj, DestroyMode.Reset);
// destroy /////////////////////////////////////////////////////////////
/// <summary>Destroys all of the connection's owned objects on the server.</summary>
// This is used when a client disconnects, to remove the players for
// that client. This also destroys non-player objects that have client
// authority set for this connection.
public static void DestroyPlayerForConnection(NetworkConnection conn)
{
// destroy all objects owned by this connection, including the player object
conn.DestroyOwnedObjects();
// remove connection from all of its observing entities observers
// fixes https://github.com/vis2k/Mirror/issues/2737
// -> cleaning those up in NetworkConnection.Disconnect is NOT enough
// because voluntary disconnects from the other end don't call
// NetworkConnectionn.Disconnect()
conn.RemoveFromObservingsObservers();
conn.identity = null;
}
// sometimes we want to GameObject.Destroy it.
// sometimes we want to just unspawn on clients and .Reset() it on server.
// => 'bool destroy' isn't obvious enough. it's really destroy OR reset!
enum DestroyMode { Destroy, Reset }
static void DestroyObject(NetworkIdentity identity, DestroyMode mode)
{
// Debug.Log($"DestroyObject instance:{identity.netId}");
// only call OnRebuildObservers while active,
// not while shutting down
// (https://github.com/vis2k/Mirror/issues/2977)
if (active && aoi)
{
// This calls user code which might throw exceptions
// We don't want this to leave us in bad state
try
{
aoi.OnDestroyed(identity);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
// remove from NetworkServer (this) dictionary
spawned.Remove(identity.netId);
identity.connectionToClient?.RemoveOwnedObject(identity);
// send object destroy message to all observers, clear observers
SendToObservers(identity, new ObjectDestroyMessage{netId = identity.netId});
identity.ClearObservers();
// in host mode, call OnStopClient manually
if (NetworkClient.active && localClientActive)
{
identity.OnStopClient();
// The object may have been spawned with host client ownership,
// e.g. a pet so we need to clear hasAuthority and call
// NotifyAuthority which invokes OnStopAuthority if hasAuthority.
identity.hasAuthority = false;
identity.NotifyAuthority();
// remove from NetworkClient dictionary
NetworkClient.spawned.Remove(identity.netId);
}
// we are on the server. call OnStopServer.
identity.OnStopServer();
// are we supposed to GameObject.Destroy() it completely?
if (mode == DestroyMode.Destroy)
{
identity.destroyCalled = true;
UnityEngine.Object.Destroy(identity.gameObject);
}
// otherwise simply .Reset() and set inactive again
else if (mode == DestroyMode.Reset)
{
identity.Reset();
}
}
static void DestroyObject(GameObject obj, DestroyMode mode)
{
if (obj == null)
{
Debug.Log("NetworkServer DestroyObject is null");
return;
}
if (GetNetworkIdentity(obj, out NetworkIdentity identity))
{
DestroyObject(identity, mode);
}
}
/// <summary>Destroys this object and corresponding objects on all clients.</summary>
// In some cases it is useful to remove an object but not delete it on
// the server. For that, use NetworkServer.UnSpawn() instead of
// NetworkServer.Destroy().
public static void Destroy(GameObject obj) => DestroyObject(obj, DestroyMode.Destroy);
// interest management /////////////////////////////////////////////////
// Helper function to add all server connections as observers.
// This is used if none of the components provides their own
// OnRebuildObservers function.
internal static void AddAllReadyServerConnectionsToObservers(NetworkIdentity identity)
{
// add all server connections
foreach (NetworkConnectionToClient conn in connections.Values)
{
// only if authenticated (don't send to people during logins)
if (conn.isReady)
identity.AddObserver(conn);
}
// add local host connection (if any)
if (localConnection != null && localConnection.isReady)
{
identity.AddObserver(localConnection);
}
}
// allocate newObservers helper HashSet only once
static readonly HashSet<NetworkConnection> newObservers = new HashSet<NetworkConnection>();
// rebuild observers default method (no AOI) - adds all connections
static void RebuildObserversDefault(NetworkIdentity identity, bool initialize)
{
// only add all connections when rebuilding the first time.
// second time we just keep them without rebuilding anything.
if (initialize)
{
// not force hidden?
if (identity.visible != Visibility.ForceHidden)
{
AddAllReadyServerConnectionsToObservers(identity);
}
}
}
// rebuild observers via interest management system
static void RebuildObserversCustom(NetworkIdentity identity, bool initialize)
{
// clear newObservers hashset before using it
newObservers.Clear();
// not force hidden?
if (identity.visible != Visibility.ForceHidden)
{
// obsolete legacy system support (for now)
#pragma warning disable 618
if (identity.visibility != null)
identity.visibility.OnRebuildObservers(newObservers, initialize);
#pragma warning restore 618
else
aoi.OnRebuildObservers(identity, newObservers, initialize);
}
// IMPORTANT: AFTER rebuilding add own player connection in any case
// to ensure player always sees himself no matter what.
// -> OnRebuildObservers might clear observers, so we need to add
// the player's own connection AFTER. 100% fail safe.
// -> fixes https://github.com/vis2k/Mirror/issues/692 where a
// player might teleport out of the ProximityChecker's cast,
// losing the own connection as observer.
if (identity.connectionToClient != null)
{
newObservers.Add(identity.connectionToClient);
}
bool changed = false;
// add all newObservers that aren't in .observers yet
foreach (NetworkConnection conn in newObservers)
{
// only add ready connections.
// otherwise the player might not be in the world yet or anymore
if (conn != null && conn.isReady)
{
if (initialize || !identity.observers.ContainsKey(conn.connectionId))
{
// new observer
conn.AddToObserving(identity);
// Debug.Log($"New Observer for {gameObject} {conn}");
changed = true;
}
}
}
// remove all old .observers that aren't in newObservers anymore
foreach (NetworkConnection conn in identity.observers.Values)
{
if (!newObservers.Contains(conn))
{
// removed observer
conn.RemoveFromObserving(identity, false);
// Debug.Log($"Removed Observer for {gameObjec} {conn}");
changed = true;
}
}
// copy new observers to observers
if (changed)
{
identity.observers.Clear();
foreach (NetworkConnection conn in newObservers)
{
if (conn != null && conn.isReady)
identity.observers.Add(conn.connectionId, conn);
}
}
// special case for host mode: we use SetHostVisibility to hide
// NetworkIdentities that aren't in observer range from host.
// this is what games like Dota/Counter-Strike do too, where a host
// does NOT see all players by default. they are in memory, but
// hidden to the host player.
//
// this code is from UNET, it's a bit strange but it works:
// * it hides newly connected identities in host mode
// => that part was the intended behaviour
// * it hides ALL NetworkIdentities in host mode when the host
// connects but hasn't selected a character yet
// => this only works because we have no .localConnection != null
// check. at this stage, localConnection is null because
// StartHost starts the server first, then calls this code,
// then starts the client and sets .localConnection. so we can
// NOT add a null check without breaking host visibility here.
// * it hides ALL NetworkIdentities in server-only mode because
// observers never contain the 'null' .localConnection
// => that was not intended, but let's keep it as it is so we
// don't break anything in host mode. it's way easier than
// iterating all identities in a special function in StartHost.
if (initialize)
{
if (!newObservers.Contains(localConnection))
{
// obsolete legacy system support (for now)
#pragma warning disable 618
if (identity.visibility != null)
identity.visibility.OnSetHostVisibility(false);
#pragma warning restore 618
else if (aoi != null)
aoi.SetHostVisibility(identity, false);
}
}
}
// RebuildObservers does a local rebuild for the NetworkIdentity.
// This causes the set of players that can see this object to be rebuild.
//
// IMPORTANT:
// => global rebuild would be more simple, BUT
// => local rebuild is way faster for spawn/despawn because we can
// simply rebuild a select NetworkIdentity only
// => having both .observers and .observing is necessary for local
// rebuilds
//
// in other words, this is the perfect solution even though it's not
// completely simple (due to .observers & .observing)
//
// Mirror maintains .observing automatically in the background. best of
// both worlds without any worrying now!
public static void RebuildObservers(NetworkIdentity identity, bool initialize)
{
// observers are null until OnStartServer creates them
if (identity.observers == null)
return;
// legacy proximitychecker support:
// make sure user doesn't use both new and old system.
#pragma warning disable 618
if (aoi != null & identity.visibility != null)
{
Debug.LogError($"RebuildObservers: {identity.name} has {identity.visibility.GetType()} component but there is also a global {aoi.GetType()} component. Can't use both systems at the same time!");
return;
}
#pragma warning restore 618
// if there is no interest management system,
// or if 'force shown' then add all connections
#pragma warning disable 618
if ((aoi == null && identity.visibility == null) ||
identity.visible == Visibility.ForceShown)
#pragma warning restore 618
{
RebuildObserversDefault(identity, initialize);
}
// otherwise let interest management system rebuild
else
{
RebuildObserversCustom(identity, initialize);
}
}
// broadcasting ////////////////////////////////////////////////////////
// helper function to get the right serialization for a connection
static NetworkWriter GetEntitySerializationForConnection(NetworkIdentity identity, NetworkConnectionToClient connection)
{
// get serialization for this entity (cached)
// IMPORTANT: int tick avoids floating point inaccuracy over days/weeks
NetworkIdentitySerialization serialization = identity.GetSerializationAtTick(Time.frameCount);
// is this entity owned by this connection?
bool owned = identity.connectionToClient == connection;
// send serialized data
// owner writer if owned
if (owned)
{
// was it dirty / did we actually serialize anything?
if (serialization.ownerWriter.Position > 0)
return serialization.ownerWriter;
}
// observers writer if not owned
else
{
// was it dirty / did we actually serialize anything?
if (serialization.observersWriter.Position > 0)
return serialization.observersWriter;
}
// nothing was serialized
return null;
}
// helper function to broadcast the world to a connection
static void BroadcastToConnection(NetworkConnectionToClient connection)
{
// for each entity that this connection is seeing
foreach (NetworkIdentity identity in connection.observing)
{
// make sure it's not null or destroyed.
// (which can happen if someone uses
// GameObject.Destroy instead of
// NetworkServer.Destroy)
if (identity != null)
{
// get serialization for this entity viewed by this connection
// (if anything was serialized this time)
NetworkWriter serialization = GetEntitySerializationForConnection(identity, connection);
if (serialization != null)
{
EntityStateMessage message = new EntityStateMessage
{
netId = identity.netId,
payload = serialization.ToArraySegment()
};
connection.Send(message);
}
// clear dirty bits only for the components that we serialized
// DO NOT clean ALL component's dirty bits, because
// components can have different syncIntervals and we don't
// want to reset dirty bits for the ones that were not
// synced yet.
// (we serialized only the IsDirty() components, or all of
// them if initialState. clearing the dirty ones is enough.)
//
// NOTE: this is what we did before push->pull
// broadcasting. let's keep doing this for
// feature parity to not break anyone's project.
// TODO make this more simple / unnecessary later.
identity.ClearDirtyComponentsDirtyBits();
}
// spawned list should have no null entries because we
// always call Remove in OnObjectDestroy everywhere.
// if it does have null then someone used
// GameObject.Destroy instead of NetworkServer.Destroy.
else Debug.LogWarning($"Found 'null' entry in observing list for connectionId={connection.connectionId}. Please call NetworkServer.Destroy to destroy networked objects. Don't use GameObject.Destroy.");
}
}
// NetworkLateUpdate called after any Update/FixedUpdate/LateUpdate
// (we add this to the UnityEngine in NetworkLoop)
static readonly List<NetworkConnectionToClient> connectionsCopy =
new List<NetworkConnectionToClient>();
static void Broadcast()
{
// copy all connections into a helper collection so that
// OnTransportDisconnected can be called while iterating.
// -> OnTransportDisconnected removes from the collection
// -> which would throw 'can't modify while iterating' errors
// => see also: https://github.com/vis2k/Mirror/issues/2739
// (copy nonalloc)
// TODO remove this when we move to 'lite' transports with only
// socket send/recv later.
connectionsCopy.Clear();
connections.Values.CopyTo(connectionsCopy);
// go through all connections
foreach (NetworkConnectionToClient connection in connectionsCopy)
{
// has this connection joined the world yet?
// for each READY connection:
// pull in UpdateVarsMessage for each entity it observes
if (connection.isReady)
{
// broadcast world state to this connection
BroadcastToConnection(connection);
}
// update connection to flush out batched messages
connection.Update();
}
// TODO this is way too slow because we iterate ALL spawned :/
// TODO this is way too complicated :/
// to understand what this tries to prevent, consider this example:
// monster has health=100
// we change health=200, dirty bit is set
// player comes in range, gets full serialization spawn packet.
// next Broadcast(), player gets the health=200 change because dirty bit was set.
//
// this code clears all dirty bits if no players are around to prevent it.
// BUT there are two issues:
// 1. what if a playerB was around the whole time?
// 2. why don't we handle broadcast and spawn packets both HERE?
// handling spawn separately is why we need this complex magic
//
// see test: DirtyBitsAreClearedForSpawnedWithoutObservers()
// see test: SyncObjectChanges_DontGrowWithoutObservers()
//
// PAUL: we also do this to avoid ever growing SyncList .changes
//ClearSpawnedDirtyBits();
//
// this was moved to NetworkIdentity.AddObserver!
// same result, but no more O(N) loop in here!
// TODO remove this comment after moving spawning into Broadcast()!
}
// update //////////////////////////////////////////////////////////////
// NetworkEarlyUpdate called before any Update/FixedUpdate
// (we add this to the UnityEngine in NetworkLoop)
internal static void NetworkEarlyUpdate()
{
// process all incoming messages first before updating the world
if (Transport.activeTransport != null)
Transport.activeTransport.ServerEarlyUpdate();
}
internal static void NetworkLateUpdate()
{
// only broadcast world if active
if (active)
Broadcast();
// process all outgoing messages after updating the world
// (even if not active. still want to process disconnects etc.)
if (Transport.activeTransport != null)
Transport.activeTransport.ServerLateUpdate();
}
}
}
| 46.177238
| 416
| 0.555603
|
[
"MIT"
] |
kotauchisunsun/MetaSample
|
Assets/Mirror/Runtime/NetworkServer.cs
| 77,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 runtime.lex-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lex.Model
{
/// <summary>
/// Either the Amazon Lex bot is still building, or one of the dependent services (Amazon
/// Polly, AWS Lambda) failed with an internal service error.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class BadGatewayException : AmazonLexException
{
/// <summary>
/// Constructs a new BadGatewayException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public BadGatewayException(string message)
: base(message) {}
/// <summary>
/// Construct instance of BadGatewayException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public BadGatewayException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of BadGatewayException
/// </summary>
/// <param name="innerException"></param>
public BadGatewayException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of BadGatewayException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public BadGatewayException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of BadGatewayException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public BadGatewayException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the BadGatewayException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected BadGatewayException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
}
| 47.84
| 179
| 0.662375
|
[
"Apache-2.0"
] |
philasmar/aws-sdk-net
|
sdk/src/Services/Lex/Generated/Model/BadGatewayException.cs
| 5,980
|
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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertInt16129()
{
var test = new InsertScalarTest__InsertInt16129();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class InsertScalarTest__InsertInt16129
{
private struct TestStruct
{
public Vector128<Int16> _fld;
public Int16 _scalarFldData;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
testStruct._scalarFldData = (short)2;
return testStruct;
}
public void RunStructFldScenario(InsertScalarTest__InsertInt16129 testClass)
{
var result = Sse2.Insert(_fld, _scalarFldData, 129);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, _scalarFldData, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Int16 _scalarClsData = (short)2;
private static Vector128<Int16> _clsVar;
private Vector128<Int16> _fld;
private Int16 _scalarFldData = (short)2;
private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable;
static InsertScalarTest__InsertInt16129()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public InsertScalarTest__InsertInt16129()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; }
_dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
var result = Sse2.Insert(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
(short)2,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr);
}
public unsafe void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
Int16 localData = (short)2;
Int16* ptr = &localData;
var result = Sse2.Insert(
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
*ptr,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr);
}
public unsafe void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
Int16 localData = (short)2;
Int16* ptr = &localData;
var result = Sse2.Insert(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
*ptr,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Insert), new Type[] { typeof(Vector128<Int16>), typeof(Int16), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
(short)2,
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Insert), new Type[] { typeof(Vector128<Int16>), typeof(Int16), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
(short)2,
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Insert), new Type[] { typeof(Vector128<Int16>), typeof(Int16), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
(short)2,
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Insert(
_clsVar,
_scalarClsData,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr);
}
public void RunLclVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario));
Int16 localData = (short)2;
var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr);
var result = Sse2.Insert(firstOp, localData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
Int16 localData = (short)2;
var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.Insert(firstOp, localData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
Int16 localData = (short)2;
var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.Insert(firstOp, localData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertScalarTest__InsertInt16129();
var result = Sse2.Insert(test._fld, test._scalarFldData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Insert(_fld, _scalarFldData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Insert(test._fld, test._scalarFldData, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> firstOp, Int16 scalarData, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray, scalarData, outArray, method);
}
private void ValidateResult(void* firstOp, Int16 scalarData, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray, scalarData, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16 scalarData, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if ((i == 1 ? result[i] != scalarData : result[i] != 0))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Insert)}<Int16>(Vector128<Int16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 38.495122
| 185
| 0.573275
|
[
"MIT"
] |
06needhamt/runtime
|
src/coreclr/tests/src/JIT/HardwareIntrinsics/X86/Sse2/Insert.Int16.129.cs
| 15,783
|
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>
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using System.Linq;
namespace cfg.test
{
public sealed partial class DetectEncoding : Bright.Config.BeanBase
{
public DetectEncoding(ByteBuf _buf)
{
Id = _buf.ReadInt();
Name = _buf.ReadString();
PostInit();
}
public static DetectEncoding DeserializeDetectEncoding(ByteBuf _buf)
{
return new test.DetectEncoding(_buf);
}
public int Id { get; protected set; }
public string Name { get; protected set; }
public const int __ID__ = -1154609646;
public override int GetTypeId() => __ID__;
public void Resolve(Dictionary<string, object> _tables)
{
PostResolve();
}
public void TranslateText(System.Func<string, string, string> translator)
{
}
public void Reload(DetectEncoding reloadData)
{
Id = reloadData.Id;
Name = reloadData.Name;
}
public override string ToString()
{
return "{ "
+ "Id:" + Id + ","
+ "Name:" + Name + ","
+ "}";
}
partial void PostInit();
partial void PostResolve();
}
}
| 23.2
| 80
| 0.551061
|
[
"MIT"
] |
HFX-93/luban_examples
|
Projects/UnityConfigReload/Assets/Gen/Code/test/DetectEncoding.cs
| 1,508
|
C#
|
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
namespace Workday.FinancialAid
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Person_Name_Suffix_DataType : INotifyPropertyChanged
{
private Country_Predefined_Person_Name_Component_ValueObjectType social_Suffix_ReferenceField;
private string social_Suffix_DescriptorField;
private Country_Predefined_Person_Name_Component_ValueObjectType academic_Suffix_ReferenceField;
private Country_Predefined_Person_Name_Component_ValueObjectType hereditary_Suffix_ReferenceField;
private Country_Predefined_Person_Name_Component_ValueObjectType honorary_Suffix_ReferenceField;
private Country_Predefined_Person_Name_Component_ValueObjectType professional_Suffix_ReferenceField;
private Country_Predefined_Person_Name_Component_ValueObjectType religious_Suffix_ReferenceField;
private Country_Predefined_Person_Name_Component_ValueObjectType royal_Suffix_ReferenceField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement(Order = 0)]
public Country_Predefined_Person_Name_Component_ValueObjectType Social_Suffix_Reference
{
get
{
return this.social_Suffix_ReferenceField;
}
set
{
this.social_Suffix_ReferenceField = value;
this.RaisePropertyChanged("Social_Suffix_Reference");
}
}
[XmlElement(Order = 1)]
public string Social_Suffix_Descriptor
{
get
{
return this.social_Suffix_DescriptorField;
}
set
{
this.social_Suffix_DescriptorField = value;
this.RaisePropertyChanged("Social_Suffix_Descriptor");
}
}
[XmlElement(Order = 2)]
public Country_Predefined_Person_Name_Component_ValueObjectType Academic_Suffix_Reference
{
get
{
return this.academic_Suffix_ReferenceField;
}
set
{
this.academic_Suffix_ReferenceField = value;
this.RaisePropertyChanged("Academic_Suffix_Reference");
}
}
[XmlElement(Order = 3)]
public Country_Predefined_Person_Name_Component_ValueObjectType Hereditary_Suffix_Reference
{
get
{
return this.hereditary_Suffix_ReferenceField;
}
set
{
this.hereditary_Suffix_ReferenceField = value;
this.RaisePropertyChanged("Hereditary_Suffix_Reference");
}
}
[XmlElement(Order = 4)]
public Country_Predefined_Person_Name_Component_ValueObjectType Honorary_Suffix_Reference
{
get
{
return this.honorary_Suffix_ReferenceField;
}
set
{
this.honorary_Suffix_ReferenceField = value;
this.RaisePropertyChanged("Honorary_Suffix_Reference");
}
}
[XmlElement(Order = 5)]
public Country_Predefined_Person_Name_Component_ValueObjectType Professional_Suffix_Reference
{
get
{
return this.professional_Suffix_ReferenceField;
}
set
{
this.professional_Suffix_ReferenceField = value;
this.RaisePropertyChanged("Professional_Suffix_Reference");
}
}
[XmlElement(Order = 6)]
public Country_Predefined_Person_Name_Component_ValueObjectType Religious_Suffix_Reference
{
get
{
return this.religious_Suffix_ReferenceField;
}
set
{
this.religious_Suffix_ReferenceField = value;
this.RaisePropertyChanged("Religious_Suffix_Reference");
}
}
[XmlElement(Order = 7)]
public Country_Predefined_Person_Name_Component_ValueObjectType Royal_Suffix_Reference
{
get
{
return this.royal_Suffix_ReferenceField;
}
set
{
this.royal_Suffix_ReferenceField = value;
this.RaisePropertyChanged("Royal_Suffix_Reference");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 25.935897
| 136
| 0.784726
|
[
"MIT"
] |
matteofabbri/Workday.WebServices
|
Workday.FinancialAid/Person_Name_Suffix_DataType.cs
| 4,046
|
C#
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Placeholder
{
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.Configure<SampleOptions>(Configuration);
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 29.55102
| 106
| 0.593923
|
[
"Apache-2.0"
] |
SteeltoeOSS/Samples
|
Configuration/src/Placeholder/Startup.cs
| 1,450
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using Vanara.Extensions;
using Vanara.InteropServices;
namespace Vanara.PInvoke
{
/// <summary>Platform invokable enumerated types, constants and functions from ole32.h</summary>
public static partial class Ole32
{
/// <summary>Specifies the destination context, which is the process in which the unmarshaling is to be done.</summary>
[PInvokeData("wtypesbase.h")]
public enum MSHCTX
{
/// <summary>The unmarshaling process is local and has shared memory access with the marshaling process.</summary>
MSHCTX_LOCAL,
/// <summary>The unmarshaling process does not have shared memory access with the marshaling process.</summary>
MSHCTX_NOSHAREDMEM,
/// <summary>
/// The unmarshaling process is on a different computer. The marshaling code cannot assume that a particular piece of
/// application code is installed on that computer.
/// </summary>
MSHCTX_DIFFERENTMACHINE,
/// <summary>The unmarshaling will be done in another apartment in the same process.</summary>
MSHCTX_INPROC,
/// <summary>Create a new context in the current apartment.</summary>
MSHCTX_CROSSCTX,
/// <summary>Reserved</summary>
MSHCTX_RESERVED1,
}
/// <summary>Specifies why the marshaling is to be done.</summary>
[PInvokeData("wtypesbase.h")]
public enum MSHLFLAGS
{
/// <summary>
/// The marshaling is occurring because an interface pointer is being passed from one process to another. This is the normal
/// case. The data packet produced by the marshaling process will be unmarshaled in the destination process. The marshaled data
/// packet can be unmarshaled just once, or not at all. If the receiver unmarshals the data packet successfully, the
/// CoReleaseMarshalData function is automatically called on the data packet as part of the unmarshaling process. If the
/// receiver does not or cannot unmarshal the data packet, the sender must call CoReleaseMarshalData on the data packet.
/// </summary>
MSHLFLAGS_NORMAL,
/// <summary>
/// The marshaling is occurring because the data packet is to be stored in a globally accessible table from which it can be
/// unmarshaled one or more times, or not at all. The presence of the data packet in the table counts as a strong reference to
/// the interface being marshaled, meaning that it is sufficient to keep the object alive. When the data packet is removed from
/// the table, the table implementer must call the CoReleaseMarshalData function on the data packet.
/// <para>
/// MSHLFLAGS_TABLESTRONG is used by the RegisterDragDrop function when registering a window as a drop target. This keeps the
/// window registered as a drop target no matter how many times the end user drags across the window. The RevokeDragDrop
/// function calls CoReleaseMarshalData.
/// </para>
/// </summary>
MSHLFLAGS_TABLESTRONG,
/// <summary>
/// The marshaling is occurring because the data packet is to be stored in a globally accessible table from which it can be
/// unmarshaled one or more times, or not at all. However, the presence of the data packet in the table acts as a weak reference
/// to the interface being marshaled, meaning that it is not sufficient to keep the object alive. When the data packet is
/// removed from the table, the table implementer must call the CoReleaseMarshalData function on the data packet.
/// <para>
/// MSHLFLAGS_TABLEWEAK is typically used when registering an object in the running object table (ROT). This prevents the
/// object's entry in the ROT from keeping the object alive in the absence of any other connections. See
/// IRunningObjectTable::Register for more information.
/// </para>
/// </summary>
MSHLFLAGS_TABLEWEAK,
/// <summary>
/// Adding this flag to an original object marshaling (as opposed to marshaling a proxy) will disable the ping protocol for that object.
/// </summary>
MSHLFLAGS_NOPING,
/// <summary>Reserved</summary>
MSHLFLAGS_RESERVED1,
/// <summary>Reserved</summary>
MSHLFLAGS_RESERVED2,
/// <summary>Reserved</summary>
MSHLFLAGS_RESERVED3,
/// <summary>Reserved</summary>
MSHLFLAGS_RESERVED4,
}
/// <summary>
/// Indicates whether the method should try to return a name in the pwcsName member of the STATSTG structure. The values are used in
/// the ILockBytes::Stat, IStorage::Stat, and IStream::Stat methods to save memory when the pwcsName member is not required.
/// </summary>
[PInvokeData("WTypes.h", MSDNShortId = "aa380316")]
public enum STATFLAG
{
/// <summary>Requests that the statistics include the pwcsName member of the STATSTG structure.</summary>
STATFLAG_DEFAULT = 0,
/// <summary>
/// Requests that the statistics not include the pwcsName member of the STATSTG structure. If the name is omitted, there is no
/// need for the ILockBytes::Stat, IStorage::Stat, and IStream::Stat methods to allocate and free memory for the string value of
/// the name, therefore the method reduces time and resources used in an allocation and free operation.
/// </summary>
STATFLAG_NONAME = 1,
/// <summary>Not implemented.</summary>
STATFLAG_NOOPEN = 2
}
/// <summary>Specify the conditions for performing the commit operation in the IStorage::Commit and IStream::Commit methods.</summary>
[PInvokeData("WTypes.h", MSDNShortId = "aa380320")]
public enum STGC
{
/// <summary>
/// You can specify this condition with STGC_CONSOLIDATE, or some combination of the other three flags in this list of elements.
/// Use this value to increase the readability of code.
/// </summary>
STGC_DEFAULT = 0,
/// <summary>
/// The commit operation can overwrite existing data to reduce overall space requirements. This value is not recommended for
/// typical usage because it is not as robust as the default value. In this case, it is possible for the commit operation to
/// fail after the old data is overwritten, but before the new data is completely committed. Then, neither the old version nor
/// the new version of the storage object will be intact.
/// <para>You can use this value in the following cases:</para>
/// <list type="bullet">
/// <item>
/// <term>The user is willing to risk losing the data.</term>
/// </item>
/// <item>
/// <term>The low-memory save sequence will be used to safely save the storage object to a smaller file.</term>
/// </item>
/// <item>
/// <term>
/// A previous commit returned STG_E_MEDIUMFULL, but overwriting the existing data would provide enough space to commit changes
/// to the storage object.
/// </term>
/// </item>
/// </list>
/// <para>
/// Be aware that the commit operation verifies that adequate space exists before any overwriting occurs. Thus, even with this
/// value specified, if the commit operation fails due to space requirements, the old data is safe. It is possible, however, for
/// data loss to occur with the STGC_OVERWRITE value specified if the commit operation fails for any reason other than lack of
/// disk space.
/// </para>
/// </summary>
STGC_OVERWRITE = 1,
/// <summary>
/// Prevents multiple users of a storage object from overwriting each other's changes. The commit operation occurs only if there
/// have been no changes to the saved storage object because the user most recently opened it. Thus, the saved version of the
/// storage object is the same version that the user has been editing. If other users have changed the storage object, the
/// commit operation fails and returns the STG_E_NOTCURRENT value. To override this behavior, call the IStorage::Commit or
/// IStream::Commit method again using the STGC_DEFAULT value.
/// </summary>
STGC_ONLYIFCURRENT = 2,
/// <summary>
/// Commits the changes to a write-behind disk cache, but does not save the cache to the disk. In a write-behind disk cache, the
/// operation that writes to disk actually writes to a disk cache, thus increasing performance. The cache is eventually written
/// to the disk, but usually not until after the write operation has already returned. The performance increase comes at the
/// expense of an increased risk of losing data if a problem occurs before the cache is saved and the data in the cache is lost.
/// <para>
/// If you do not specify this value, then committing changes to root-level storage objects is robust even if a disk cache is
/// used. The two-phase commit process ensures that data is stored on the disk and not just to the disk cache.
/// </para>
/// </summary>
STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE = 4,
/// <summary>
/// Windows 2000 and Windows XP: Indicates that a storage should be consolidated after it is committed, resulting in a smaller
/// file on disk. This flag is valid only on the outermost storage object that has been opened in transacted mode. It is not
/// valid for streams. The STGC_CONSOLIDATE flag can be combined with any other STGC flags.
/// </summary>
STGC_CONSOLIDATE = 8
}
/// <summary>Indicate whether a storage element is to be moved or copied. They are used in the IStorage::MoveElementTo method.</summary>
[PInvokeData("WTypes.h", MSDNShortId = "aa380336")]
public enum STGMOVE
{
/// <summary>Indicates that the method should move the data from the source to the destination.</summary>
STGMOVE_MOVE = 0,
/// <summary>
/// Indicates that the method should copy the data from the source to the destination. A copy is the same as a move except that
/// the source element is not removed after copying the element to the destination. Copying an element on top of itself is undefined.
/// </summary>
STGMOVE_COPY = 1,
/// <summary>Not implemented.</summary>
STGMOVE_SHALLOWCOPY = 2
}
/// <summary>Specifies a mapping for a class ID.</summary>
/// <remarks>
/// The TYSPEC enumeration and uCLSSPEC union provide mappings to a class ID. Note that TYSPEC_CLSID is the only supported value.
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/wtypes/ne-wtypes-tyspec typedef enum tagTYSPEC { TYSPEC_CLSID, TYSPEC_FILEEXT,
// TYSPEC_MIMETYPE, TYSPEC_FILENAME, TYSPEC_PROGID, TYSPEC_PACKAGENAME, TYSPEC_OBJECTID } TYSPEC;
[PInvokeData("wtypes.h", MSDNShortId = "f2972300-5a95-43e3-b2d1-cd8f30d14d1d")]
public enum TYSPEC
{
/// <summary>A CLSID.</summary>
TYSPEC_CLSID,
/// <summary>A file name extension.</summary>
TYSPEC_FILEEXT,
/// <summary>A MIME type.</summary>
TYSPEC_MIMETYPE,
/// <summary>A file name.</summary>
TYSPEC_FILENAME,
/// <summary>A PROGID.</summary>
TYSPEC_PROGID,
/// <summary>A package name.</summary>
TYSPEC_PACKAGENAME,
/// <summary>An object ID.</summary>
TYSPEC_OBJECTID,
}
/// <summary>Equivalent to <see cref="VarEnum"/>, but cast to <see cref="ushort"/>.</summary>
[Flags]
[PInvokeData("Wtypes.h", MSDNShortId = "ms221127")]
public enum VARTYPE : ushort
{
/// <summary>Not specified.</summary>
[CorrespondingType(typeof(object))]
VT_EMPTY = 0,
/// <summary>Null.</summary>
[CorrespondingType(typeof(DBNull))]
VT_NULL = 1,
/// <summary>A 2-byte integer.</summary>
[CorrespondingType(typeof(short))]
VT_I2 = 2,
/// <summary>A 4-byte integer.</summary>
[CorrespondingType(typeof(int))]
VT_I4 = 3,
/// <summary>A 4-byte real.</summary>
[CorrespondingType(typeof(float))]
VT_R4 = 4,
/// <summary>A 8-byte real.</summary>
[CorrespondingType(typeof(double))]
VT_R8 = 5,
/// <summary>Currency</summary>
[CorrespondingType(typeof(decimal))]
VT_CY = 6,
/// <summary>A date.</summary>
[CorrespondingType(typeof(DateTime))]
VT_DATE = 7,
/// <summary>A string.</summary>
[CorrespondingType(typeof(string))]
VT_BSTR = 8,
/// <summary>An IDispatch pointer.</summary>
[CorrespondingType(typeof(object))]
VT_DISPATCH = 9,
/// <summary>An SCODE value.</summary>
[CorrespondingType(typeof(Win32Error))]
VT_ERROR = 10,
/// <summary>A Boolean value. True is -1 and false is 0.</summary>
[CorrespondingType(typeof(bool))]
VT_BOOL = 11,
/// <summary>A variant pointer.</summary>
[CorrespondingType(typeof(object))]
VT_VARIANT = 12,
/// <summary>An IUnknown pointer.</summary>
[CorrespondingType(typeof(object))]
VT_UNKNOWN = 13,
/// <summary>A 16-byte fixed-point value.</summary>
[CorrespondingType(typeof(decimal))]
VT_DECIMAL = 14,
/// <summary>A character.</summary>
[CorrespondingType(typeof(sbyte))]
VT_I1 = 16,
/// <summary>An unsigned character.</summary>
[CorrespondingType(typeof(byte))]
VT_UI1 = 17,
/// <summary>An unsigned short.</summary>
[CorrespondingType(typeof(ushort))]
VT_UI2 = 18,
/// <summary>An unsigned long.</summary>
[CorrespondingType(typeof(uint))]
VT_UI4 = 19,
/// <summary>A 64-bit integer.</summary>
[CorrespondingType(typeof(long))]
VT_I8 = 20,
/// <summary>A 64-bit unsigned integer.</summary>
[CorrespondingType(typeof(ulong))]
VT_UI8 = 21,
/// <summary>An integer.</summary>
[CorrespondingType(typeof(int))]
VT_INT = 22,
/// <summary>An unsigned integer.</summary>
[CorrespondingType(typeof(uint))]
VT_UINT = 23,
/// <summary>A C-style void.</summary>
[CorrespondingType(typeof(IntPtr))]
VT_VOID = 24,
/// <summary>A C-style void.</summary>
[CorrespondingType(typeof(double))]
VT_HRESULT = 25,
/// <summary>A pointer type.</summary>
[CorrespondingType(typeof(IntPtr))]
VT_PTR = 26,
/// <summary>A safe array. Use VT_ARRAY in VARIANT.</summary>
VT_SAFEARRAY = 27,
/// <summary>A C-style array.</summary>
VT_CARRAY = 28,
/// <summary>A user-defined type.</summary>
[CorrespondingType(typeof(IntPtr))]
VT_USERDEFINED = 29,
/// <summary>A null-terminated string.</summary>
[CorrespondingType(typeof(string))]
VT_LPSTR = 30,
/// <summary>A wide null-terminated string.</summary>
[CorrespondingType(typeof(string))]
VT_LPWSTR = 31,
/// <summary>A user-defined type.</summary>
[CorrespondingType(typeof(IntPtr))]
VT_RECORD = 36,
/// <summary>A FILETIME value.</summary>
[CorrespondingType(typeof(System.Runtime.InteropServices.ComTypes.FILETIME))]
VT_FILETIME = 64,
/// <summary>Length-prefixed bytes.</summary>
[CorrespondingType(typeof(BLOB))]
VT_BLOB = 65,
/// <summary>The name of the stream follows.</summary>
[CorrespondingType(typeof(IStream))]
VT_STREAM = 66,
/// <summary>The name of the storage follows.</summary>
[CorrespondingType(typeof(IStorage))]
VT_STORAGE = 67,
/// <summary>The stream contains an object.</summary>
[CorrespondingType(typeof(IStream))]
VT_STREAMED_OBJECT = 68,
/// <summary>The storage contains an object.</summary>
[CorrespondingType(typeof(IStorage))]
VT_STORED_OBJECT = 69,
/// <summary>The blob contains an object.</summary>
VT_BLOB_OBJECT = 70,
/// <summary>A clipboard format.</summary>
[CorrespondingType(typeof(CLIPDATA))]
VT_CF = 71,
/// <summary>A class ID (GUID).</summary>
[CorrespondingType(typeof(Guid))]
VT_CLSID = 72,
/// <summary>A stream with a GUID version.</summary>
VT_VERSIONED_STREAM = 73,
/// <summary>A simple counted array.</summary>
VT_VECTOR = 0x1000,
/// <summary>A SAFEARRAY pointer.</summary>
VT_ARRAY = 0x2000,
/// <summary>A void pointer for local use.</summary>
VT_BYREF = 0x4000,
}
/// <summary>Gets the .NET runtime type which corresponds to the <see cref="VARTYPE"/>.</summary>
/// <param name="vt">The <see cref="VARTYPE"/> enumeration value to evaluate.</param>
/// <returns>
/// <para>The corresponding .NET runtime type.</para>
/// <para>
/// If <paramref name="vt"/> specifies <see cref="VARTYPE.VT_VECTOR"/> or <see cref="VARTYPE.VT_ARRAY"/>, the return type is an
/// array of the element type.
/// </para>
/// <para>
/// If <paramref name="vt"/> specifies <see cref="VARTYPE.VT_BYREF"/> and the element type is a value type, the return type is a
/// pointer to the element type.
/// </para>
/// </returns>
public static Type GetCorrespondingType(this VARTYPE vt)
{
var elemVT = vt & ~(VARTYPE)0xF000;
var specVT = vt & (VARTYPE)0xF000;
var type = CorrespondingTypeAttribute.GetCorrespondingTypes(elemVT).FirstOrDefault();
if (type is null || elemVT == 0)
return null;
// Change type if by reference
if (specVT.IsFlagSet(VARTYPE.VT_BYREF) && type.IsValueType)
type = type.MakePointerType();
// Change type if vector
if (specVT.IsFlagSet(VARTYPE.VT_VECTOR) || specVT.IsFlagSet(VARTYPE.VT_ARRAY))
type = type.MakeArrayType();
return type;
}
/// <summary>Contains an operating system platform and processor architecture.</summary>
// https://docs.microsoft.com/en-us/windows/win32/api/wtypes/ns-wtypes-csplatform typedef struct tagCSPLATFORM { DWORD dwPlatformId;
// DWORD dwVersionHi; DWORD dwVersionLo; DWORD dwProcessorArch; } CSPLATFORM;
[PInvokeData("wtypes.h", MSDNShortId = "e9ffa8ba-98a2-431c-a069-20ed4a45e6f8")]
[StructLayout(LayoutKind.Sequential)]
public struct CSPLATFORM
{
/// <summary>The operating system platform. See the <c>dwPlatformId</c> member of OSVERSIONINFO.</summary>
public PlatformID dwPlatformId;
/// <summary>The major version of the operating system.</summary>
public uint dwVersionHi;
/// <summary>The minor version of the operating system.</summary>
public uint dwVersionLo;
/// <summary>The processor architecture. See the <c>wProcessorArchitecture</c> member of SYSTEM_INFO.</summary>
public ProcessorArchitecture dwProcessorArch;
}
/// <summary>Contains a list of attributes used to look up a class implementation.</summary>
// https://docs.microsoft.com/en-us/windows/win32/api/wtypes/ns-wtypes-querycontext typedef struct tagQUERYCONTEXT { DWORD
// dwContext; CSPLATFORM Platform; LCID Locale; DWORD dwVersionHi; DWORD dwVersionLo; } QUERYCONTEXT;
[PInvokeData("wtypes.h", MSDNShortId = "5d6a17e1-dcdd-4691-aec2-f63dbcb26027")]
[StructLayout(LayoutKind.Sequential)]
public struct QUERYCONTEXT
{
/// <summary>The execution context.</summary>
public CLSCTX dwContext;
/// <summary>The operating system platform and processor architecture. For more information, see CSPLATFORM.</summary>
public CSPLATFORM Platform;
/// <summary>The locale identifier. For more information, see Language Identifier Constants and Strings.</summary>
public LCID Locale;
/// <summary>The high version number.</summary>
public uint dwVersionHi;
/// <summary>The low version number.</summary>
public uint dwVersionLo;
}
/// <summary>Specifies a mapping for a class ID.</summary>
/// <remarks>
/// The TYSPEC enumeration and uCLSSPEC union provide mappings to a class ID. Note that TYSPEC_CLSID is the only supported value.
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/wtypes/ne-wtypes-tyspec typedef enum tagTYSPEC { TYSPEC_CLSID, TYSPEC_FILEEXT,
// TYSPEC_MIMETYPE, TYSPEC_FILENAME, TYSPEC_PROGID, TYSPEC_PACKAGENAME, TYSPEC_OBJECTID } TYSPEC;
[PInvokeData("wtypes.h", MSDNShortId = "f2972300-5a95-43e3-b2d1-cd8f30d14d1d")]
[StructLayout(LayoutKind.Sequential)]
public struct uCLSSPEC
{
/// <summary>The union type.</summary>
public TYSPEC tyspec;
/// <summary>The union.</summary>
public SpecUnion tagged_union;
/// <summary>The union.</summary>
[StructLayout(LayoutKind.Explicit)]
public struct SpecUnion
{
/// <summary/>
[FieldOffset(0)] public Guid clsid;
/// <summary/>
[FieldOffset(0)] public StrPtrUni pFileExt;
/// <summary/>
[FieldOffset(0)] public StrPtrUni pMimeType;
/// <summary/>
[FieldOffset(0)] public StrPtrUni pProgId;
/// <summary/>
[FieldOffset(0)] public StrPtrUni pFileName;
/// <summary/>
[FieldOffset(0)] public BYNAME ByName;
/// <summary/>
[FieldOffset(0)] public BYOBJECTID ByObjectId;
/// <summary/>
public struct BYNAME
{
/// <summary/>
public StrPtrUni pPackageName;
/// <summary/>
public Guid PolicyId;
}
/// <summary/>
public struct BYOBJECTID
{
/// <summary/>
public Guid ObjectId;
/// <summary/>
public Guid PolicyId;
}
}
}
}
}
| 37.632058
| 139
| 0.70092
|
[
"MIT"
] |
AndreGleichner/Vanara
|
PInvoke/Ole/Ole32/WTypes.cs
| 20,662
|
C#
|
using System;
using System.Threading.Tasks;
namespace ITLIBRIUM.BddToolkit.Examples
{
public interface PrePaidAccountHistoryDao
{
Task Append(Recharged recharged);
public Task<PrePaidAccountHistory> GetBy(Guid accountId);
}
}
| 23.090909
| 65
| 0.740157
|
[
"MIT"
] |
Magicianred/BDD-toolkit-dotnet
|
BddToolkit.Examples.UseCases/PrePaidAccountHistoryDao.cs
| 254
|
C#
|
using hcloud_api.Models.Objects.Datacenters;
using Newtonsoft.Json;
namespace hcloud_api.Models.Objects
{
public class Datacenter
{
/// <summary>
/// ID of the Resource
/// </summary>
[JsonProperty("id")]
public int Id { get; set; }
/// <summary>
/// Unique identifier of the Datacenter
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Description of the Datacenter
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("location")]
public Location Location { get; set; }
/// <summary>
/// The Server types the Datacenter can handle
/// </summary>
[JsonProperty("server_types")]
public DcServerTypes ServerTypes { get; set; }
}
}
| 25.472222
| 54
| 0.549618
|
[
"MIT"
] |
djsvist/hcloud-api-net
|
hcloud-api/Models/Objects/Datacenter.cs
| 919
|
C#
|
#region Copyright (c) OPTANO GmbH
// ////////////////////////////////////////////////////////////////////////////////
//
// OPTANO GmbH Source Code
// Copyright (c) 2010-2021 OPTANO GmbH
// ALL RIGHTS RESERVED.
//
// The entire contents of this file is protected by German and
// International Copyright Laws. Unauthorized reproduction,
// reverse-engineering, and distribution of all or any portion of
// the code contained in this file is strictly prohibited and may
// result in severe civil and criminal penalties and will be
// prosecuted to the maximum extent possible under the law.
//
// RESTRICTIONS
//
// THIS SOURCE CODE AND ALL RESULTING INTERMEDIATE FILES
// ARE CONFIDENTIAL AND PROPRIETARY TRADE SECRETS OF
// OPTANO GMBH.
//
// THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED
// FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE
// COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE
// AVAILABLE TO OTHER INDIVIDUALS WITHOUT WRITTEN CONSENT
// AND PERMISSION FROM OPTANO GMBH.
//
// ////////////////////////////////////////////////////////////////////////////////
#endregion
namespace Optano.Algorithm.Tuner.Application
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Optano.Algorithm.Tuner.Configuration;
/// <summary>
/// Contains all relevant parameters for this adapter.
/// </summary>
public class ApplicationRunnerConfiguration : ConfigurationBase
{
#region Public properties
/// <summary>
/// Gets the basic command to the target algorithm.
/// </summary>
public string BasicCommand { get; private set; }
/// <summary>
/// Gets the path to an XML file defining the parameter tree.
/// </summary>
public string PathToParameterTree { get; private set; }
/// <summary>
/// Gets a value indicating whether whether the target algorithm should be tuned by value (otherwise, it's tuned by runtime).
/// </summary>
public bool TuneByValue { get; private set; }
/// <summary>
/// Gets a value indicating whether whether lower values are better than higher ones.
/// </summary>
public bool SortValuesAscendingly { get; private set; }
/// <summary>
/// Gets the factor for the penalization of the average runtime.
/// </summary>
public int FactorParK { get; private set; }
#endregion
#region Public Methods and Operators
/// <inheritdoc />
public override bool IsCompatible(ConfigurationBase other)
{
// Currently, we cannot check other configs than the AlgorithmTunerConfiguration for compatibility.
return true;
}
/// <inheritdoc />
public override bool IsTechnicallyCompatible(ConfigurationBase other)
{
return true;
}
/// <inheritdoc />
public override string ToString()
{
var builder = new StringBuilder("ApplicationRunnerConfiguration:\r\n");
builder.AppendLine($"{nameof(ApplicationRunnerConfiguration.BasicCommand)}: {this.BasicCommand}")
.AppendLine($"{nameof(ApplicationRunnerConfiguration.PathToParameterTree)}: {this.PathToParameterTree}")
.AppendLine($"{nameof(ApplicationRunnerConfiguration.TuneByValue)}: {this.TuneByValue}")
.AppendLine($"{nameof(ApplicationRunnerConfiguration.SortValuesAscendingly)}: {this.SortValuesAscendingly}")
.AppendLine($"{nameof(ApplicationRunnerConfiguration.FactorParK)}: {this.FactorParK}");
return builder.ToString();
}
#endregion
/// <summary>
/// The <see cref="IConfigBuilder{TConfiguration}"/> of <see cref="ApplicationRunnerConfiguration"/>.
/// </summary>
[SuppressMessage(
"NDepend",
"ND1305:NestedTypesShouldNotBeVisible",
Justification = "This type is part of the Builder pattern.")]
public class ApplicationConfigurationBuilder : IConfigBuilder<ConfigurationBase>
{
#region Fields
/// <summary>
/// The basic command to the target algorithm as specified by the parsed arguments.
/// </summary>
private string _basicCommand;
/// <summary>
/// The path to an XML file defining the parameter tree as specified by the parsed arguments.
/// </summary>
private string _pathToParameterTree;
/// <summary>
/// A value indicating whether the target algorithm should be tuned by value (otherwise, it's tuned by runtime).
/// </summary>
private bool? _tuneByValue = false;
/// <summary>
/// A value indicating whether lower values are better than higher ones.
/// </summary>
private bool? _sortValuesAscendingly = true;
/// <summary>
/// The factor for the penalization of the average runtime.
/// </summary>
private int? _factorParK = 0;
#endregion
#region Public properties
/// <summary>
/// Gets a value indicating whether this instance has path to parameter tree.
/// </summary>
/// <value>
/// <c>true</c> if this instance has path to parameter tree; otherwise, <c>false</c>.
/// </value>
public bool HasPathToParameterTree => !string.IsNullOrWhiteSpace(this._pathToParameterTree);
/// <summary>
/// Gets a value indicating whether this instance has basic command.
/// </summary>
/// <value>
/// <c>true</c> if this instance has basic command; otherwise, <c>false</c>.
/// </value>
public bool HasBasicCommand => !string.IsNullOrWhiteSpace(this._basicCommand);
#endregion
#region Public Methods and Operators
/// <summary>
/// Sets <see cref="ApplicationRunnerConfiguration.BasicCommand"/>.
/// </summary>
/// <param name="basicCommand">The basic command.</param>
/// <returns>The <see cref="ApplicationConfigurationBuilder"/> in its new state.</returns>
public ApplicationConfigurationBuilder SetBasicCommand(string basicCommand)
{
this._basicCommand = basicCommand;
return this;
}
/// <summary>
/// Sets <see cref="ApplicationRunnerConfiguration.PathToParameterTree"/>.
/// </summary>
/// <param name="pathToParameterTree">The path to the parameter tree.</param>
/// <returns>The <see cref="ApplicationConfigurationBuilder"/> in its new state.</returns>
public ApplicationConfigurationBuilder SetPathToParameterTree(string pathToParameterTree)
{
this._pathToParameterTree = pathToParameterTree;
return this;
}
/// <summary>
/// Sets <see cref="ApplicationRunnerConfiguration.TuneByValue"/>.
/// </summary>
/// <param name="tuneByValue">The TuneByValue-Boolean.</param>
/// <returns>The <see cref="ApplicationConfigurationBuilder"/> in its new state.</returns>
public ApplicationConfigurationBuilder SetTuneByValue(bool tuneByValue)
{
this._tuneByValue = tuneByValue;
return this;
}
/// <summary>
/// Sets <see cref="ApplicationRunnerConfiguration.SortValuesAscendingly"/>.
/// </summary>
/// <param name="sortValuesAscendingly">The SortValuesAscendingly-Boolean.</param>
/// <returns>The <see cref="ApplicationConfigurationBuilder"/> in its new state.</returns>
public ApplicationConfigurationBuilder SetSortValuesAscendingly(bool sortValuesAscendingly)
{
this._sortValuesAscendingly = sortValuesAscendingly;
return this;
}
/// <summary>
/// Sets <see cref="ApplicationRunnerConfiguration.FactorParK"/>.
/// </summary>
/// <param name="factorParK">The factor for the penalization of the average runtime.</param>
/// <returns>The <see cref="ApplicationConfigurationBuilder"/> in its new state.</returns>
public ApplicationConfigurationBuilder SetFactorParK(int factorParK)
{
if (factorParK < 0)
{
throw new ArgumentOutOfRangeException(
nameof(factorParK),
$"{nameof(factorParK)} needs to be greater or equal to 0.");
}
this._factorParK = factorParK;
return this;
}
/// <summary>
/// Builds the <see cref="ApplicationRunnerConfiguration"/>.
/// </summary>
/// <returns>
/// The <see cref="ApplicationRunnerConfiguration"/>.
/// </returns>
public ApplicationRunnerConfiguration Build()
{
return this.BuildWithFallback(null);
}
/// <summary>
/// Builds the <see cref="ApplicationRunnerConfiguration"/>.
/// </summary>
/// <param name="basicCommand">The basic command.</param>
/// <param name="pathToParameterTree">The path to the parameter tree.</param>
/// <returns>
/// The <see cref="ApplicationRunnerConfiguration"/>.
/// </returns>
public ApplicationRunnerConfiguration Build(string basicCommand, string pathToParameterTree)
{
this._basicCommand = basicCommand;
this._pathToParameterTree = pathToParameterTree;
return this.BuildWithFallback(null);
}
/// <inheritdoc />
public ConfigurationBase BuildWithFallback(ConfigurationBase fallback)
{
return this.BuildWithFallback(ConfigurationBase.CastToConfigurationType<ApplicationRunnerConfiguration>(fallback));
}
#endregion
#region Methods
/// <summary>
/// Builds the <see cref="ApplicationRunnerConfiguration"/> with fallback.
/// </summary>
/// <param name="fallback">The fallback.</param>
/// <returns>
/// The <see cref="ApplicationRunnerConfiguration"/>.
/// </returns>
private ApplicationRunnerConfiguration BuildWithFallback(ApplicationRunnerConfiguration fallback)
{
var config = new ApplicationRunnerConfiguration
{
BasicCommand = this._basicCommand ?? fallback?.BasicCommand
?? throw new InvalidOperationException("You must set the basic command!"),
PathToParameterTree = this._pathToParameterTree ?? fallback?.PathToParameterTree
?? throw new InvalidOperationException("You must set the path to the parameter tree!"),
TuneByValue = this._tuneByValue ?? fallback?.TuneByValue ?? false,
SortValuesAscendingly = this._sortValuesAscendingly ?? fallback?.SortValuesAscendingly
?? true,
FactorParK = this._factorParK ??
fallback?.FactorParK ??
0,
};
return config;
}
#endregion
}
}
}
| 41.851724
| 146
| 0.566038
|
[
"MIT"
] |
OPTANO/optano.algorithm.tuner.examples
|
Source/Tuner.Application/Optano.Algorithm.Tuner.Application/ApplicationRunnerConfiguration.cs
| 12,139
|
C#
|
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Example script that can be used to show tooltips.
/// </summary>
[AddComponentMenu("NGUI/UI/Tooltip")]
public class UITooltip : MonoBehaviour
{
static protected UITooltip mInstance;
public Camera uiCamera;
public UILabel text;
public UISprite background;
public float appearSpeed = 10f;
public bool scalingTransitions = true;
protected Transform mTrans;
protected float mTarget = 0f;
protected float mCurrent = 0f;
protected Vector3 mPos;
protected Vector3 mSize = Vector3.zero;
protected UIWidget[] mWidgets;
/// <summary>
/// Whether the tooltip is currently visible.
/// </summary>
static public bool isVisible { get { return (mInstance != null && mInstance.mTarget == 1f); } }
void Awake () { mInstance = this; }
void OnDestroy () { mInstance = null; }
/// <summary>
/// Get a list of widgets underneath the tooltip.
/// </summary>
protected virtual void Start ()
{
mTrans = transform;
mWidgets = GetComponentsInChildren<UIWidget>();
mPos = mTrans.localPosition;
if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
SetAlpha(0f);
}
/// <summary>
/// Update the tooltip's alpha based on the target value.
/// </summary>
protected virtual void Update ()
{
if (mCurrent != mTarget)
{
mCurrent = Mathf.Lerp(mCurrent, mTarget, RealTime.deltaTime * appearSpeed);
if (Mathf.Abs(mCurrent - mTarget) < 0.001f) mCurrent = mTarget;
SetAlpha(mCurrent * mCurrent);
if (scalingTransitions)
{
Vector3 offset = mSize * 0.25f;
offset.y = -offset.y;
Vector3 size = Vector3.one * (1.5f - mCurrent * 0.5f);
Vector3 pos = Vector3.Lerp(mPos - offset, mPos, mCurrent);
mTrans.localPosition = pos;
mTrans.localScale = size;
}
}
}
/// <summary>
/// Set the alpha of all widgets.
/// </summary>
protected virtual void SetAlpha (float val)
{
for (int i = 0, imax = mWidgets.Length; i < imax; ++i)
{
UIWidget w = mWidgets[i];
Color c = w.color;
c.a = val;
w.color = c;
}
}
/// <summary>
/// Set the tooltip's text to the specified string.
/// </summary>
protected virtual void SetText (string tooltipText)
{
if (text != null && !string.IsNullOrEmpty(tooltipText))
{
mTarget = 1f;
if (text != null) text.text = tooltipText;
// Orthographic camera positioning is trivial
mPos = Input.mousePosition;
if (background != null && !background.isAnchored)
{
Transform textTrans = text.transform;
Vector3 offset = textTrans.localPosition;
Vector3 textScale = textTrans.localScale;
// Calculate the dimensions of the printed text
mSize = text.printedSize;
// Scale by the transform and adjust by the padding offset
mSize.x *= textScale.x;
mSize.y *= textScale.y;
Vector4 border = background.border;
mSize.x += border.x + border.z + ( offset.x - border.x) * 2f;
mSize.y += border.y + border.w + (-offset.y - border.y) * 2f;
background.width = Mathf.RoundToInt(mSize.x);
background.height = Mathf.RoundToInt(mSize.y);
}
if (uiCamera != null)
{
// Since the screen can be of different than expected size, we want to convert
// mouse coordinates to view space, then convert that to world position.
mPos.x = Mathf.Clamp01(mPos.x / Screen.width);
mPos.y = Mathf.Clamp01(mPos.y / Screen.height);
// Calculate the ratio of the camera's target orthographic size to current screen size
float activeSize = uiCamera.orthographicSize / mTrans.parent.lossyScale.y;
float ratio = (Screen.height * 0.5f) / activeSize;
// Calculate the maximum on-screen size of the tooltip window
Vector2 max = new Vector2(ratio * mSize.x / Screen.width, ratio * mSize.y / Screen.height);
// Limit the tooltip to always be visible
mPos.x = Mathf.Min(mPos.x, 1f - max.x);
mPos.y = Mathf.Max(mPos.y, max.y);
// Update the absolute position and save the local one
mTrans.position = uiCamera.ViewportToWorldPoint(mPos);
mPos = mTrans.localPosition;
mPos.x = Mathf.Round(mPos.x);
mPos.y = Mathf.Round(mPos.y);
mTrans.localPosition = mPos;
}
else
{
// Don't let the tooltip leave the screen area
if (mPos.x + mSize.x > Screen.width) mPos.x = Screen.width - mSize.x;
if (mPos.y - mSize.y < 0f) mPos.y = mSize.y;
// Simple calculation that assumes that the camera is of fixed size
mPos.x -= Screen.width * 0.5f;
mPos.y -= Screen.height * 0.5f;
}
}
else mTarget = 0f;
}
/// <summary>
/// Show a tooltip with the specified text.
/// </summary>
static public void ShowText (string tooltipText)
{
if (mInstance != null)
{
mInstance.SetText(tooltipText);
}
}
}
| 26.931818
| 96
| 0.666878
|
[
"Unlicense"
] |
Skipbits/TinyBox
|
Assets/NGUI/Scripts/UI/UITooltip.cs
| 4,740
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Brightcove.MediaFramework.Brightcove.Entities;
using Brightcove.MediaFramework.Brightcove.Pipelines.VideoUpload;
using Sitecore.Data.Items;
using Sitecore.MediaFramework.Diagnostics;
namespace Brightcove.MediaFramework.Brightcove.Upload
{
public interface IStorageService
{
StorageExecutorBase GetExecutor();
}
public interface IStorageService<out TConfig> : IStorageService where TConfig : StorageServiceConfigBase
{
TConfig Config { get; }
}
public abstract class StorageExecutorBase
{
public abstract UploadFileInfo RetrieveFile(string fileId);
public virtual object Save(UploadFileInfo uploadFileInfo)
{
return Save(new List<UploadFileInfo> { uploadFileInfo }).FirstOrDefault();
}
public virtual IEnumerable<object> Save(IList<UploadFileInfo> uploadFiles)
{
return uploadFiles.Select(SaveFile).ToList();
}
protected abstract object SaveFile(UploadFileInfo uploadFileInfo);
public abstract bool Delete(string itemId);
}
public abstract class StorageExecutorBase<TConfig> : StorageExecutorBase
where TConfig : StorageServiceConfigBase
{
public TConfig Config;
protected StorageExecutorBase(TConfig config)
{
Config = config;
}
}
public static class StorageServiceManager
{
public static IStorageService Service;
static StorageServiceManager()
{
Service = Sitecore.Configuration.Factory.CreateObject("Brightcove.StorageService", true) as
IStorageService;
}
public static UploadFileInfo RetrieveFile(string fileId)
{
return Service.GetExecutor().RetrieveFile(fileId);
}
public static bool Delete(string requestId, Notification notification)
{
return Service.GetExecutor().Delete(requestId);
}
}
}
| 28.71831
| 108
| 0.680726
|
[
"Apache-2.0"
] |
KRazguliaev/pmi.sitecore.9.1.brightcove
|
src/Brightcove.MediaFramework.Brightcove/Upload/StorageServiceManager.cs
| 2,041
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Unit : MonoBehaviour
{
public static Dictionary<string, List<Unit>> unitsByType;
public string type;
public float health = 100;
public GameObject healthBarFront;
//the state of the unit
public STATE state;
//not all units will have all states implemented
[System.Serializable]
public enum STATE
{
MOVE,//the unit is just moving
ATTACK_MOVE,//the unit is moving until it can attack
ATTACK,//the unit is attacking(possibly redundant due to HOLD and ATTACK_MOVE)!!!
HOLD,//the unit is not moving but will try to attack
IDLE,//Unit will do nothing and try to transition state
STOP//Unit will do nothing and not try to transition state(state must be changed externally)
}
// Start is called before the first frame update
protected void Start()
{
if(unitsByType == null)
{
unitsByType = new Dictionary<string, List<Unit>>();
}
if(unitsByType.ContainsKey(type) == false)
{
unitsByType.Add(type, new List<Unit>());
}
unitsByType[type].Add(this);
state = STATE.IDLE;
if(gameObject.transform.Find("HealthBar") != null)
{
healthBarFront = gameObject.transform.Find("HealthBar").Find("Front").gameObject;
}
else
{
Debug.Log("healthbar not found in unit.Start()!");
}
}
/// <summary>
/// applies damage to the target
/// </summary>
/// <param name="dmg">amount of damage done(negative values heal)</param>
/// <returns>returns true if the target looses all health</returns>
public bool applyDamage(float dmg)
{
health -= dmg;
healthBarFront.transform.localScale = new Vector3( health / 100, healthBarFront.transform.localScale.y, healthBarFront.transform.localScale.z);
if(health > 500)
{
health = 500;
}
if (health <= 0)
{
onDeath();
unitsByType[type].Remove(this);//remove this instance from the list
Destroy(gameObject);//destory the gameobject
return true;//i am dead
}
else
{
return false;
}
}
protected virtual void onDeath()
{
//dead
}
// Update is called once per frame
void Update()
{
}
}
| 28.011236
| 151
| 0.593261
|
[
"MIT"
] |
enyaw15/LudumDare44
|
Assets/Scripts/Unit.cs
| 2,495
|
C#
|
using System;
namespace TeaDriven.Graphology.Visualization
{
public class TextGraphVisualization : IGraphVisualization
{
#region Dependencies
private readonly IGetNodeString _getNodeString;
#endregion Dependencies
#region Constructors
public TextGraphVisualization(IGetNodeString getNodeString)
{
if (getNodeString == null) throw new ArgumentNullException("getNodeString");
this._getNodeString = getNodeString;
}
#endregion Constructors
#region IGraphVisualization Members
public string Draw(GraphNode graphNode)
{
return this.Draw(graphNode, 0);
}
#endregion IGraphVisualization Members
#region Internal methods
private string Draw(GraphNode graphNode, int depth)
{
string graph = this._getNodeString.For(graphNode, depth) + Environment.NewLine;
depth++;
foreach (GraphNode subGraphNode in graphNode.SubGraph)
{
graph += this.Draw(subGraphNode, depth);
}
return graph;
}
#endregion Internal methods
}
}
| 23.529412
| 91
| 0.618333
|
[
"MIT"
] |
TeaDrivenDev/Graphology
|
Src/TeaDriven.Graphology/Visualization/TextGraphVisualization.cs
| 1,202
|
C#
|
using Microsoft.AspNet.OData.Builder;
using Microsoft.OData.Edm;
using System;
namespace WidgetWebAPI.Support
{
class DomainModelBuilder : ODataConventionModelBuilder
{
#region Constructor(s)
public DomainModelBuilder(IServiceProvider serviceProvider) : base(serviceProvider) { }
#endregion
public override IEdmModel GetEdmModel()
{
Namespace = "WidgetData"; // Hide Model Schema from $metadata
EntityTypeConfiguration<Domain.Widget> WidgetConfiguration = EntitySet<Domain.Widget>("Widget").EntityType;
WidgetConfiguration
.HasKey(e => e.WidgetId)
.Filter() // Allow for the $filter Command
.Count() // Allow for the $count Command
.Expand() // Allow for the $expand Command
.OrderBy() // Allow for the $orderby Command
.Page() // Allow for the $top and $skip Commands
.Select(); // Allow for the $select Command;
WidgetConfiguration.HasMany(e => e.Part);
EntityTypeConfiguration<Domain.WidgetPart> WidgetPartConfiguration = EntityType<Domain.WidgetPart>();
WidgetPartConfiguration.HasKey(e => new { e.WidgetId, e.PartId, e.BlueprintId });
EntityTypeConfiguration<Domain.Supplier> SupplierConfiguration = EntitySet<Domain.Supplier>("Supplier").EntityType;
SupplierConfiguration
.HasKey(e => e.SupplierId)
.Filter() // Allow for the $filter Command
.Count() // Allow for the $count Command
.Expand() // Allow for the $expand Command
.OrderBy() // Allow for the $orderby Command
.Page() // Allow for the $top and $skip Commands
.Select(); // Allow for the $select Command;
SupplierConfiguration.HasMany(e => e.Part);
EntityTypeConfiguration<Domain.SupplierPart> SupplierPartConfiguration = EntityType<Domain.SupplierPart>();
SupplierPartConfiguration.HasKey(e => new { e.SupplierId, e.PartId });
EntityTypeConfiguration<Domain.Part> PartConfiguration = EntitySet<Domain.Part>("Part").EntityType;
PartConfiguration
.HasKey(e => e.PartId)
.Filter() // Allow for the $filter Command
.Count() // Allow for the $count Command
.Expand() // Allow for the $expand Command
.OrderBy() // Allow for the $orderby Command
.Page() // Allow for the $top and $skip Commands
.Select(); // Allow for the $select Command;
PartConfiguration.HasMany(e => e.Supplier);
PartConfiguration.HasMany(e => e.Widget);
return base.GetEdmModel();
}
}
}
| 37.246154
| 118
| 0.702189
|
[
"MIT"
] |
mitselplik/widget-web-api
|
Support/DomainModelBuilder.cs
| 2,423
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace hotspot
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.956522
| 66
| 0.583333
|
[
"Apache-2.0"
] |
cybex-dev/Wifi-Hotspot
|
hotspot-source/hotspot/Program.cs
| 530
|
C#
|
using EventStore.ClientAPI;
using NUnit.Framework;
using EventStore.Core.Tests.ClientAPI.Helpers;
using EventStore.Core.Tests.Helpers;
namespace EventStore.Core.Tests.ClientAPI.Embedded {
public class
happy_case_writing_and_subscribing_to_normal_events_manual_ack : ClientAPI.
happy_case_writing_and_subscribing_to_normal_events_manual_ack {
protected override IEventStoreConnection BuildConnection(MiniNode node) {
return EmbeddedTestConnection.To(node);
}
}
public class
happy_case_writing_and_subscribing_to_normal_events_auto_ack : ClientAPI.
happy_case_writing_and_subscribing_to_normal_events_auto_ack {
protected override IEventStoreConnection BuildConnection(MiniNode node) {
return EmbeddedTestConnection.To(node);
}
}
public class
happy_case_catching_up_to_normal_events_auto_ack : ClientAPI.happy_case_catching_up_to_normal_events_auto_ack {
protected override IEventStoreConnection BuildConnection(MiniNode node) {
return EmbeddedTestConnection.To(node);
}
}
public class
happy_case_catching_up_to_normal_events_manual_ack : ClientAPI.
happy_case_catching_up_to_normal_events_manual_ack {
protected override IEventStoreConnection BuildConnection(MiniNode node) {
return EmbeddedTestConnection.To(node);
}
}
public class
happy_case_catching_up_to_link_to_events_manual_ack : ClientAPI.
happy_case_catching_up_to_link_to_events_manual_ack {
protected override IEventStoreConnection BuildConnection(MiniNode node) {
return EmbeddedTestConnection.To(node);
}
}
public class
happy_case_catching_up_to_link_to_events_auto_ack : ClientAPI.
happy_case_catching_up_to_link_to_events_auto_ack {
protected override IEventStoreConnection BuildConnection(MiniNode node) {
return EmbeddedTestConnection.To(node);
}
}
public class
when_writing_and_subscribing_to_normal_events_manual_nack : ClientAPI.
when_writing_and_subscribing_to_normal_events_manual_nack {
protected override IEventStoreConnection BuildConnection(MiniNode node) {
return EmbeddedTestConnection.To(node);
}
}
}
| 33.580645
| 113
| 0.838617
|
[
"Apache-2.0",
"CC0-1.0"
] |
01100010011001010110010101110000/EventStore
|
src/EventStore.Core.Tests/ClientAPI/Embedded/persistent_connect_integration_tests.cs
| 2,084
|
C#
|
using Exilland.GodotCon.CardEffects.Card.Cards;
using Godot;
using GodotOnReady.Attributes;
using System;
namespace Exilland.GodotCon.CardEffects.Card
{
public partial class Card : Control
{
[Signal]
public delegate void StopDrag();
[OnReadyGet] private Label title = null!;
[OnReadyGet] private Label description = null!;
private CardInfo? cardInfo;
private bool draggable;
private bool dragAndDrop;
public CardInfo? CardInfo
{
get => cardInfo;
set
{
cardInfo = value;
InitFromCardInfo();
}
}
public bool Draggable
{
get => draggable;
set
{
draggable = value;
if (!draggable)
{
dragAndDrop = false;
}
MouseFilter = draggable ? MouseFilterEnum.Ignore : MouseFilterEnum.Pass;
SetProcess(draggable);
SetProcessInput(draggable);
}
}
public override void _Input(InputEvent @event)
{
if (Draggable)
{
if (@event is InputEventMouseMotion motion)
if (!dragAndDrop
&& (Input.GetMouseButtonMask() & (int)ButtonList.MaskLeft) != 0
&& motion.Relative.LengthSquared() > 48)
dragAndDrop = true;
if (@event is InputEventMouseButton mouseButton)
{
if (!dragAndDrop && mouseButton.Pressed) dragAndDrop = true;
if (dragAndDrop && !mouseButton.Pressed)
{
EmitSignal(nameof(StopDrag));
}
}
}
}
public override void _Process(float delta)
{
if (Draggable)
{
RectGlobalPosition = RectGlobalPosition
.LinearInterpolate(
GetViewport().GetMousePosition() - RectSize * 0.5f,
delta * 12);
}
}
[OnReady]
private void InitFromCardInfo()
{
if (cardInfo == null || !IsInsideTree())
return;
title.Text = cardInfo.Title;
description.Text = cardInfo.Description;
}
}
}
| 27.444444
| 88
| 0.47085
|
[
"MIT"
] |
Exilland/GodotCon2021-CardEffectsExample
|
01 - SceneBased/Card/Card.cs
| 2,470
|
C#
|
using System;
using System.Collections.Generic;
using JSIL;
public static class Program {
public static void Main (string[] args) {
var fn = Builtins.CreateNamedFunction<Func<int, int>>(
"Test", new[] { "argInt" },
@"return argInt + closureInt;",
new {
closureInt = 2
}
);
if (fn == null)
Console.WriteLine("fn == null");
else
Console.WriteLine(fn(1));
}
}
| 24.35
| 62
| 0.507187
|
[
"MIT"
] |
RedpointGames/JSIL
|
Tests/SpecialTestCases/CreateNamedFunction.cs
| 487
|
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("ClientManagement.Backend.Logic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ClientManagement.Backend.Logic")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c47eea4c-2abc-453e-a27e-364525fad26d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.72973
| 84
| 0.748779
|
[
"MIT"
] |
RevProject-1/Logic
|
ClientManagement.Backend/ClientManagement.Backend.Logic/Properties/AssemblyInfo.cs
| 1,436
|
C#
|
using System;
using NHapi.Base.Model;
using NHapi.Base.Log;
using NHapi.Base;
using NHapi.Base.Model.Primitive;
namespace NHapi.Model.V281.Datatype
{
///<summary>
/// <p>The HL7 DDI (Daily Deductible Information) data type. Consists of the following components: </p><ol>
/// <li>Delay Days (NM)</li>
/// <li>Monetary Amount (MO)</li>
/// <li>Number of Days (NM)</li>
/// </ol>
///</summary>
[Serializable]
public class DDI : AbstractType, IComposite{
private IType[] data;
///<summary>
/// Creates a DDI.
/// <param name="message">The Message to which this Type belongs</param>
///</summary>
public DDI(IMessage message) : this(message, null){}
///<summary>
/// Creates a DDI.
/// <param name="message">The Message to which this Type belongs</param>
/// <param name="description">The description of this type</param>
///</summary>
public DDI(IMessage message, string description) : base(message, description){
data = new IType[3];
data[0] = new NM(message,"Delay Days");
data[1] = new MO(message,"Monetary Amount");
data[2] = new NM(message,"Number of Days");
}
///<summary>
/// Returns an array containing the data elements.
///</summary>
public IType[] Components
{
get{
return this.data;
}
}
///<summary>
/// Returns an individual data component.
/// @throws DataTypeException if the given element number is out of range.
///<param name="index">The index item to get (zero based)</param>
///<returns>The data component (as a type) at the requested number (ordinal)</returns>
///</summary>
public IType this[int index] {
get{
try {
return this.data[index];
} catch (System.ArgumentOutOfRangeException) {
throw new DataTypeException("Element " + index + " doesn't exist in 3 element DDI composite");
}
}
}
///<summary>
/// Returns Delay Days (component #0). This is a convenience method that saves you from
/// casting and handling an exception.
///</summary>
public NM DelayDays {
get{
NM ret = null;
try {
ret = (NM)this[0];
} catch (DataTypeException e) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem accessing known data type component - this is a bug.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns Monetary Amount (component #1). This is a convenience method that saves you from
/// casting and handling an exception.
///</summary>
public MO MonetaryAmount {
get{
MO ret = null;
try {
ret = (MO)this[1];
} catch (DataTypeException e) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem accessing known data type component - this is a bug.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns Number of Days (component #2). This is a convenience method that saves you from
/// casting and handling an exception.
///</summary>
public NM NumberOfDays {
get{
NM ret = null;
try {
ret = (NM)this[2];
} catch (DataTypeException e) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem accessing known data type component - this is a bug.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
}}
| 28.646552
| 133
| 0.663256
|
[
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] |
AMCN41R/nHapi
|
src/NHapi.Model.V281/Datatype/DDI.cs
| 3,323
|
C#
|
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVORVOQuadtreeWrapWrapWrapWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVORVOQuadtreeWrapWrapWrap);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0);
Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVORVOQuadtreeWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVORVOQuadtreeWrapWrapWrap();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVORVOQuadtreeWrapWrapWrap constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m___Register_xlua_st_(RealStatePtr L)
{
try {
{
System.IntPtr _L = LuaAPI.lua_touserdata(L, 1);
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVORVOQuadtreeWrapWrapWrap.__Register( _L );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
}
}
| 26.081818
| 197
| 0.598815
|
[
"MIT"
] |
zxsean/DCET
|
Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVORVOQuadtreeWrapWrapWrapWrap.cs
| 2,871
|
C#
|
namespace SmartHouse.Infrastructure.Data.Helpers
{
public class RedisSettings
{
public string Connection { get; set; }
public int DatabaseId { get; set; }
public string Password { get; set; }
}
}
| 25.777778
| 49
| 0.633621
|
[
"MIT"
] |
JeanRasin/SmartHouse
|
SmartHouse.Infrastructure.Data/Helpers/RedisSettings.cs
| 234
|
C#
|
// Generated class v2.14.0.0, can be modified
namespace NHtmlUnit.Svg
{
public partial class SvgGroup
{
}
}
| 11.818182
| 46
| 0.615385
|
[
"Apache-2.0"
] |
HtmlUnit/NHtmlUnit
|
app/NHtmlUnit/NonGenerated/Svg/SvgGroup.cs
| 130
|
C#
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.ServiceFabric.Client.Http.Serialization
{
using System;
using System.Collections.Generic;
using Microsoft.ServiceFabric.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Converter for <see cref="RepairTaskUpdateHealthPolicyDescription" />.
/// </summary>
internal class RepairTaskUpdateHealthPolicyDescriptionConverter
{
/// <summary>
/// Deserializes the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from.</param>
/// <returns>The object Value.</returns>
internal static RepairTaskUpdateHealthPolicyDescription Deserialize(JsonReader reader)
{
return reader.Deserialize(GetFromJsonProperties);
}
/// <summary>
/// Gets the object from Json properties.
/// </summary>
/// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from, reader must be placed at first property.</param>
/// <returns>The object Value.</returns>
internal static RepairTaskUpdateHealthPolicyDescription GetFromJsonProperties(JsonReader reader)
{
var taskId = default(string);
var version = default(string);
var performPreparingHealthCheck = default(bool?);
var performRestoringHealthCheck = default(bool?);
do
{
var propName = reader.ReadPropertyName();
if (string.Compare("TaskId", propName, StringComparison.Ordinal) == 0)
{
taskId = reader.ReadValueAsString();
}
else if (string.Compare("Version", propName, StringComparison.Ordinal) == 0)
{
version = reader.ReadValueAsString();
}
else if (string.Compare("PerformPreparingHealthCheck", propName, StringComparison.Ordinal) == 0)
{
performPreparingHealthCheck = reader.ReadValueAsBool();
}
else if (string.Compare("PerformRestoringHealthCheck", propName, StringComparison.Ordinal) == 0)
{
performRestoringHealthCheck = reader.ReadValueAsBool();
}
else
{
reader.SkipPropertyValue();
}
}
while (reader.TokenType != JsonToken.EndObject);
return new RepairTaskUpdateHealthPolicyDescription(
taskId: taskId,
version: version,
performPreparingHealthCheck: performPreparingHealthCheck,
performRestoringHealthCheck: performRestoringHealthCheck);
}
/// <summary>
/// Serializes the object to JSON.
/// </summary>
/// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param>
/// <param name="obj">The object to serialize to JSON.</param>
internal static void Serialize(JsonWriter writer, RepairTaskUpdateHealthPolicyDescription obj)
{
// Required properties are always serialized, optional properties are serialized when not null.
writer.WriteStartObject();
writer.WriteProperty(obj.TaskId, "TaskId", JsonWriterExtensions.WriteStringValue);
if (obj.Version != null)
{
writer.WriteProperty(obj.Version, "Version", JsonWriterExtensions.WriteStringValue);
}
if (obj.PerformPreparingHealthCheck != null)
{
writer.WriteProperty(obj.PerformPreparingHealthCheck, "PerformPreparingHealthCheck", JsonWriterExtensions.WriteBoolValue);
}
if (obj.PerformRestoringHealthCheck != null)
{
writer.WriteProperty(obj.PerformRestoringHealthCheck, "PerformRestoringHealthCheck", JsonWriterExtensions.WriteBoolValue);
}
writer.WriteEndObject();
}
}
}
| 42.883495
| 144
| 0.587276
|
[
"MIT"
] |
aL3891/service-fabric-client-dotnet
|
src/Microsoft.ServiceFabric.Client.Http/Serialization/RepairTaskUpdateHealthPolicyDescriptionConverter.cs
| 4,417
|
C#
|
#if !NOSOCKET
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NBitcoin.Protocol
{
public interface MessageListener<in T>
{
void PushMessage(T message);
}
public class NullMessageListener<T> : MessageListener<T>
{
#region MessageListener<T> Members
public void PushMessage(T message)
{
}
#endregion
}
public class NewThreadMessageListener<T> : MessageListener<T>
{
readonly Action<T> _Process;
public NewThreadMessageListener(Action<T> process)
{
if(process == null)
throw new ArgumentNullException(nameof(process));
_Process = process;
}
#region MessageListener<T> Members
public void PushMessage(T message)
{
if(message != null)
Task.Factory.StartNew(() =>
{
try
{
_Process(message);
}
catch(Exception ex)
{
NodeServerTrace.Error("Unexpected expected during message loop", ex);
}
});
}
#endregion
}
public class EventLoopMessageListener<T> : MessageListener<T>, IDisposable
{
public EventLoopMessageListener(Action<T> processMessage)
{
new Thread(new ThreadStart(() =>
{
try
{
while(!cancellationSource.IsCancellationRequested)
{
var message = _MessageQueue.Take(cancellationSource.Token);
if(message != null)
{
try
{
processMessage(message);
}
catch(Exception ex)
{
NodeServerTrace.Error("Unexpected expected during message loop", ex);
}
}
}
}
catch(OperationCanceledException)
{
}
})).Start();
}
BlockingCollection<T> _MessageQueue = new BlockingCollection<T>(new ConcurrentQueue<T>());
public BlockingCollection<T> MessageQueue
{
get
{
return _MessageQueue;
}
}
#region MessageListener Members
public void PushMessage(T message)
{
_MessageQueue.Add(message);
}
#endregion
#region IDisposable Members
CancellationTokenSource cancellationSource = new CancellationTokenSource();
public void Dispose()
{
if(cancellationSource.IsCancellationRequested)
return;
cancellationSource.Cancel();
}
#endregion
}
public class PollMessageListener<T> : MessageListener<T>
{
BlockingCollection<T> _MessageQueue = new BlockingCollection<T>(new ConcurrentQueue<T>());
public BlockingCollection<T> MessageQueue
{
get
{
return _MessageQueue;
}
}
public virtual T ReceiveMessage(CancellationToken cancellationToken = default(CancellationToken))
{
return MessageQueue.Take(cancellationToken);
}
#region MessageListener Members
public virtual void PushMessage(T message)
{
_MessageQueue.Add(message);
}
#endregion
}
}
#endif
| 20.006757
| 100
| 0.651469
|
[
"MIT"
] |
Ilchuk-Mihail/NBitcoin
|
NBitcoin/Protocol/MessageListener.cs
| 2,963
|
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities.Gltf.Schema.Extensions;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities.Gltf.Schema
{
[Serializable]
public class GltfObject : GltfProperty
{
#region Serialized Fields
/// <summary>
/// Names of glTF extensions used somewhere in this asset.
/// </summary>
public string[] extensionsUsed;
/// <summary>
/// Names of glTF extensions required to properly load this asset.
/// </summary>
public string[] extensionsRequired;
/// <summary>
/// An array of accessors. An accessor is a typed view into a bufferView.
/// </summary>
public GltfAccessor[] accessors;
/// <summary>
/// An array of keyframe animations.
/// </summary>
public GltfAnimation[] animations;
/// <summary>
/// Metadata about the glTF asset.
/// </summary>
public GltfAssetInfo asset;
/// <summary>
/// An array of buffers. A buffer points to binary geometry, animation, or skins.
/// </summary>
public GltfBuffer[] buffers;
/// <summary>
/// An array of bufferViews.
/// A bufferView is a view into a buffer generally representing a subset of the buffer.
/// </summary>
public GltfBufferView[] bufferViews;
/// <summary>
/// An array of cameras. A camera defines a projection matrix.
/// </summary>
public GltfCamera[] cameras;
/// <summary>
/// An array of images. An image defines data used to create a texture.
/// </summary>
public GltfImage[] images;
/// <summary>
/// An array of materials. A material defines the appearance of a primitive.
/// </summary>
public GltfMaterial[] materials;
/// <summary>
/// An array of meshes. A mesh is a set of primitives to be rendered.
/// </summary>
public GltfMesh[] meshes;
/// <summary>
/// An array of nodes.
/// </summary>
public GltfNode[] nodes;
/// <summary>
/// An array of samplers. A sampler contains properties for texture filtering and wrapping modes.
/// </summary>
public GltfSampler[] samplers;
/// <summary>
/// The index of the default scene.
/// </summary>
public int scene;
/// <summary>
/// An array of scenes.
/// </summary>
public GltfScene[] scenes;
/// <summary>
/// An array of skins. A skin is defined by joints and matrices.
/// </summary>
public GltfSkin[] skins;
/// <summary>
/// An array of textures.
/// </summary>
public GltfTexture[] textures;
#endregion Serialized Fields
/// <summary>
/// The name of the gltf Object.
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// The absolute path to the glTF Object on disk.
/// </summary>
public string Uri { get; internal set; }
/// <summary>
/// The <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> reference for the gltf Object.
/// </summary>
public GameObject GameObjectReference { get; internal set; }
/// <summary>
/// The list of registered glTF extensions found for this object.
/// </summary>
public List<GltfExtension> RegisteredExtensions { get; internal set; } = new List<GltfExtension>();
/// <summary>
/// Flag for setting object load behavior.
/// Importers should run on the main thread; all other loading scenarios should likely use the background thread
/// </summary>
internal bool UseBackgroundThread { get; set; } = true;
/// <summary>
/// Get an accessor from an accessor index
/// </summary>
public GltfAccessor GetAccessor(int index)
{
if (index < 0) return null;
var accessor = accessors[index];
accessor.BufferView = bufferViews[accessor.bufferView];
accessor.BufferView.Buffer = buffers[accessor.BufferView.buffer];
return accessor;
}
}
}
| 32.208333
| 133
| 0.557999
|
[
"MIT"
] |
HyperLethalVector/ProjectEsky-UnityIntegration
|
Assets/MRTK/Core/Utilities/Gltf/Schema/GltfObject.cs
| 4,640
|
C#
|
using System;
using System.Threading.Tasks;
using System.Web.Http;
using OpenInvoicePeru.Comun.Dto.Intercambio;
using OpenInvoicePeru.Firmado;
using OpenInvoicePeru.Servicio;
using Swashbuckle.Swagger.Annotations;
namespace OpenInvoicePeru.WebApi.Controllers
{
/// <inheritdoc />
public class EnviarResumenController : ApiController
{
private readonly ISerializador _serializador;
private readonly IServicioSunatDocumentos _servicioSunatDocumentos;
/// <inheritdoc />
public EnviarResumenController(ISerializador serializador, IServicioSunatDocumentos servicioSunatDocumentos)
{
_serializador = serializador;
_servicioSunatDocumentos = servicioSunatDocumentos;
}
/// <summary>
/// Envia el Resumen Diario/Comunicacion de Baja a SUNAT
/// </summary>
[HttpPost]
[SwaggerResponse(200, "OK", typeof(EnviarResumenResponse))]
[SwaggerResponse(400, "Bad Request", typeof(string))]
[SwaggerResponse(209, "Conflicts", typeof(string))]
public async Task<IHttpActionResult> Post([FromBody]EnviarDocumentoRequest request)
{
var response = new EnviarResumenResponse();
var nombreArchivo = $"{request.Ruc}-{request.IdDocumento}";
try
{
var tramaZip = await _serializador.GenerarZip(request.TramaXmlFirmado, nombreArchivo);
_servicioSunatDocumentos.Inicializar(new ParametrosConexion
{
Ruc = request.Ruc,
UserName = request.UsuarioSol,
Password = request.ClaveSol,
EndPointUrl = request.EndPointUrl
});
var resultado = _servicioSunatDocumentos.EnviarResumen(new DocumentoSunat
{
NombreArchivo = $"{nombreArchivo}.zip",
TramaXml = tramaZip
});
if (resultado.Exito)
{
response.NroTicket = resultado.NumeroTicket;
response.Exito = true;
response.NombreArchivo = nombreArchivo;
}
else
{
response.MensajeError = resultado.MensajeError;
response.Exito = false;
}
}
catch (Exception ex)
{
response.MensajeError = ex.Message;
response.Pila = ex.StackTrace;
response.Exito = false;
}
return Ok(response);
}
}
}
| 35.74026
| 117
| 0.550872
|
[
"Apache-2.0"
] |
cibernav/openinvoiceperu-1
|
OpenInvoicePeru/OpenInvoicePeru.WebApi/Controllers/EnviarResumenController.cs
| 2,754
|
C#
|
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
using Stride.Core;
using Stride.Core.Shaders.Ast;
namespace Stride.Shaders.Parser.Analysis
{
[DataContract]
internal class StatementNodeCouple
{
public Statement Statement;
public Node Node;
public StatementNodeCouple() : this(null, null) { }
public StatementNodeCouple(Statement statement, Node node)
{
Statement = statement;
Node = node;
}
}
}
| 29.076923
| 81
| 0.677249
|
[
"MIT"
] |
Ethereal77/stride
|
sources/engine/Stride.Shaders.Parser/Analysis/StatementNodeCouple.cs
| 756
|
C#
|
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XamarinChromecast
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
}
| 15.724138
| 42
| 0.524123
|
[
"MIT"
] |
jorgediegocrespo/XamarinChromecast
|
XamarinChromecast/XamarinChromecast/XamarinChromecast/App.xaml.cs
| 458
|
C#
|
////////////////////////////////////////////////////////////////////////////////
//EF Core Provider for LCPI OLE DB.
// IBProvider and Contributors. 27.04.2019.
using System;
using System.Diagnostics;
using System.Linq.Expressions;
namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Methods.Translators{
////////////////////////////////////////////////////////////////////////////////
//using
using Structure_TypeCache
=Structure.Structure_TypeCache;
using Structure_MethodIdCache
=Structure.Structure_MethodIdCache;
using Structure_MethodInfoCache
=Structure.Structure_MethodInfoCache;
////////////////////////////////////////////////////////////////////////////////
//class ETranslator__DbMath__std__Abs__NullableSByte
sealed class ETranslator__DbMath__std__Abs__NullableSByte
:Root.Query.Local.LcpiOleDb__LocalEval_MethodCallTranslator
{
public static readonly Root.Query.Local.LcpiOleDb__LocalEval_MethodCallTranslator
Instance
=new ETranslator__DbMath__std__Abs__NullableSByte();
//-----------------------------------------------------------------------
private ETranslator__DbMath__std__Abs__NullableSByte()
:base(Structure_MethodIdCache.MethodIdOf__DbMath__std__Abs__NullableSByte)
{
}//ETranslator__DbMath__std__Abs__NullableSByte
//interface -------------------------------------------------------------
public override Expression Translate(in tagOpData opData)
{
Debug.Assert(!Object.ReferenceEquals(opData.MethodId,null));
Debug.Assert(opData.MethodId==Structure_MethodInfoCache.MethodInfoOf__DbMath__std__Abs__NullableSByte);
//----------------------------------------
Debug.Assert(Object.ReferenceEquals(opData.CallObject,null));
Debug.Assert(!Object.ReferenceEquals(opData.Arguments,null));
Debug.Assert(opData.Arguments.Count==1);
Debug.Assert(!Object.ReferenceEquals(opData.Arguments[0],null));
Debug.Assert(opData.Arguments[0].Type==Structure_TypeCache.TypeOf__System_NullableSByte);
//----------------------------------------
var node_Arg0
=opData.Arguments[0];
Debug.Assert(!Object.ReferenceEquals(node_Arg0,null));
Debug.Assert(!Object.ReferenceEquals(node_Arg0.Type,null));
Debug.Assert(node_Arg0.Type==Structure_TypeCache.TypeOf__System_NullableSByte);
//----------------------------------------
var r
=Code.Method_Code__Math__Abs__NullableSByte.CreateCallExpression
(node_Arg0);
Debug.Assert(!Object.ReferenceEquals(r,null));
return r;
}//Translate
};//class ETranslator__DbMath__std__Abs__NullableSByte
////////////////////////////////////////////////////////////////////////////////
}//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Methods.Translators
| 37.333333
| 121
| 0.643929
|
[
"MIT"
] |
ibprovider/Lcpi.EFCore.LcpiOleDb
|
Code/Provider/Source/Basement/EF/Root/Query/Local/Expressions/Methods/Translators/DbMath/ETranslator__DbMath__std__Abs__NullableSByte.cs
| 2,802
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookTowards : MonoBehaviour,IMove
{
[SerializeField] private Transform _targetTransform;
[SerializeField] private bool isAllTimeUpdate = false;
private bool _canMove = false;
public void Setup(GameObject target,float distance)
{
}
public void Run()
{
_canMove = true;
Look();
}
public void SetTargetObject(GameObject targetObject)
{
this._targetTransform = targetObject.transform;
}
public void SetAngle(float angle)
{
}
private void Update()
{
if (isAllTimeUpdate && _canMove == true)
Look();
}
private void Look()
{
if(_targetTransform != null)
{
Vector3 dir = _targetTransform.position - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
public void StopMovement()
{
_canMove = false;
}
}
| 21.96
| 79
| 0.618397
|
[
"MIT"
] |
tanvirfiji/Circular-Shoot
|
Assets/Script/Enemy/LookTowards.cs
| 1,100
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Signum.Engine.Authorization;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using Signum.Entities.Profiler;
using System.Drawing;
using Signum.Entities.Reflection;
using System.Xml.Linq;
using System.IO;
using Signum.React.Files;
using Signum.React.Filters;
namespace Signum.React.Profiler
{
[ValidateModelFilter]
public class ProfilerHeavyController : ControllerBase
{
[HttpPost("api/profilerHeavy/clear")]
public void Clear()
{
ProfilerPermission.ViewHeavyProfiler.AssertAuthorized();
HeavyProfiler.Clean();
}
[HttpPost("api/profilerHeavy/setEnabled/{isEnabled}")]
public void SetEnabled(bool isEnabled)
{
ProfilerPermission.ViewHeavyProfiler.AssertAuthorized();
HeavyProfiler.Enabled = isEnabled;
}
[HttpGet("api/profilerHeavy/isEnabled")]
public bool IsEnabled()
{
ProfilerPermission.ViewHeavyProfiler.AssertAuthorized();
return HeavyProfiler.Enabled;
}
[HttpGet("api/profilerHeavy/entries")]
public List<HeavyProfofilerEntryTS> Entries()
{
ProfilerPermission.ViewHeavyProfiler.AssertAuthorized();
var now = PerfCounter.Ticks;
lock (HeavyProfiler.Entries)
return HeavyProfiler.Entries.Select(e => new HeavyProfofilerEntryTS(e, false, now)).ToList();
}
[HttpGet("api/profilerHeavy/details/{fullIndex}")]
public List<HeavyProfofilerEntryTS> Details(string fullIndex)
{
ProfilerPermission.ViewHeavyProfiler.AssertAuthorized();
var entry = HeavyProfiler.Find(fullIndex);
var result = new List<HeavyProfofilerEntryTS>();
var now = PerfCounter.Ticks;
HeavyProfofilerEntryTS.Fill(result, entry, 0, now);
return result;
}
[HttpGet("api/profilerHeavy/stackTrace/{fullIndex}")]
public List<StackTraceTS>? StackTrace(string fullIndex)
{
ProfilerPermission.ViewHeavyProfiler.AssertAuthorized();
var e = HeavyProfiler.Find(fullIndex);
if (e == null)
return null;
if (e.ExternalStackTrace != null)
return (from est in e.ExternalStackTrace
select new StackTraceTS
{
Method = est.MethodName,
Color = est.Namespace == null ? null : ColorExtensions.ToHtmlColor(est.Namespace.Split('.').Take(2).ToString(".").GetHashCode()),
Type = est.Type,
Namespace = est.Namespace!,
FileName = est.FileName,
LineNumber = est.LineNumber ?? 0
}).ToList();
if (e.StackTrace != null)
return (from i in 0.To(e.StackTrace.FrameCount)
let sf = e.StackTrace!.GetFrame(i)
let mi = sf.GetMethod()
let t = mi.DeclaringType
select new StackTraceTS
{
Namespace = t?.Namespace!,
Color = t == null ? null : ColorExtensions.ToHtmlColor(t.Assembly.FullName!.GetHashCode()),
Type = t?.TypeName()!,
Method = mi.Name,
FileName = sf.GetFileName()!,
LineNumber = sf.GetFileLineNumber(),
}).ToList();
return null;
}
[HttpGet("api/profilerHeavy/download")]
public FileStreamResult Download(string? indices = null)
{
XDocument doc = indices == null ?
HeavyProfiler.ExportXml() :
HeavyProfiler.Find(indices).ExportXmlDocument(false);
using (MemoryStream ms = new MemoryStream())
{
doc.Save(ms);
string fileName = "Profile-{0}.xml".FormatWith(DateTime.Now.ToString("o").Replace(":", "."));
return FilesController.GetFileStreamResult(new MemoryStream(ms.ToArray()), fileName);
}
}
[HttpPost("api/profilerHeavy/upload")]
public void Upload([Required, FromBody]FileUpload file)
{
using (MemoryStream sr = new MemoryStream(file.content))
{
var doc = XDocument.Load(sr);
HeavyProfiler.ImportXml(doc, rebaseTime: true);
}
}
public class FileUpload
{
public string fileName;
public byte[] content;
}
private static string GetColor(string role)
{
if (role == null)
return Color.Gray.ToHtml();
if (RoleColors.TryGetValue(role, out Color color))
return color.ToHtml();
return ColorExtensions.ToHtmlColor(StringHashEncoder.GetHashCode32(role));
}
public static Dictionary<string, Color> RoleColors = new Dictionary<string, Color>
{
{ "SQL", Color.Gold },
{ "DB", Color.MediumSlateBlue },
{ "LINQ", Color.Violet },
{ "MvcRequest", Color.LimeGreen },
{ "MvcResult", Color.SeaGreen }
};
public class HeavyProfofilerEntryTS
{
public long BeforeStart;
public long Start;
public long End;
public string Elapsed;
public string Role;
public string Color;
public int Depth;
public int AsyncDepth;
public string? AdditionalData;
public string FullIndex;
public bool IsFinished;
public HeavyProfofilerEntryTS(HeavyProfilerEntry e, bool fullAditionalData, long now)
{
BeforeStart = e.BeforeStart;
Start = e.Start;
End = e.End ?? now;
Elapsed = e.ElapsedToString();
IsFinished = e.End.HasValue;
Role = e.Role;
Color = GetColor(e.Role);
Depth = e.Depth;
FullIndex = e.FullIndex();
AdditionalData = fullAditionalData ? e.AdditionalData : e.AdditionalDataPreview();
}
internal static int Fill(List<HeavyProfofilerEntryTS> result, HeavyProfilerEntry entry, int asyncDepth, long now)
{
result.Add(new HeavyProfofilerEntryTS(entry, true, now) { AsyncDepth = asyncDepth });
if (entry.Entries == null)
return asyncDepth;
Dictionary<HeavyProfilerEntry, int> newDepths = new Dictionary<HeavyProfilerEntry, int>();
for (int i = 0; i < entry.Entries.Count; i++)
{
var e = entry.Entries[i];
var maxAsyncDepth = newDepths.Where(kvp => kvp.Key.Overlaps(e)).Max(a => (int?)a.Value);
var newAsyncDepth = Fill(result, e, maxAsyncDepth.HasValue ? maxAsyncDepth.Value + 1 : asyncDepth + 1, now);
newDepths.Add(e, newAsyncDepth);
}
return newDepths.Values.Max();
}
}
public class StackTraceTS
{
public string? Color;
public string Namespace;
public string? Type;
public string Method;
public string? FileName;
public int? LineNumber;
}
}
}
| 34.766234
| 158
| 0.529324
|
[
"MIT"
] |
AlejandroCano/extensions
|
Signum.React.Extensions/Profiler/ProfilerHeavyController.cs
| 8,031
|
C#
|
// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string AuthToken = "your_auth_token";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var ipAccessControlListMapping = twilio.CreateIpAccessControlListMapping("SD32a3c49700934481addd5ce1659f04d2", "AL32a3c49700934481addd5ce1659f04d2");
Console.WriteLine(ipAccessControlListMapping.Sid);
}
}
| 34.444444
| 153
| 0.769355
|
[
"MIT"
] |
PatNeedham/api-snippets
|
rest/sip-in/associate-control-domain/associate-control-domain.4.x.cs
| 620
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 4.0.1
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace QuantLib {
public class SARCurrency : Currency {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
internal SARCurrency(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NQuantLibcPINVOKE.SARCurrency_SWIGUpcast(cPtr), cMemoryOwn) {
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SARCurrency obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
protected override void Dispose(bool disposing) {
lock(this) {
if (swigCPtr.Handle != global::System.IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
NQuantLibcPINVOKE.delete_SARCurrency(swigCPtr);
}
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
base.Dispose(disposing);
}
}
public SARCurrency() : this(NQuantLibcPINVOKE.new_SARCurrency(), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
}
}
| 37.022727
| 137
| 0.631062
|
[
"Apache-2.0"
] |
andrew-stakiwicz-r3/financial_derivatives_demo
|
quantlib_swig_bindings/CSharp/csharp/SARCurrency.cs
| 1,629
|
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.IoT.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoT.Model.Internal.MarshallTransformations
{
/// <summary>
/// SetDefaultPolicyVersion Request Marshaller
/// </summary>
public class SetDefaultPolicyVersionRequestMarshaller : IMarshaller<IRequest, SetDefaultPolicyVersionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((SetDefaultPolicyVersionRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(SetDefaultPolicyVersionRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.IoT");
request.Headers["Content-Type"] = "application/x-amz-json-";
request.HttpMethod = "PATCH";
string uriResourcePath = "/policies/{policyName}/version/{policyVersionId}";
if (!publicRequest.IsSetPolicyName())
throw new AmazonIoTException("Request object does not have required field PolicyName set");
uriResourcePath = uriResourcePath.Replace("{policyName}", StringUtils.FromString(publicRequest.PolicyName));
if (!publicRequest.IsSetPolicyVersionId())
throw new AmazonIoTException("Request object does not have required field PolicyVersionId set");
uriResourcePath = uriResourcePath.Replace("{policyVersionId}", StringUtils.FromString(publicRequest.PolicyVersionId));
request.ResourcePath = uriResourcePath;
return request;
}
private static SetDefaultPolicyVersionRequestMarshaller _instance = new SetDefaultPolicyVersionRequestMarshaller();
internal static SetDefaultPolicyVersionRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static SetDefaultPolicyVersionRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 37.901099
| 161
| 0.672369
|
[
"Apache-2.0"
] |
GitGaby/aws-sdk-net
|
sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/SetDefaultPolicyVersionRequestMarshaller.cs
| 3,449
|
C#
|
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Types.Enums;
namespace CPNewbieBot
{
internal class Program
{
static ITelegramBotClient TelegramBotClient;
static void Main(string[] args)
{
MainAsync(args).Wait();
}
static async Task MainAsync(string[] args)
{
var token = File.ReadAllText("token.txt");
TelegramBotClient = new TelegramBotClient(token);
var me = await TelegramBotClient.GetMeAsync();
Console.WriteLine("Telegram bot started!");
TelegramBotClient.OnMessage += BotClient_OnMessage;
TelegramBotClient.StartReceiving();
while (true) Thread.Sleep(int.MaxValue);
}
static async void BotClient_OnMessage(object sender, MessageEventArgs e)
{
var msg = e.Message;
var text = msg.Text.Trim();
var responder = msg.From?.Username ?? "user";
const string TelegramBotName = "@cpnewbiebot", TelegramBotCommand = "/search";
// First type of message: reply referring me
if (msg.ReplyToMessage != null && (text.Contains(TelegramBotName) || text.Contains(TelegramBotCommand)))
{
var finder = new DefinitionFinder();
await finder.Parse(msg.ReplyToMessage.Text, responder);
await TelegramBotClient.SendTextMessageAsync(msg.Chat, finder.Message, ParseMode.Markdown,
replyToMessageId: msg.MessageId);
}
// Second type of message: manual search
else if (text.StartsWith(TelegramBotCommand))
{
var finder = new DefinitionFinder();
await finder.Parse(text.Substring(TelegramBotCommand.Length), responder);
await TelegramBotClient.SendTextMessageAsync(msg.Chat, finder.Message, ParseMode.Markdown,
replyToMessageId: msg.MessageId);
}
// "Fallback message": referring me but no reply
else if (msg.ReplyToMessage == null && text.Contains(TelegramBotName))
{
var defaultMessage = $"Hi, {responder}! How could I help you today?\n\n" +
$"You can search for unknown terms in a message by replying to it with the command {TelegramBotCommand} or by " +
$"tagging me on the reply ({TelegramBotName}).\nYou can also search for a specific keyword by typing " +
$"{TelegramBotCommand} [keyword]. One is glad to be of service!";
await TelegramBotClient.SendTextMessageAsync(msg.Chat, defaultMessage, replyToMessageId: msg.MessageId);
}
}
}
}
| 41.101449
| 133
| 0.610014
|
[
"MIT"
] |
JoaoBaptMG/CPNewbieBot
|
CPNewbieBot/Program.cs
| 2,838
|
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 Microsoft.ML.Probabilistic.Learners.Tests
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
/// <summary>
/// A set of functions to perform equality comparison of complex types.
/// </summary>
internal static class Comparers
{
/// <summary>
/// Checks if two dictionaries are equal.
/// </summary>
/// <typeparam name="TKey">The type of the key in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the value in the dictionary.</typeparam>
/// <param name="dictionary1">The first dictionary.</param>
/// <param name="dictionary2">The second dictionary.</param>
/// <param name="valueComparer">The comparer of dictionary values.</param>
/// <returns>True if the given dictionaries are equal, false otherwise.</returns>
public static bool Dictionary<TKey, TValue>(
IDictionary<TKey, TValue> dictionary1,
IDictionary<TKey, TValue> dictionary2,
Func<TValue, TValue, bool> valueComparer)
{
Debug.Assert(dictionary1 != null && dictionary2 != null, "Valid dictionaries should be provided.");
if (dictionary1.Count != dictionary2.Count)
{
return false;
}
return dictionary1.Keys.All(
key => dictionary2.ContainsKey(key) && valueComparer(dictionary1[key], dictionary2[key]));
}
/// <summary>
/// Checks if two sets are equal.
/// </summary>
/// <typeparam name="T">The type of set elements.</typeparam>
/// <param name="set1">The first set.</param>
/// <param name="set2">The second set.</param>
/// <returns>True if the given sets are equal, false otherwise.</returns>
public static bool Set<T>(ISet<T> set1, ISet<T> set2)
{
Debug.Assert(set1 != null && set2 != null, "Valid sets should be provided.");
if (set1.Count != set2.Count)
{
return false;
}
return set1.Any(v => set2.Contains(v));
}
/// <summary>
/// Checks if two collections are equal, that is, contain the same elements in the same order.
/// </summary>
/// <typeparam name="T">The type of collection elements.</typeparam>
/// <param name="collection1">The first collection.</param>
/// <param name="collection2">The second collection.</param>
/// <returns>True if the given collections are equal, false otherwise.</returns>
public static bool Collection<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
Debug.Assert(collection1 != null && collection2 != null, "Valid collections should be provided.");
return collection1.SequenceEqual(collection2);
}
/// <summary>
/// Checks if two collections are equivalent, that is, contain the same elements.
/// </summary>
/// <typeparam name="T">The type of collection elements.</typeparam>
/// <param name="collection1">The first collection.</param>
/// <param name="collection2">The second collection.</param>
/// <returns>True if the given collections are equivalent, false otherwise.</returns>
public static bool CollectionEquivalence<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
Debug.Assert(collection1 != null && collection2 != null, "Valid collections should be provided.");
ISet<T> set1 = new HashSet<T>(collection1);
ISet<T> set2 = new HashSet<T>(collection2);
return Set(set1, set2);
}
/// <summary>
/// Checks if two values are equal.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="value1">The first value.</param>
/// <param name="value2">The second value.</param>
/// <returns>True if the given values are equal, false otherwise.</returns>
public static bool Generic<T>(T value1, T value2)
{
return object.Equals(value1, value2);
}
}
}
| 42.788462
| 111
| 0.603596
|
[
"MIT"
] |
0xflotus/infer
|
test/Learners/LearnersTests/Comparers.cs
| 4,450
|
C#
|
using System;
using System.Buffers;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using CommandLine;
namespace PortLogger
{
internal static class Program
{
private static async Task Main(string[] args)
{
await Parser.Default.ParseArguments<Config>(args).WithParsedAsync(Run);
}
private static async Task Run(Config config)
{
var sessionId = DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss");
var folder = Path.Combine(config.DestinationFolder, sessionId);
Directory.CreateDirectory(folder);
await ListenAsync(config, sessionId);
}
private static async Task ListenAsync(Config config, string sessionId)
{
TcpListener server = null;
try
{
server = new TcpListener(IPAddress.Any, config.IncomingPort);
server.Start();
var cts = new CancellationTokenSource();
var task = ListenIncomingRequestsAsync(config, server, sessionId, cts.Token);
Console.WriteLine("Press enter to stop.");
Console.ReadLine();
// Notify to stop active connection(s) and wait a small delay.
cts.Cancel();
await Task.Delay(100, CancellationToken.None);
// Stop accepting new connection and make sure the task has completed.
server.Stop();
await task;
}
finally
{
server?.Stop();
}
}
private static async Task ListenIncomingRequestsAsync(
Config config,
TcpListener server,
string sessionId,
CancellationToken ct)
{
var connectionId = 0;
while (true)
{
TcpClient client;
try
{
client = await server.AcceptTcpClientAsync();
}
catch (ObjectDisposedException)
{
break;
}
connectionId++;
// Fire & forget call.
HandleConnectionAsync(client, connectionId, sessionId, config, ct);
}
}
private static async void HandleConnectionAsync(
TcpClient client,
int connectionId,
string sessionId,
Config config,
CancellationToken ct)
{
Console.WriteLine(DateTimeOffset.Now + ": New connection #" + connectionId);
try
{
await using var streamClient = client.GetStream();
using var server = new TcpClient();
await server.ConnectAsync(config.OutgoingHost, config.OutgoingPort);
await using var streamServer = server.GetStream();
await Task.WhenAll(
CopyToAsync(streamClient, streamServer, true, sessionId, connectionId, config, ct),
CopyToAsync(streamServer, streamClient, false, sessionId, connectionId, config, ct)
);
}
catch (OperationCanceledException)
{
// Ignore. We are closing the connection.
}
catch (Exception ex)
{
Console.WriteLine("Fatal exception ignored in HandleConnectionAsync to prevent stopping the app.");
Console.WriteLine(ex);
}
Console.WriteLine(DateTimeOffset.Now + ": Closing connection #" + connectionId);
}
private static async Task CopyToAsync(
Stream origin,
Stream destination,
bool isClient,
string sessionId,
int connectionId,
Config config,
CancellationToken ct)
{
var folder = Path.Combine(config.DestinationFolder, sessionId);
var filename = connectionId + "_" + (isClient ? "client" : "server") + ".txt";
var path = Path.Combine(folder, filename);
const int bufferSize = 1024;
var pool = ArrayPool<byte>.Shared;
var buffer = pool.Rent(bufferSize);
try
{
while (true)
{
var bytesRead = await origin.ReadAsync(buffer, ct);
if (bytesRead == 0)
break;
try
{
await using var stream = new FileStream(path, FileMode.Append);
await stream.WriteAsync(buffer, 0, bytesRead, ct);
}
catch (Exception ex)
{
Console.WriteLine("An error occured when appending to the file: " + path);
Console.WriteLine(ex);
}
await destination.WriteAsync(buffer, 0, bytesRead, ct);
}
}
finally
{
pool.Return(buffer);
}
}
}
}
| 32.70625
| 115
| 0.506784
|
[
"MIT"
] |
doxakis/PortLogger
|
PortLogger/Program.cs
| 5,235
|
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the route53-2013-04-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.Route53.Model
{
/// <summary>
/// No traffic policy instance exists with the specified ID.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class NoSuchTrafficPolicyInstanceException : AmazonRoute53Exception
{
/// <summary>
/// Constructs a new NoSuchTrafficPolicyInstanceException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public NoSuchTrafficPolicyInstanceException(string message)
: base(message) {}
/// <summary>
/// Construct instance of NoSuchTrafficPolicyInstanceException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public NoSuchTrafficPolicyInstanceException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of NoSuchTrafficPolicyInstanceException
/// </summary>
/// <param name="innerException"></param>
public NoSuchTrafficPolicyInstanceException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of NoSuchTrafficPolicyInstanceException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public NoSuchTrafficPolicyInstanceException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of NoSuchTrafficPolicyInstanceException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public NoSuchTrafficPolicyInstanceException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the NoSuchTrafficPolicyInstanceException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected NoSuchTrafficPolicyInstanceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
}
| 48.354839
| 178
| 0.688292
|
[
"Apache-2.0"
] |
DetlefGolze/aws-sdk-net
|
sdk/src/Services/Route53/Generated/Model/NoSuchTrafficPolicyInstanceException.cs
| 5,996
|
C#
|
/*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.
*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com)
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.Buffers
{
using System;
using System.Buffers;
partial class UnpooledUnsafeDirectByteBuffer
{
protected internal sealed override ReadOnlyMemory<byte> _GetReadableMemory(int index, int count)
{
return new ReadOnlyMemory<byte>(_buffer, index, count);
}
protected internal sealed override ReadOnlySpan<byte> _GetReadableSpan(int index, int count)
{
return new ReadOnlySpan<byte>(_buffer, index, count);
}
protected internal sealed override ReadOnlySequence<byte> _GetSequence(int index, int count)
{
return new ReadOnlySequence<byte>(_buffer, index, count);
}
protected internal sealed override Memory<byte> _GetMemory(int index, int count)
{
return new Memory<byte>(_buffer, index, count);
}
protected internal sealed override Span<byte> _GetSpan(int index, int count)
{
return new Span<byte>(_buffer, index, count);
}
}
}
| 35.118644
| 104
| 0.69112
|
[
"MIT"
] |
cuteant/SpanNetty
|
src/DotNetty.Buffers/UnpooledUnsafeDirectByteBuffer.NetStandard.cs
| 2,074
|
C#
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using System.Collections.Generic;
using osuTK;
using osu.Framework.Allocation;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.Comments.Buttons
{
public class ShowMoreRepliesButton : LoadingButton
{
protected override IEnumerable<Drawable> EffectTargets => new[] { text };
private OsuSpriteText text;
public ShowMoreRepliesButton()
{
AutoSizeAxes = Axes.Both;
LoadingAnimationSize = new Vector2(8);
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
IdleColour = colourProvider.Light2;
HoverColour = colourProvider.Light1;
}
protected override Drawable CreateContent() => new Container
{
AutoSizeAxes = Axes.Both,
Child = text = new OsuSpriteText
{
AlwaysPresent = true,
Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold),
Text = CommonStrings.ButtonsShowMore
}
};
protected override void OnLoadStarted() => text.FadeOut(200, Easing.OutQuint);
protected override void OnLoadFinished() => text.FadeIn(200, Easing.OutQuint);
}
}
| 32.215686
| 87
| 0.637858
|
[
"MIT"
] |
CenTdemeern1/osu
|
osu.Game/Overlays/Comments/Buttons/ShowMoreRepliesButton.cs
| 1,595
|
C#
|
namespace CyberCAT.Core.DumpedEnums
{
public enum worldgeometryaverageNormalDetectionHelperQueryStatus
{
Finished = 0,
NoGeometry = 1
}
}
| 16.111111
| 65
| 0.786207
|
[
"MIT"
] |
Deweh/CyberCAT
|
CyberCAT.Core/Enums/Dumped Enums/worldgeometryaverageNormalDetectionHelperQueryStatus.cs
| 145
|
C#
|
using UnrealBuildTool;
public class Test : ModuleRules
{
public Test(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
bUseRTTI = true;
PublicDependencyModuleNames.AddRange
(
new string[]
{
"Core"
}
);
PrivateDependencyModuleNames.AddRange
(
new string[]
{
"Engine",
"GoogleTest",
"VariantManager",
"CoreUObject",
"Application",
"Domain",
}
);
}
}
| 15.78125
| 62
| 0.609901
|
[
"Apache-2.0"
] |
IhnoL/GoogleMockUnreal
|
Plugins/CustomVariantManager/Source/0Test/Test.Build.cs
| 505
|
C#
|
using GutenTag;
namespace GutenTag.Hspi
{
public class Ruby : Tag
{
public Ruby() : base("ruby")
{
}
}
}
| 12.818182
| 36
| 0.496454
|
[
"MIT"
] |
alexdresko/GutenTag.Hspi
|
GutenTag.Hspi/Ruby.cs
| 141
|
C#
|
using EFCore.BulkExtensions.SqlAdapters;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace EFCore.BulkExtensions.SQLAdapters.SQLServer
{
public class SqlOperationsServerAdapter: ISqlOperationsAdapter
{
#region Methods
// Insert
public void Insert<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress)
{
InsertAsync(context, type, entities, tableInfo, progress, CancellationToken.None, isAsync: false).GetAwaiter().GetResult();
}
public async Task InsertAsync<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress, CancellationToken cancellationToken)
{
await InsertAsync(context, type, entities, tableInfo, progress, cancellationToken, isAsync: true).ConfigureAwait(false);
}
// Publish Async and NonAsync are merged into single operation flow with protected method using arg: bool isAsync (keeps code DRY)
// https://docs.microsoft.com/en-us/archive/msdn-magazine/2015/july/async-programming-brownfield-async-development#the-flag-argument-hack
protected async Task InsertAsync<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress, CancellationToken cancellationToken, bool isAsync)
{
tableInfo.CheckToSetIdentityForPreserveOrder(entities);
if (isAsync)
{
await context.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.OpenConnection();
}
var connection = context.GetUnderlyingConnection(tableInfo.BulkConfig);
try
{
var transaction = context.Database.CurrentTransaction;
using var sqlBulkCopy = GetSqlBulkCopy((SqlConnection)connection, transaction, tableInfo.BulkConfig);
bool setColumnMapping = false;
tableInfo.SetSqlBulkCopyConfig(sqlBulkCopy, entities, setColumnMapping, progress);
try
{
var dataTable = GetDataTable(context, type, entities, sqlBulkCopy, tableInfo);
if (isAsync)
{
await sqlBulkCopy.WriteToServerAsync(dataTable, cancellationToken).ConfigureAwait(false);
}
else
{
sqlBulkCopy.WriteToServer(dataTable);
}
}
catch (InvalidOperationException ex)
{
if (ex.Message.Contains(BulkExceptionMessage.ColumnMappingNotMatch))
{
bool tableExist = isAsync ? await tableInfo.CheckTableExistAsync(context, tableInfo, cancellationToken, isAsync: true).ConfigureAwait(false)
: tableInfo.CheckTableExistAsync(context, tableInfo, cancellationToken, isAsync: false).GetAwaiter().GetResult();
if (!tableExist)
{
var sqlCreateTableCopy = SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempTableName, tableInfo);
var sqlDropTable = SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlCreateTableCopy, cancellationToken).ConfigureAwait(false);
await context.Database.ExecuteSqlRawAsync(sqlDropTable, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlCreateTableCopy);
context.Database.ExecuteSqlRaw(sqlDropTable);
}
}
}
throw;
}
}
finally
{
if (isAsync)
{
await context.Database.CloseConnectionAsync().ConfigureAwait(false);
}
else
{
context.Database.CloseConnection();
}
}
if (!tableInfo.CreatedOutputTable)
{
tableInfo.CheckToSetIdentityForPreserveOrder(entities, reset: true);
}
}
// Merge
public void Merge<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, OperationType operationType, Action<decimal> progress) where T : class
{
MergeAsync(context, type, entities, tableInfo, operationType, progress, CancellationToken.None, isAsync: false).GetAwaiter().GetResult();
}
public async Task MergeAsync<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, OperationType operationType, Action<decimal> progress, CancellationToken cancellationToken) where T : class
{
await MergeAsync(context, type, entities, tableInfo, operationType, progress, cancellationToken, isAsync: true).ConfigureAwait(false);
}
protected async Task MergeAsync<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, OperationType operationType, Action<decimal> progress, CancellationToken cancellationToken, bool isAsync) where T : class
{
tableInfo.InsertToTempTable = true;
var dropTempTableIfExists = tableInfo.BulkConfig.UseTempDB;
if (dropTempTableIfExists)
{
var sqlDropTable = SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlDropTable, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlDropTable);
}
}
var sqlCreateTableCopy = SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempTableName, tableInfo);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlCreateTableCopy, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlCreateTableCopy);
}
if (tableInfo.TimeStampColumnName != null)
{
var sqlAddColumn = SqlQueryBuilder.AddColumn(tableInfo.FullTempTableName, tableInfo.TimeStampColumnName, tableInfo.TimeStampOutColumnType);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlAddColumn, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlAddColumn);
}
}
if (tableInfo.CreatedOutputTable)
{
var sqlCreateOutputTableCopy = SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempOutputTableName, tableInfo, true);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlCreateOutputTableCopy, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlCreateOutputTableCopy);
}
if (tableInfo.TimeStampColumnName != null)
{
var sqlAddColumn = SqlQueryBuilder.AddColumn(tableInfo.FullTempOutputTableName, tableInfo.TimeStampColumnName, tableInfo.TimeStampOutColumnType);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlAddColumn, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlAddColumn);
}
}
var sqlAlterTableColumnsToNullable = SqlQueryBuilder.AlterTableColumnsToNullable(tableInfo.FullTempOutputTableName, tableInfo);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlAlterTableColumnsToNullable, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlAlterTableColumnsToNullable);
}
}
bool keepIdentity = tableInfo.BulkConfig.SqlBulkCopyOptions.HasFlag(SqlBulkCopyOptions.KeepIdentity);
try
{
if (isAsync)
{
await InsertAsync(context, type, entities, tableInfo, progress, cancellationToken).ConfigureAwait(false);
}
else
{
Insert(context, type, entities, tableInfo, progress);
}
if (keepIdentity && tableInfo.HasIdentity)
{
var sqlSetIdentityInsertTrue = SqlQueryBuilder.SetIdentityInsert(tableInfo.FullTableName, true);
if (isAsync)
{
await context.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
await context.Database.ExecuteSqlRawAsync(sqlSetIdentityInsertTrue, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.OpenConnection();
context.Database.ExecuteSqlRaw(sqlSetIdentityInsertTrue);
}
}
var sqlMergeTable = SqlQueryBuilder.MergeTable(tableInfo, operationType);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlMergeTable, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlMergeTable);
}
if (tableInfo.CreatedOutputTable)
{
if (isAsync)
{
await tableInfo.LoadOutputDataAsync(context, type, entities, tableInfo, cancellationToken, isAsync: true).ConfigureAwait(false);
}
else
{
tableInfo.LoadOutputDataAsync(context, type, entities, tableInfo, cancellationToken, isAsync: false).GetAwaiter().GetResult();
}
}
}
finally
{
if (!tableInfo.BulkConfig.UseTempDB)
{
if (tableInfo.CreatedOutputTable)
{
var sqlDropOutputTable = SqlQueryBuilder.DropTable(tableInfo.FullTempOutputTableName, tableInfo.BulkConfig.UseTempDB);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlDropOutputTable, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlDropOutputTable);
}
}
var sqlDropTable = SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlDropTable, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlDropTable);
}
}
if (keepIdentity && tableInfo.HasIdentity)
{
var sqlSetIdentityInsertFalse = SqlQueryBuilder.SetIdentityInsert(tableInfo.FullTableName, false);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlSetIdentityInsertFalse, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlSetIdentityInsertFalse);
}
context.Database.CloseConnection();
}
}
}
// Read
public void Read<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress) where T : class
{
ReadAsync(context, type, entities, tableInfo, progress, CancellationToken.None, isAsync: false).GetAwaiter().GetResult();
}
public async Task ReadAsync<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress, CancellationToken cancellationToken) where T : class
{
await ReadAsync(context, type, entities, tableInfo, progress, cancellationToken, isAsync: true).ConfigureAwait(false);
}
protected async Task ReadAsync<T>(DbContext context, Type type, IList<T> entities, TableInfo tableInfo, Action<decimal> progress, CancellationToken cancellationToken, bool isAsync) where T : class
{
Dictionary<string, string> previousPropertyColumnNamesDict = tableInfo.ConfigureBulkReadTableInfo();
var sqlCreateTableCopy = SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempTableName, tableInfo);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlCreateTableCopy, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlCreateTableCopy);
}
try
{
if (isAsync)
{
await InsertAsync(context, type, entities, tableInfo, progress, cancellationToken).ConfigureAwait(false);
}
else
{
InsertAsync(context, type, entities, tableInfo, progress, cancellationToken, isAsync: false).GetAwaiter().GetResult();
}
tableInfo.PropertyColumnNamesDict = tableInfo.OutputPropertyColumnNamesDict;
var sqlSelectJoinTable = SqlQueryBuilder.SelectJoinTable(tableInfo);
tableInfo.PropertyColumnNamesDict = previousPropertyColumnNamesDict;
List<T> existingEntities;
if (typeof(T) == type)
{
Expression<Func<DbContext, IQueryable<T>>> expression = tableInfo.GetQueryExpression<T>(sqlSelectJoinTable, false);
var compiled = EF.CompileQuery(expression); // instead using Compiled queries
existingEntities = compiled(context).ToList();
}
else // TODO: Consider removing
{
Expression<Func<DbContext, IEnumerable>> expression = tableInfo.GetQueryExpression(type, sqlSelectJoinTable, false);
var compiled = EF.CompileQuery(expression); // instead using Compiled queries
existingEntities = compiled(context).Cast<T>().ToList();
}
tableInfo.UpdateReadEntities(type, entities, existingEntities);
}
finally
{
if (!tableInfo.BulkConfig.UseTempDB)
{
var sqlDropTable = SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB);
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlDropTable, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlDropTable);
}
}
}
}
// Truncate
public void Truncate(DbContext context, TableInfo tableInfo)
{
var sqlTruncateTable = SqlQueryBuilder.TruncateTable(tableInfo.FullTableName);
context.Database.ExecuteSqlRaw(sqlTruncateTable);
}
public async Task TruncateAsync(DbContext context, TableInfo tableInfo, CancellationToken cancellationToken)
{
var sqlTruncateTable = SqlQueryBuilder.TruncateTable(tableInfo.FullTableName);
await context.Database.ExecuteSqlRawAsync(sqlTruncateTable, cancellationToken).ConfigureAwait(false);
}
#endregion
#region Connection
private static SqlBulkCopy GetSqlBulkCopy(SqlConnection sqlConnection, IDbContextTransaction transaction, BulkConfig config)
{
var sqlTransaction = transaction == null ? null : (SqlTransaction)transaction.GetUnderlyingTransaction(config);
var sqlBulkCopy = new SqlBulkCopy(sqlConnection, config.SqlBulkCopyOptions, sqlTransaction);
return sqlBulkCopy;
}
#endregion
#region DataTable
/// <summary>
/// Supports <see cref="SqlBulkCopy"/>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <param name="type"></param>
/// <param name="entities"></param>
/// <param name="sqlBulkCopy"></param>
/// <param name="tableInfo"></param>
/// <returns></returns>
internal static DataTable GetDataTable<T>(DbContext context, Type type, IList<T> entities, SqlBulkCopy sqlBulkCopy, TableInfo tableInfo)
{
DataTable dataTable = InnerGetDataTable(context, ref type, entities, tableInfo);
foreach (DataColumn item in dataTable.Columns) //Add mapping
{
sqlBulkCopy.ColumnMappings.Add(item.ColumnName, item.ColumnName);
}
return dataTable;
}
/// <summary>
/// Common logic for two versions of GetDataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <param name="type"></param>
/// <param name="entities"></param>
/// <param name="tableInfo"></param>
/// <returns></returns>
private static DataTable InnerGetDataTable<T>(DbContext context, ref Type type, IList<T> entities, TableInfo tableInfo)
{
var dataTable = new DataTable();
var columnsDict = new Dictionary<string, object>();
var ownedEntitiesMappedProperties = new HashSet<string>();
var isSqlServer = context.Database.ProviderName.EndsWith(DbServer.SqlServer.ToString());
var sqlServerBytesWriter = new SqlServerBytesWriter
{
IsGeography = true
};
var objectIdentifier = tableInfo.ObjectIdentifier;
type = tableInfo.HasAbstractList ? entities[0].GetType() : type;
var entityType = context.Model.FindEntityType(type);
var entityTypeProperties = entityType.GetProperties();
var entityPropertiesDict = entityTypeProperties.Where(a => tableInfo.PropertyColumnNamesDict.ContainsKey(a.Name) || a.Name == tableInfo.TimeStampPropertyName).ToDictionary(a => a.Name, a => a);
var entityNavigationOwnedDict = entityType.GetNavigations().Where(a => a.TargetEntityType.IsOwned()).ToDictionary(a => a.Name, a => a);
var entityShadowFkPropertiesDict = entityTypeProperties.Where(a => a.IsShadowProperty() &&
a.IsForeignKey() &&
a.GetContainingForeignKeys().FirstOrDefault()?.DependentToPrincipal?.Name != null)
.ToDictionary(a => a.Name, a => a);
var entityShadowFkPropertyColumnNamesDict = entityShadowFkPropertiesDict.ToDictionary(a => a.Key, a => a.Value.GetColumnName(objectIdentifier));
var shadowPropertyColumnNamesDict = entityPropertiesDict.Where(a => a.Value.IsShadowProperty()).ToDictionary(a => a.Key, a => a.Value.GetColumnName(objectIdentifier));
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var discriminatorColumn = GetDiscriminatorColumn(tableInfo);
foreach (var property in properties)
{
if (entityPropertiesDict.ContainsKey(property.Name))
{
var propertyEntityType = entityPropertiesDict[property.Name];
string columnName = propertyEntityType.GetColumnName(objectIdentifier);
var isConvertible = tableInfo.ConvertibleColumnConverterDict.ContainsKey(columnName);
var propertyType = isConvertible ? tableInfo.ConvertibleColumnConverterDict[columnName].ProviderClrType : property.PropertyType;
var underlyingType = Nullable.GetUnderlyingType(propertyType);
if (underlyingType != null)
{
propertyType = underlyingType;
}
if (isSqlServer && (propertyType == typeof(Geometry) || propertyType.IsSubclassOf(typeof(Geometry))))
{
propertyType = typeof(byte[]);
tableInfo.HasSpatialType = true;
if (tableInfo.BulkConfig.PropertiesToIncludeOnCompare != null || tableInfo.BulkConfig.PropertiesToIncludeOnCompare != null)
{
throw new InvalidOperationException("OnCompare properties Config can not be set for Entity with Spatial types like 'Geometry'");
}
}
if (!columnsDict.ContainsKey(property.Name))
{
dataTable.Columns.Add(columnName, propertyType);
columnsDict.Add(property.Name, null);
}
}
else if (entityShadowFkPropertiesDict.ContainsKey(property.Name))
{
var fk = entityShadowFkPropertiesDict[property.Name];
entityPropertiesDict.TryGetValue(fk.GetColumnName(objectIdentifier), out var entityProperty);
if (entityProperty == null) // BulkRead
continue;
var columnName = entityProperty.GetColumnName(objectIdentifier);
var propertyType = entityProperty.ClrType;
var underlyingType = Nullable.GetUnderlyingType(propertyType);
if (underlyingType != null)
{
propertyType = underlyingType;
}
if (propertyType == typeof(Geometry) && isSqlServer)
{
propertyType = typeof(byte[]);
}
if (!columnsDict.ContainsKey(property.Name))
{
dataTable.Columns.Add(columnName, propertyType);
columnsDict.Add(columnName, null);
}
}
else if (entityNavigationOwnedDict.ContainsKey(property.Name)) // isOWned
{
Type navOwnedType = type.Assembly.GetType(property.PropertyType.FullName);
var ownedEntityType = context.Model.FindEntityType(property.PropertyType);
if (ownedEntityType == null)
{
ownedEntityType = context.Model.GetEntityTypes().SingleOrDefault(a => a.DefiningNavigationName == property.Name && a.DefiningEntityType.Name == entityType.Name);
}
var ownedEntityProperties = ownedEntityType.GetProperties().ToList();
var ownedEntityPropertyNameColumnNameDict = new Dictionary<string, string>();
foreach (var ownedEntityProperty in ownedEntityProperties)
{
if (!ownedEntityProperty.IsPrimaryKey())
{
string columnName = ownedEntityProperty.GetColumnName(objectIdentifier);
if (tableInfo.PropertyColumnNamesDict.ContainsValue(columnName))
{
ownedEntityPropertyNameColumnNameDict.Add(ownedEntityProperty.Name, columnName);
ownedEntitiesMappedProperties.Add(property.Name + "_" + ownedEntityProperty.Name);
}
}
}
var innerProperties = property.PropertyType.GetProperties();
if (!tableInfo.LoadOnlyPKColumn)
{
foreach (var innerProperty in innerProperties)
{
if (ownedEntityPropertyNameColumnNameDict.ContainsKey(innerProperty.Name))
{
var columnName = ownedEntityPropertyNameColumnNameDict[innerProperty.Name];
var propertyName = $"{property.Name}_{innerProperty.Name}";
if (tableInfo.ConvertibleColumnConverterDict.ContainsKey(propertyName))
{
var convertor = tableInfo.ConvertibleColumnConverterDict[propertyName];
var underlyingType = Nullable.GetUnderlyingType(convertor.ProviderClrType) ?? convertor.ProviderClrType;
dataTable.Columns.Add(columnName, underlyingType);
}
else
{
var ownedPropertyType = Nullable.GetUnderlyingType(innerProperty.PropertyType) ?? innerProperty.PropertyType;
dataTable.Columns.Add(columnName, ownedPropertyType);
}
columnsDict.Add(property.Name + "_" + innerProperty.Name, null);
}
}
}
}
}
if (tableInfo.BulkConfig.EnableShadowProperties)
{
foreach (var shadowProperty in entityPropertiesDict.Values.Where(a => a.IsShadowProperty()))
{
var columnName = shadowProperty.GetColumnName(objectIdentifier);
// If a model has an entity which has a relationship without an explicity defined FK, the data table will already contain the foreign key shadow property
if (dataTable.Columns.Contains(columnName))
continue;
var isConvertible = tableInfo.ConvertibleColumnConverterDict.ContainsKey(columnName);
var propertyType = isConvertible ? tableInfo.ConvertibleColumnConverterDict[columnName].ProviderClrType : shadowProperty.ClrType;
var underlyingType = Nullable.GetUnderlyingType(propertyType);
if (underlyingType != null)
{
propertyType = underlyingType;
}
if (isSqlServer && (propertyType == typeof(Geometry) || propertyType.IsSubclassOf(typeof(Geometry))))
{
propertyType = typeof(byte[]);
}
dataTable.Columns.Add(columnName, propertyType);
columnsDict.Add(shadowProperty.Name, null);
}
}
if (discriminatorColumn != null)
{
dataTable.Columns.Add(discriminatorColumn, typeof(string));
columnsDict.Add(discriminatorColumn, type.Name);
}
bool hasConverterProperties = tableInfo.ConvertiblePropertyColumnDict.Count > 0;
foreach (var entity in entities)
{
foreach (var property in properties)
{
var propertyValue = tableInfo.FastPropertyDict.ContainsKey(property.Name) ? tableInfo.FastPropertyDict[property.Name].Get(entity) : null;
if (tableInfo.BulkConfig.DateTime2PrecisionForceRound && isSqlServer && tableInfo.DateTime2PropertiesPrecisionLessThen7Dict.ContainsKey(property.Name))
{
DateTime dateTimePropertyValue = (DateTime)propertyValue;
int precision = tableInfo.DateTime2PropertiesPrecisionLessThen7Dict[property.Name];
int digitsToRemove = 7 - precision;
int powerOf10 = (int)Math.Pow(10, digitsToRemove);
long subsecondTicks = dateTimePropertyValue.Ticks % 10000000;
long ticksToRound = subsecondTicks + (subsecondTicks % 10 == 0 ? 1 : 0); // if ends with 0 add 1 tick to make sure rounding of value .5_zeros is rounded to Upper like SqlServer is doing, not to Even as Math.Round works
int roundedTicks = Convert.ToInt32(Math.Round((decimal)ticksToRound / powerOf10, 0)) * powerOf10;
dateTimePropertyValue = dateTimePropertyValue.AddTicks(-subsecondTicks).AddTicks(roundedTicks);
propertyValue = dateTimePropertyValue;
}
if (hasConverterProperties && tableInfo.ConvertiblePropertyColumnDict.ContainsKey(property.Name))
{
string columnName = tableInfo.ConvertiblePropertyColumnDict[property.Name];
propertyValue = tableInfo.ConvertibleColumnConverterDict[columnName].ConvertToProvider.Invoke(propertyValue);
}
if (tableInfo.HasSpatialType && propertyValue is Geometry geometryValue)
{
geometryValue.SRID = tableInfo.BulkConfig.SRID;
propertyValue = sqlServerBytesWriter.Write(geometryValue);
}
if (entityPropertiesDict.ContainsKey(property.Name))
{
columnsDict[property.Name] = propertyValue;
}
else if (entityShadowFkPropertiesDict.ContainsKey(property.Name))
{
var foreignKeyShadowProperty = entityShadowFkPropertiesDict[property.Name];
var columnName = entityShadowFkPropertyColumnNamesDict[property.Name];
entityPropertiesDict.TryGetValue(columnName, out var entityProperty);
if (entityProperty == null) // BulkRead
continue;
columnsDict[columnName] = propertyValue == null ? null : foreignKeyShadowProperty.FindFirstPrincipal().PropertyInfo.GetValue(propertyValue); // TODO Check if can be optimized
}
else if (entityNavigationOwnedDict.ContainsKey(property.Name) && !tableInfo.LoadOnlyPKColumn)
{
var ownedProperties = property.PropertyType.GetProperties().Where(a => ownedEntitiesMappedProperties.Contains(property.Name + "_" + a.Name));
foreach (var ownedProperty in ownedProperties)
{
var columnName = $"{property.Name}_{ownedProperty.Name}";
var ownedPropertyValue = propertyValue == null ? null : tableInfo.FastPropertyDict[columnName].Get(propertyValue);
if (tableInfo.ConvertibleColumnConverterDict.ContainsKey(columnName))
{
var converter = tableInfo.ConvertibleColumnConverterDict[columnName];
columnsDict[columnName] = ownedPropertyValue == null ? null : converter.ConvertToProvider.Invoke(ownedPropertyValue);
}
else
{
columnsDict[columnName] = ownedPropertyValue;
}
}
}
}
if (tableInfo.BulkConfig.EnableShadowProperties)
{
foreach (var shadowPropertyName in shadowPropertyColumnNamesDict.Keys)
{
var shadowProperty = entityPropertiesDict[shadowPropertyName];
var columnName = shadowPropertyColumnNamesDict[shadowPropertyName];
var propertyValue = context.Entry(entity).Property(shadowPropertyName).CurrentValue;
if (tableInfo.ConvertibleColumnConverterDict.ContainsKey(columnName))
{
propertyValue = tableInfo.ConvertibleColumnConverterDict[columnName].ConvertToProvider.Invoke(propertyValue);
}
columnsDict[shadowPropertyName] = propertyValue;
}
}
var record = columnsDict.Values.ToArray();
dataTable.Rows.Add(record);
}
return dataTable;
}
private static string GetDiscriminatorColumn(TableInfo tableInfo)
{
string discriminatorColumn = null;
if (!tableInfo.BulkConfig.EnableShadowProperties && tableInfo.ShadowProperties.Count > 0)
{
discriminatorColumn = tableInfo.ShadowProperties.ElementAt(0);
}
return discriminatorColumn;
}
#endregion
}
}
| 50.04
| 242
| 0.56058
|
[
"MIT"
] |
huer12/EFCore.BulkExtensions
|
EFCore.BulkExtensions/SQLAdapters/SQLServer/SqlServerAdapter.cs
| 35,030
|
C#
|
using System.Net.Sockets;
namespace kcp2k
{
public static class Extensions
{
// 100k attempts of 1 KB increases = default + 100 MB max
public static void SetReceiveBufferToOSLimit(this Socket socket, int stepSize = 1024, int attempts = 100_000)
{
// setting a too large size throws a socket exception.
// so let's keep increasing until we encounter it.
for (int i = 0; i < attempts; ++i)
{
// increase in 1 KB steps
try { socket.ReceiveBufferSize += stepSize; }
catch (SocketException) { break; }
}
}
// 100k attempts of 1 KB increases = default + 100 MB max
public static void SetSendBufferToOSLimit(this Socket socket, int stepSize = 1024, int attempts = 100_000)
{
// setting a too large size throws a socket exception.
// so let's keep increasing until we encounter it.
for (int i = 0; i < attempts; ++i)
{
// increase in 1 KB steps
try { socket.SendBufferSize += stepSize; }
catch (SocketException) { break; }
}
}
}
}
| 37.818182
| 118
| 0.535256
|
[
"MIT"
] |
yacoubb/blob-game
|
2021-blob-game-unity/Assets/Mirror/Runtime/Transport/KCP/kcp2k/highlevel/Extensions.cs
| 1,248
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.ComponentModel;
namespace Azure.Security.KeyVault.Certificates
{
/// <summary>
/// Elliptic Curve Cryptography (ECC) curve names.
/// </summary>
public readonly struct CertificateKeyCurveName : IEquatable<CertificateKeyCurveName>
{
private readonly string _value;
/// <summary>
/// Initializes a new instance of the <see cref="CertificateKeyCurveName"/> structure.
/// </summary>
/// <param name="value">The string value of the instance.</param>
public CertificateKeyCurveName(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Gets the NIST P-256 elliptic curve, AKA SECG curve SECP256R1
/// For more information, see <see href="https://docs.microsoft.com/azure/key-vault/keys/about-keys#curve-types">Curve types</see>.
/// </summary>
public static CertificateKeyCurveName P256 { get; } = new CertificateKeyCurveName("P-256");
/// <summary>
/// Gets the NIST P-384 elliptic curve, AKA SECG curve SECP384R1.
/// For more information, see <see href="https://docs.microsoft.com/azure/key-vault/keys/about-keys#curve-types">Curve types</see>.
/// </summary>
public static CertificateKeyCurveName P384 { get; } = new CertificateKeyCurveName("P-384");
/// <summary>
/// Gets the NIST P-521 elliptic curve, AKA SECG curve SECP521R1.
/// For more information, see <see href="https://docs.microsoft.com/azure/key-vault/keys/about-keys#curve-types">Curve types</see>.
/// </summary>
public static CertificateKeyCurveName P521 { get; } = new CertificateKeyCurveName("P-521");
/// <summary>
/// Gets the SECG SECP256K1 elliptic curve.
/// For more information, see <see href="https://docs.microsoft.com/azure/key-vault/keys/about-keys#curve-types">Curve types</see>.
/// </summary>
public static CertificateKeyCurveName P256K { get; } = new CertificateKeyCurveName("P-256K");
/// <summary>
/// Determines if two <see cref="CertificateKeyCurveName"/> values are the same.
/// </summary>
/// <param name="left">The first <see cref="CertificateKeyCurveName"/> to compare.</param>
/// <param name="right">The second <see cref="CertificateKeyCurveName"/> to compare.</param>
/// <returns>True if <paramref name="left"/> and <paramref name="right"/> are the same; otherwise, false.</returns>
public static bool operator ==(CertificateKeyCurveName left, CertificateKeyCurveName right) => left.Equals(right);
/// <summary>
/// Determines if two <see cref="CertificateKeyCurveName"/> values are different.
/// </summary>
/// <param name="left">The first <see cref="CertificateKeyCurveName"/> to compare.</param>
/// <param name="right">The second <see cref="CertificateKeyCurveName"/> to compare.</param>
/// <returns>True if <paramref name="left"/> and <paramref name="right"/> are different; otherwise, false.</returns>
public static bool operator !=(CertificateKeyCurveName left, CertificateKeyCurveName right) => !left.Equals(right);
/// <summary>
/// Converts a string to a <see cref="CertificateKeyCurveName"/>.
/// </summary>
/// <param name="value">The string value to convert.</param>
public static implicit operator CertificateKeyCurveName(string value) => new CertificateKeyCurveName(value);
/// <inheritdoc/>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is CertificateKeyCurveName other && Equals(other);
/// <inheritdoc/>
public bool Equals(CertificateKeyCurveName other) => string.Equals(_value, other._value, StringComparison.Ordinal);
/// <inheritdoc/>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc/>
public override string ToString() => _value;
}
}
| 49.488372
| 139
| 0.652726
|
[
"MIT"
] |
0rland0Wats0n/azure-sdk-for-net
|
sdk/keyvault/Azure.Security.KeyVault.Certificates/src/CertificateKeyCurveName.cs
| 4,258
|
C#
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class GetUserRecentActivitiesRequest : PaginatedAPIRequest<List<APIRecentActivity>>
{
private readonly long userId;
public GetUserRecentActivitiesRequest(long userId, int page = 0, int itemsPerPage = 5)
: base(page, itemsPerPage)
{
this.userId = userId;
}
protected override string Target => $"users/{userId}/recent_activity";
}
public enum RecentActivityType
{
Achievement,
BeatmapPlaycount,
BeatmapsetApprove,
BeatmapsetDelete,
BeatmapsetRevive,
BeatmapsetUpdate,
BeatmapsetUpload,
Medal,
Rank,
RankLost,
UserSupportAgain,
UserSupportFirst,
UserSupportGift,
UsernameChange,
}
public enum BeatmapApproval
{
Ranked,
Approved,
Qualified,
}
}
| 25.680851
| 95
| 0.61309
|
[
"MIT"
] |
123tris/osu
|
osu.Game/Online/API/Requests/GetUserRecentActivitiesRequest.cs
| 1,163
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DatabaseMigrator
{
using System;
using System.Collections.Generic;
public partial class wp_usermeta
{
public decimal umeta_id { get; set; }
public decimal user_id { get; set; }
public string meta_key { get; set; }
public string meta_value { get; set; }
}
}
| 32.391304
| 84
| 0.520805
|
[
"Apache-2.0"
] |
siderisltd/UspeliteProject
|
Tools/DatabaseMigrator/wp_usermeta.cs
| 745
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class RoomListingMenu : MonoBehaviourPunCallbacks
{
[SerializeField] private Transform container;
[SerializeField] private RoomListing roomListing;
private List<RoomListing> _listings = new List<RoomListing>();
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
foreach (RoomInfo info in roomList)
{
// removed from room list
if (info.RemovedFromList)
{
int index = _listings.FindIndex(i => i.RoomInfo.Name == info.Name);
if (index != -1)
{
Destroy(_listings[index].gameObject);
_listings.RemoveAt(index);
}
}
else // added in the list
{
RoomListing listing = Instantiate(roomListing, container) as RoomListing;
if (listing != null)
{
listing.SetRoomInfo(info);
_listings.Add(listing);
}
}
}
}
}
| 28.166667
| 89
| 0.54776
|
[
"Apache-2.0"
] |
rsaz/mankind
|
Assets/_Game/Scripts/Network/Client/Lobby/RoomListingMenu.cs
| 1,185
|
C#
|
namespace ColorCanvas.Models
{
internal struct HsvColor
{
public double H;
public double S;
public double V;
public HsvColor(double h, double s, double v)
{
H = h;
S = s;
V = v;
}
}
}
| 16.588235
| 53
| 0.453901
|
[
"Apache-2.0"
] |
KHCmaster/PPD
|
Win/ColorCanvas/Models/HsvColor.cs
| 284
|
C#
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Text.Tests
{
public class EncodingEquals
{
#region Positive Test Cases
// Verify method Equals
[Fact]
public void PosTest1()
{
Encoding e1 = Encoding.GetEncoding("utf-8");
Encoding e2 = Encoding.UTF8;
Assert.True(e1.Equals(e2));
}
#endregion
}
}
| 24.227273
| 101
| 0.606004
|
[
"MIT"
] |
690486439/corefx
|
src/System.Text.Encoding/tests/Encoding/EncodingEquals.cs
| 533
|
C#
|
/*--------------------------------------------------------------------------------------
Copyright © 2013 Theodoros Bebekis
teo.bebekis@gmail.com
--------------------------------------------------------------------------------------*/
using System;
namespace Tripous.Data.Metadata
{
/// <summary>
/// Represents a node in a metadata (schema) tree that has loadable children.
/// <para>That is a Tables, Columns, Indexes etc node.</para>
/// </summary>
public interface IMetaNodeList : IMetaNode
{
/* methods */
/// <summary>
/// Loads the metadata information if it is not already loaded
/// </summary>
void Load();
/// <summary>
/// Forces the loading of metadata information even if it is already loaded
/// </summary>
void ReLoad();
/* properties */
/// <summary>
/// True if the metadata is alreade loaded
/// </summary>
bool IsLoaded { get; }
/// <summary>
/// Gets the node list
/// </summary>
IMetaNode[] Nodes { get; }
}
}
| 30.153846
| 97
| 0.439626
|
[
"Unlicense"
] |
tbebekis/Tripous
|
Tripous.Data/Metadata/IMetaNodeList.cs
| 1,179
|
C#
|
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
#if (AddDependencyInjection == false)
using System;
#else
using DefaultLambda.DependencyInjection.ConfigurationService;
#endif
namespace DefaultLambda.Database
{
public class NHibernateHelper
#if (AddDependencyInjection)
: INHibernateHelper
#endif
{
private readonly ISessionFactory _hbnSessionFactory;
public NHibernateHelper(
#if (AddDependencyInjection)
IConfigurationService configurationService
#endif
)
{
#if (AddDependencyInjection)
string connectionString = configurationService
.GetConfiguration()["DB_CONN_STRING"];
#else
string connectionString = Environment.GetEnvironmentVariable("DB_CONN_STRING");
#endif
Configuration hbnConfiguration = Fluently.Configure()
.Database(
#if (UsePostgres)
PostgreSQLConfiguration.PostgreSQL82
.ConnectionString(connectionString)
#else
SQLiteConfiguration.Standard // Add database here
.ConnectionString(connectionString)
#endif
.ShowSql())
.Mappings(m =>
{
// Add mappings here
}
).BuildConfiguration();
this._hbnSessionFactory = hbnConfiguration.BuildSessionFactory();
}
public ISession OpenSession()
{
return this._hbnSessionFactory.OpenSession();
}
}
}
| 28.701754
| 91
| 0.622861
|
[
"MIT"
] |
jbonadiman/aws-lambda-template
|
Database/NHibernateHelper.cs
| 1,638
|
C#
|
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
namespace Sidekick.Business.Apis.Poe.Trade.Data.Stats
{
public class StatData
{
public string Id { get; set; }
public string Text { get; set; }
public string Type { get; set; }
public StatDataOption Option { get; set; }
[JsonIgnore]
public string Category { get; set; }
[JsonIgnore]
public Regex Pattern { get; set; }
[JsonIgnore]
public Regex NegativePattern { get; set; }
}
}
| 22.958333
| 53
| 0.61343
|
[
"MIT"
] |
PeteyPii/Sidekick
|
src/Sidekick.Business/Apis/Poe/Trade/Data/Stats/StatData.cs
| 551
|
C#
|
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using ClearCanvas.Common;
using ClearCanvas.Desktop;
using ClearCanvas.Desktop.View.WinForms;
namespace ClearCanvas.Ris.Client.Admin.View.WinForms
{
/// <summary>
/// Provides a Windows Forms view onto <see cref="ProcedureTypeSummaryComponent"/>
/// </summary>
[ExtensionOf(typeof(ProcedureTypeSummaryComponentViewExtensionPoint))]
public class ProcedureTypeSummaryComponentView : WinFormsView, IApplicationComponentView
{
private ProcedureTypeSummaryComponent _component;
private ProcedureTypeSummaryComponentControl _control;
#region IApplicationComponentView Members
public void SetComponent(IApplicationComponent component)
{
_component = (ProcedureTypeSummaryComponent)component;
}
#endregion
public override object GuiElement
{
get
{
if (_control == null)
{
_control = new ProcedureTypeSummaryComponentControl(_component);
}
return _control;
}
}
}
}
| 24.54717
| 90
| 0.734819
|
[
"Apache-2.0"
] |
SNBnani/Xian
|
Ris/Client/Admin/View/WinForms/ProcedureTypeSummaryComponentView.cs
| 1,301
|
C#
|
using System;
using Xunit.Abstractions;
namespace Xunit.ConsoleClient
{
public class DiagnosticMessageSink : TestMessageSink
{
readonly string assemblyDisplayName;
readonly object consoleLock;
readonly ConsoleColor displayColor;
readonly bool noColor;
DiagnosticMessageSink(object consoleLock, string assemblyDisplayName, bool showDiagnostics, bool noColor, ConsoleColor displayColor)
{
this.consoleLock = consoleLock;
this.assemblyDisplayName = assemblyDisplayName;
this.noColor = noColor;
this.displayColor = displayColor;
if (showDiagnostics)
Diagnostics.DiagnosticMessageEvent += HandleDiagnosticMessage;
}
public static DiagnosticMessageSink ForDiagnostics(object consoleLock, string assemblyDisplayName, bool showDiagnostics, bool noColor)
=> new DiagnosticMessageSink(consoleLock, assemblyDisplayName, showDiagnostics, noColor, ConsoleColor.Yellow);
public static DiagnosticMessageSink ForInternalDiagnostics(object consoleLock, bool showDiagnostics, bool noColor)
=> new DiagnosticMessageSink(consoleLock, null, showDiagnostics, noColor, ConsoleColor.DarkGray);
public static DiagnosticMessageSink ForInternalDiagnostics(object consoleLock, string assemblyDisplayName, bool showDiagnostics, bool noColor)
=> new DiagnosticMessageSink(consoleLock, assemblyDisplayName, showDiagnostics, noColor, ConsoleColor.DarkGray);
void HandleDiagnosticMessage(MessageHandlerArgs<IDiagnosticMessage> args)
{
lock (consoleLock)
{
if (!noColor)
ConsoleHelper.SetForegroundColor(displayColor);
if (assemblyDisplayName != null)
Console.WriteLine($" {assemblyDisplayName}: {args.Message.Message}");
else
Console.WriteLine($" {args.Message.Message}");
if (!noColor)
ConsoleHelper.ResetColor();
}
}
}
}
| 41.411765
| 150
| 0.672822
|
[
"Apache-2.0"
] |
erikbra/xunit
|
src/xunit.console/Sinks/DiagnosticMessageSink.cs
| 2,114
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Native.Csharp.App.Gameplay.CharacterUtil
{
public class TimeHandler
{
}
}
| 15.928571
| 50
| 0.726457
|
[
"MIT"
] |
apflu/DungeonBot
|
Native.Csharp/App/Gameplay/CharacterUtil/TimeHandler.cs
| 225
|
C#
|
using System;
namespace ClassToString
{
class Person
{
private string name;
public Person(string name)
{
this.name = name;
}
// ToString() 메서드 오버라이드(재정의)
public override string ToString() => $"[Person 클래스: {this.name}]";
}
class ClassToString
{
static void Main()
{
Person person = new Person("박용준");
Console.WriteLine(person); // 개체를 문자열로 출력하면 ToString() 호출됨
}
}
}
| 18.62963
| 74
| 0.514911
|
[
"MIT"
] |
VisualAcademy/DotNet
|
DotNet/DotNet/44_Override/06_ClassToString/ClassToString.cs
| 567
|
C#
|
using FEZAnalyzer.Entity;
using OpenCvSharp;
namespace FEZAnalyzer.ResultRecognize.NewUI.Base
{
internal class WarTotalScoreScanner
{
private static readonly Vec3b White = new Vec3b(0xFF, 0xFF, 0xFF);
private const int Width = 60;
private const int Height = 30;
// 走査するy座標
private const int Y = 0;
private readonly Rect _rect;
public WarTotalScoreScanner(int left, int top)
{
_rect = new Rect(left, top, Width, Height);
}
public int? Scan(WarResultImage resultImage)
{
var ret = "";
using (var tmp = resultImage.Image.Clone(_rect))
using (var mat = new Mat<Vec3b>(tmp))
{
var idx = mat.GetIndexer();
for (var x = 0; x < mat.Width - 5; x++)
{
if (idx[Y, x] != White)
{
continue;
}
var skipPixel = 0;
var r1c = idx[Y, x + 1]; // 1px横のピクセルの色
var r2c = idx[Y, x + 2]; // 2px横のピクセルの色
var r3c = idx[Y, x + 3]; // 3px横のピクセルの色
var r4c = idx[Y, x + 4]; // 4px横のピクセルの色
var r5c = idx[Y, x + 5]; // 5px横のピクセルの色
if (r1c != White)
{
// Group:1px
// (+2, -1)pxの色をチェック
if (idx[Y + 2, x - 1] == White)
{
ret += "4";
}
else
{
ret += "1";
}
skipPixel = 0;
}
else if (r1c == White && r2c == White && r3c != White)
{
// Group:3px
// 指定のピクセルの色をチェック
var c1 = idx[Y + 4, x - 1]; // (+4, -1)px
var c2 = idx[Y + 5, x - 1]; // (+5, -1)px
var c3 = idx[Y + 6, x - 1]; // (+6, -1)px
var c4 = idx[Y + 5, x + 0]; // (+5, 0)px
if (c1 == White && c2 == White && c3 == White && c4 == White) // true, true, true, true :6
{
ret += "6";
}
else if (c1 == White && c2 == White && c3 == White && c4 != White) // true, true, true, false:0
{
ret += "0";
}
else if (c1 == White && c2 != White && c3 == White && c4 == White) // true, false, true, true :8
{
ret += "8";
}
else if (c1 == White && c2 == White && c3 != White && c4 != White) // true, true, false, false:9
{
ret += "9";
}
else if (c1 != White && c2 != White && c3 != White && c4 != White) // false, false, false, false:2
{
ret += "2";
}
else if (c1 != White && c2 != White && c3 != White && c4 == White) // false, false, false, true :3
{
ret += "3";
}
skipPixel = 2;
}
else if (r1c == White && r2c == White && r3c == White && r4c == White && r5c != White)
{
// Group:5px
// (+1, 0)pxの色をチェック
if (idx[Y + 1, x + 0] == White)
{
ret += "5";
}
else
{
ret += "7";
}
skipPixel = 4;
}
// 同じ数字の部分は走査をスキップさせる
x += skipPixel;
}
}
return string.IsNullOrEmpty(ret) ? (int?)null : int.Parse(ret);
}
}
}
| 36.133333
| 123
| 0.30512
|
[
"MIT"
] |
saipan-fez/fez_analyzer
|
src/FEZAnalyzer/FEZAnalyzer.ResultRecognize/NewUI/Base/WarTotalScoreScanner.cs
| 4,522
|
C#
|
using UnityEngine;
namespace Voxels.Utils {
public static class MathUtils {
public static float Remap(float inValue, float inMin, float inMax, float outMin, float outMax) {
return outMin + (outMax - outMin) * ((inValue - inMin) / (inMax - inMin));
}
public static Vector3 UnpackRotation(Byte3 rot) {
var pitch = Remap(rot.X, 0, 255, 0, 360);
var yaw = Remap(rot.Y, 0, 255, 0, 360);
var roll = Remap(rot.Z, 0, 255, 0, 360);
return new Vector3(pitch, yaw, roll);
}
public static Byte3 PackRotation(Vector3 rot) {
var p = (byte)Mathf.RoundToInt(Remap(rot.x, 0, 360, 0, 255));
var y = (byte)Mathf.RoundToInt(Remap(rot.y, 0, 360, 0, 255));
var r = (byte)Mathf.RoundToInt(Remap(rot.z, 0, 360, 0, 255));
return new Byte3(p, y, r);
}
}
}
| 29.961538
| 98
| 0.643132
|
[
"MIT"
] |
TxN/VoxelLand
|
Assets/Scripts/Utils/MathUtils.cs
| 779
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using System.Globalization;
using System.Linq;
using JetBrains.Annotations;
using UnitsNet.InternalHelpers;
using UnitsNet.Units;
// ReSharper disable once CheckNamespace
namespace UnitsNet
{
/// <inheritdoc />
/// <summary>
/// The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor.
/// </summary>
public partial class ElectricResistance : IQuantity<ElectricResistanceUnit>, IEquatable<ElectricResistance>, IComparable, IComparable<ElectricResistance>, IConvertible, IFormattable
{
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
private readonly double _value;
/// <summary>
/// The unit this quantity was constructed with.
/// </summary>
private readonly ElectricResistanceUnit? _unit;
static ElectricResistance()
{
BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0);
Info = new QuantityInfo<ElectricResistanceUnit>(QuantityType.ElectricResistance,
new UnitInfo<ElectricResistanceUnit>[] {
new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Gigaohm, BaseUnits.Undefined),
new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Kiloohm, BaseUnits.Undefined),
new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Megaohm, BaseUnits.Undefined),
new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Milliohm, BaseUnits.Undefined),
new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Ohm, BaseUnits.Undefined),
},
BaseUnit, Zero, BaseDimensions);
}
/// <summary>
/// Creates the quantity with the given numeric value and unit.
/// </summary>
/// <param name="numericValue">The numeric value to contruct this quantity with.</param>
/// <param name="unit">The unit representation to contruct this quantity with.</param>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public ElectricResistance(double numericValue, ElectricResistanceUnit unit)
{
if(unit == ElectricResistanceUnit.Undefined)
throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit));
_value = Guard.EnsureValidNumber(numericValue, nameof(numericValue));
_unit = unit;
}
/// <summary>
/// Creates an instance of the quantity with the given numeric value in units compatible with the given <see cref="UnitSystem"/>.
/// If multiple compatible units were found, the first match is used.
/// </summary>
/// <param name="numericValue">The numeric value to contruct this quantity with.</param>
/// <param name="unitSystem">The unit system to create the quantity with.</param>
/// <exception cref="ArgumentNullException">The given <see cref="UnitSystem"/> is null.</exception>
/// <exception cref="ArgumentException">No unit was found for the given <see cref="UnitSystem"/>.</exception>
public ElectricResistance(double numericValue, UnitSystem unitSystem)
{
if(unitSystem == null) throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault(u => u.Value.Equals(BaseUnit));
// for custom units, sometimes we don't find the base unit, this grabs the first off the list.
if(Equals(firstUnitInfo, null ))
{
firstUnitInfo = unitInfos.FirstOrDefault();
}
_value = Guard.EnsureValidNumber(numericValue, nameof(numericValue));
_unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
}
#region Static Properties
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
public static QuantityInfo<ElectricResistanceUnit> Info { get; }
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public static BaseDimensions BaseDimensions { get; }
/// <summary>
/// The base unit of ElectricResistance, which is Ohm. All conversions go via this value.
/// </summary>
public static ElectricResistanceUnit BaseUnit { get; } = ElectricResistanceUnit.Ohm;
/// <summary>
/// Represents the largest possible value of ElectricResistance
/// </summary>
public static ElectricResistance MaxValue { get; } = new ElectricResistance(double.MaxValue, BaseUnit);
/// <summary>
/// Represents the smallest possible value of ElectricResistance
/// </summary>
public static ElectricResistance MinValue { get; } = new ElectricResistance(double.MinValue, BaseUnit);
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
public static QuantityType QuantityType { get; } = QuantityType.ElectricResistance;
/// <summary>
/// All units of measurement for the ElectricResistance quantity.
/// </summary>
public static ElectricResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast<ElectricResistanceUnit>().Except(new ElectricResistanceUnit[]{ ElectricResistanceUnit.Undefined }).ToArray();
/// <summary>
/// Gets an instance of this quantity with a value of 0 in the base unit Ohm.
/// </summary>
public static ElectricResistance Zero { get; } = new ElectricResistance(0, BaseUnit);
#endregion
#region Properties
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
public double Value => _value;
Enum IQuantity.Unit => Unit;
/// <inheritdoc />
public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit);
/// <inheritdoc />
public QuantityInfo<ElectricResistanceUnit> QuantityInfo => Info;
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
QuantityInfo IQuantity.QuantityInfo => Info;
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
public QuantityType Type => ElectricResistance.QuantityType;
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public BaseDimensions Dimensions => ElectricResistance.BaseDimensions;
#endregion
#region Conversion Properties
/// <summary>
/// Get ElectricResistance in Gigaohms.
/// </summary>
public double Gigaohms => As(ElectricResistanceUnit.Gigaohm);
/// <summary>
/// Get ElectricResistance in Kiloohms.
/// </summary>
public double Kiloohms => As(ElectricResistanceUnit.Kiloohm);
/// <summary>
/// Get ElectricResistance in Megaohms.
/// </summary>
public double Megaohms => As(ElectricResistanceUnit.Megaohm);
/// <summary>
/// Get ElectricResistance in Milliohms.
/// </summary>
public double Milliohms => As(ElectricResistanceUnit.Milliohm);
/// <summary>
/// Get ElectricResistance in Ohms.
/// </summary>
public double Ohms => As(ElectricResistanceUnit.Ohm);
#endregion
#region Static Methods
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
public static string GetAbbreviation(ElectricResistanceUnit unit)
{
return GetAbbreviation(unit, null);
}
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
/// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] IFormatProvider provider)
{
return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider);
}
#endregion
#region Static Factory Methods
/// <summary>
/// Get ElectricResistance from Gigaohms.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricResistance FromGigaohms(QuantityValue gigaohms)
{
double value = (double) gigaohms;
return new ElectricResistance(value, ElectricResistanceUnit.Gigaohm);
}
/// <summary>
/// Get ElectricResistance from Kiloohms.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricResistance FromKiloohms(QuantityValue kiloohms)
{
double value = (double) kiloohms;
return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm);
}
/// <summary>
/// Get ElectricResistance from Megaohms.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricResistance FromMegaohms(QuantityValue megaohms)
{
double value = (double) megaohms;
return new ElectricResistance(value, ElectricResistanceUnit.Megaohm);
}
/// <summary>
/// Get ElectricResistance from Milliohms.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricResistance FromMilliohms(QuantityValue milliohms)
{
double value = (double) milliohms;
return new ElectricResistance(value, ElectricResistanceUnit.Milliohm);
}
/// <summary>
/// Get ElectricResistance from Ohms.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricResistance FromOhms(QuantityValue ohms)
{
double value = (double) ohms;
return new ElectricResistance(value, ElectricResistanceUnit.Ohm);
}
/// <summary>
/// Dynamically convert from value and unit enum <see cref="ElectricResistanceUnit" /> to <see cref="ElectricResistance" />.
/// </summary>
/// <param name="value">Value to convert from.</param>
/// <param name="fromUnit">Unit to convert from.</param>
/// <returns>ElectricResistance unit value.</returns>
public static ElectricResistance From(QuantityValue value, ElectricResistanceUnit fromUnit)
{
return new ElectricResistance((double)value, fromUnit);
}
#endregion
#region Static Parse Methods
/// <summary>
/// Parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="ArgumentException">
/// Expected string to have one or two pairs of quantity and unit in the format
/// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in"
/// </exception>
/// <exception cref="AmbiguousUnitParseException">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse("1 cup") will throw, because it can refer to any of
/// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
/// </exception>
/// <exception cref="UnitsNetException">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
public static ElectricResistance Parse(string str)
{
return Parse(str, null);
}
/// <summary>
/// Parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="ArgumentException">
/// Expected string to have one or two pairs of quantity and unit in the format
/// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in"
/// </exception>
/// <exception cref="AmbiguousUnitParseException">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse("1 cup") will throw, because it can refer to any of
/// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
/// </exception>
/// <exception cref="UnitsNetException">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static ElectricResistance Parse(string str, [CanBeNull] IFormatProvider provider)
{
return QuantityParser.Default.Parse<ElectricResistance, ElectricResistanceUnit>(
str,
provider,
From);
}
/// <summary>
/// Try to parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
public static bool TryParse([CanBeNull] string str, out ElectricResistance result)
{
return TryParse(str, null, out result);
}
/// <summary>
/// Try to parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricResistance result)
{
return QuantityParser.Default.TryParse<ElectricResistance, ElectricResistanceUnit>(
str,
provider,
From,
out result);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
public static ElectricResistanceUnit ParseUnit(string str)
{
return ParseUnit(str, null);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static ElectricResistanceUnit ParseUnit(string str, IFormatProvider provider = null)
{
return UnitParser.Default.Parse<ElectricResistanceUnit>(str, provider);
}
/// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricResistanceUnit)"/>
public static bool TryParseUnit(string str, out ElectricResistanceUnit unit)
{
return TryParseUnit(str, null, out unit);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="unit">The parsed unit if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.TryParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricResistanceUnit unit)
{
return UnitParser.Default.TryParse<ElectricResistanceUnit>(str, provider, out unit);
}
#endregion
#region Arithmetic Operators
/// <summary>Negate the value.</summary>
public static ElectricResistance operator -(ElectricResistance right)
{
return new ElectricResistance(-right.Value, right.Unit);
}
/// <summary>Get <see cref="ElectricResistance"/> from adding two <see cref="ElectricResistance"/>.</summary>
public static ElectricResistance operator +(ElectricResistance left, ElectricResistance right)
{
return new ElectricResistance(left.Value + right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="ElectricResistance"/> from subtracting two <see cref="ElectricResistance"/>.</summary>
public static ElectricResistance operator -(ElectricResistance left, ElectricResistance right)
{
return new ElectricResistance(left.Value - right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="ElectricResistance"/> from multiplying value and <see cref="ElectricResistance"/>.</summary>
public static ElectricResistance operator *(double left, ElectricResistance right)
{
return new ElectricResistance(left * right.Value, right.Unit);
}
/// <summary>Get <see cref="ElectricResistance"/> from multiplying value and <see cref="ElectricResistance"/>.</summary>
public static ElectricResistance operator *(ElectricResistance left, double right)
{
return new ElectricResistance(left.Value * right, left.Unit);
}
/// <summary>Get <see cref="ElectricResistance"/> from dividing <see cref="ElectricResistance"/> by value.</summary>
public static ElectricResistance operator /(ElectricResistance left, double right)
{
return new ElectricResistance(left.Value / right, left.Unit);
}
/// <summary>Get ratio value from dividing <see cref="ElectricResistance"/> by <see cref="ElectricResistance"/>.</summary>
public static double operator /(ElectricResistance left, ElectricResistance right)
{
return left.Ohms / right.Ohms;
}
#endregion
#region Equality / IComparable
/// <summary>Returns true if less or equal to.</summary>
public static bool operator <=(ElectricResistance left, ElectricResistance right)
{
if(left is null || right is null )
return false;
return left.Value <= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than or equal to.</summary>
public static bool operator >=(ElectricResistance left, ElectricResistance right)
{
if(left is null || right is null )
return false;
return left.Value >= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if less than.</summary>
public static bool operator <(ElectricResistance left, ElectricResistance right)
{
if(left is null || right is null )
return false;
return left.Value < right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than.</summary>
public static bool operator >(ElectricResistance left, ElectricResistance right)
{
if(left is null || right is null )
return false;
return left.Value > right.GetValueAs(left.Unit);
}
/// <summary>Returns true if exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(ElectricResistance, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator ==(ElectricResistance left, ElectricResistance right)
{
if(left is null && right is null )
return true;
if( left is null )
return false;
return left.Equals(right);
}
/// <summary>Returns true if not exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(ElectricResistance, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator !=(ElectricResistance left, ElectricResistance right)
{
return !(left == right);
}
/// <inheritdoc />
public int CompareTo(object obj)
{
if(obj is null) throw new ArgumentNullException(nameof(obj));
if(!(obj is ElectricResistance objElectricResistance)) throw new ArgumentException("Expected type ElectricResistance.", nameof(obj));
return CompareTo(objElectricResistance);
}
/// <inheritdoc />
public int CompareTo(ElectricResistance other)
{
if(other is null) throw new ArgumentNullException();
return _value.CompareTo(other.GetValueAs(this.Unit));
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(ElectricResistance, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public override bool Equals(object obj)
{
if(obj is null || !(obj is ElectricResistance objElectricResistance))
return false;
return Equals(objElectricResistance);
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(ElectricResistance, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public bool Equals(ElectricResistance other)
{
if(other is null)
return false;
return _value.Equals(other.GetValueAs(this.Unit));
}
/// <summary>
/// <para>
/// Compare equality to another ElectricResistance within the given absolute or relative tolerance.
/// </para>
/// <para>
/// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of
/// this quantity's value to be considered equal.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Relative);
/// </code>
/// </example>
/// </para>
/// <para>
/// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Absolute);
/// </code>
/// </example>
/// </para>
/// <para>
/// Note that it is advised against specifying zero difference, due to the nature
/// of floating point operations and using System.Double internally.
/// </para>
/// </summary>
/// <param name="other">The other quantity to compare to.</param>
/// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param>
/// <param name="comparisonType">The comparison type: either relative or absolute.</param>
/// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns>
public bool Equals(ElectricResistance other, double tolerance, ComparisonType comparisonType)
{
if(tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0.");
double thisValue = (double)this.Value;
double otherValueInThisUnits = other.As(this.Unit);
return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A hash code for the current ElectricResistance.</returns>
public override int GetHashCode()
{
return new { QuantityType, Value, Unit }.GetHashCode();
}
#endregion
#region Conversion Methods
/// <summary>
/// Convert to the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>Value converted to the specified unit.</returns>
public double As(ElectricResistanceUnit unit)
{
if(Unit == unit)
return Convert.ToDouble(Value);
var converted = GetValueAs(unit);
return Convert.ToDouble(converted);
}
/// <inheritdoc cref="IQuantity.As(UnitSystem)"/>
public double As(UnitSystem unitSystem)
{
if(unitSystem == null)
throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault(u => u.Value.Equals(BaseUnit));
if (firstUnitInfo is null)
{
firstUnitInfo = unitInfos.FirstOrDefault();
if (firstUnitInfo is null)
throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
}
return As(firstUnitInfo.Value);
}
/// <inheritdoc />
double IQuantity.As(Enum unit)
{
if(!(unit is ElectricResistanceUnit unitAsElectricResistanceUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit));
return As(unitAsElectricResistanceUnit);
}
/// <summary>
/// Converts this ElectricResistance to another ElectricResistance with the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>A ElectricResistance with the specified unit.</returns>
public ElectricResistance ToUnit(ElectricResistanceUnit unit)
{
var convertedValue = GetValueAs(unit);
return new ElectricResistance(convertedValue, unit);
}
/// <inheritdoc />
IQuantity IQuantity.ToUnit(Enum unit)
{
if(!(unit is ElectricResistanceUnit unitAsElectricResistanceUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit));
return ToUnit(unitAsElectricResistanceUnit);
}
/// <inheritdoc cref="IQuantity.ToUnit(UnitSystem)"/>
public ElectricResistance ToUnit(UnitSystem unitSystem)
{
if(unitSystem == null)
throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault(u=> u.Value.Equals(BaseUnit));
if (firstUnitInfo == null)
throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
return ToUnit(firstUnitInfo.Value);
}
/// <inheritdoc />
IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem);
/// <inheritdoc />
IQuantity<ElectricResistanceUnit> IQuantity<ElectricResistanceUnit>.ToUnit(ElectricResistanceUnit unit) => ToUnit(unit);
/// <inheritdoc />
IQuantity<ElectricResistanceUnit> IQuantity<ElectricResistanceUnit>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem);
/// <summary>
/// Converts the current value + unit to the base unit.
/// This is typically the first step in converting from one unit to another.
/// </summary>
/// <returns>The value in the base unit representation.</returns>
private double GetValueInBaseUnit()
{
switch(Unit)
{
case ElectricResistanceUnit.Gigaohm: return (_value) * 1e9d;
case ElectricResistanceUnit.Kiloohm: return (_value) * 1e3d;
case ElectricResistanceUnit.Megaohm: return (_value) * 1e6d;
case ElectricResistanceUnit.Milliohm: return (_value) * 1e-3d;
case ElectricResistanceUnit.Ohm: return _value;
default:
throw new NotImplementedException($"Can not convert {Unit} to base units.");
}
}
private double GetValueAs(ElectricResistanceUnit unit)
{
if(Unit == unit)
return _value;
var baseUnitValue = GetValueInBaseUnit();
switch(unit)
{
case ElectricResistanceUnit.Gigaohm: return (baseUnitValue) / 1e9d;
case ElectricResistanceUnit.Kiloohm: return (baseUnitValue) / 1e3d;
case ElectricResistanceUnit.Megaohm: return (baseUnitValue) / 1e6d;
case ElectricResistanceUnit.Milliohm: return (baseUnitValue) / 1e-3d;
case ElectricResistanceUnit.Ohm: return baseUnitValue;
default:
throw new NotImplementedException($"Can not convert {Unit} to {unit}.");
}
}
#endregion
#region ToString Methods
/// <summary>
/// Gets the default string representation of value and unit.
/// </summary>
/// <returns>String representation.</returns>
public override string ToString()
{
return ToString("g");
}
/// <summary>
/// Gets the default string representation of value and unit using the given format provider.
/// </summary>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public string ToString([CanBeNull] IFormatProvider provider)
{
return ToString("g", provider);
}
/// <summary>
/// Get string representation of value and unit.
/// </summary>
/// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
[Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")]
public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix)
{
var value = Convert.ToDouble(Value);
var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix);
return ToString(provider, format);
}
/// <summary>
/// Get string representation of value and unit.
/// </summary>
/// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param>
/// <param name="args">Arguments for string format. Value and unit are implictly included as arguments 0 and 1.</param>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
[Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")]
public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args)
{
if (format == null) throw new ArgumentNullException(nameof(format));
if (args == null) throw new ArgumentNullException(nameof(args));
provider = provider ?? CultureInfo.CurrentUICulture;
var value = Convert.ToDouble(Value);
var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args);
return string.Format(provider, format, formatArgs);
}
/// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/>
/// <summary>
/// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentUICulture" />.
/// </summary>
/// <param name="format">The format string.</param>
/// <returns>The string representation.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentUICulture);
}
/// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/>
/// <summary>
/// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentUICulture" /> if null.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="formatProvider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
/// <returns>The string representation.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return QuantityFormatter.Format<ElectricResistanceUnit>(this, format, formatProvider);
}
#endregion
#region IConvertible Methods
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to bool is not supported.");
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to char is not supported.");
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to DateTime is not supported.");
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(_value);
}
string IConvertible.ToString(IFormatProvider provider)
{
return ToString("g", provider);
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if(conversionType == typeof(ElectricResistance))
return this;
else if(conversionType == typeof(ElectricResistanceUnit))
return Unit;
else if(conversionType == typeof(QuantityType))
return ElectricResistance.QuantityType;
else if(conversionType == typeof(BaseDimensions))
return ElectricResistance.BaseDimensions;
else
throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to {conversionType} is not supported.");
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(_value);
}
#endregion
}
}
| 44.662017
| 225
| 0.615495
|
[
"MIT"
] |
thomas-chizek/ExtendedSIUnits
|
UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs
| 41,627
|
C#
|
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/WebServices.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public unsafe partial struct WS_HTTP_HEADER_AUTH_SECURITY_BINDING_TEMPLATE
{
public WS_SECURITY_BINDING_PROPERTIES securityBindingProperties;
public WS_WINDOWS_INTEGRATED_AUTH_CREDENTIAL* clientCredential;
}
}
| 37.133333
| 145
| 0.78456
|
[
"MIT"
] |
DaZombieKiller/terrafx.interop.windows
|
sources/Interop/Windows/um/WebServices/WS_HTTP_HEADER_AUTH_SECURITY_BINDING_TEMPLATE.cs
| 559
|
C#
|
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Solutions.Middleware.Telemetry;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Bot.Solutions.Testing.Fakes
{
public class MockLuisRecognizer : ITelemetryLuisRecognizer
{
public MockLuisRecognizer(IRecognizerConvert defaultIntent)
{
TestUtterances = new Dictionary<string, IRecognizerConvert>();
DefaultIntent = defaultIntent;
}
private Dictionary<string, IRecognizerConvert> TestUtterances { get; set; }
private IRecognizerConvert DefaultIntent { get; set; }
public void RegisterUtterances(Dictionary<string, IRecognizerConvert> utterances)
{
foreach (var utterance in utterances)
{
TestUtterances.Add(utterance.Key, utterance.Value);
}
}
public bool LogPersonalInformation => throw new NotImplementedException();
public Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<T> RecognizeAsync<T>(DialogContext dialogContext, CancellationToken cancellationToken = default(CancellationToken))
where T : IRecognizerConvert, new()
{
var text = dialogContext.Context.Activity.Text;
var mockResult = TestUtterances.GetValueOrDefault(text, DefaultIntent);
return Task.FromResult((T)mockResult);
}
public Task<T> RecognizeAsync<T>(ITurnContext turnContext, CancellationToken cancellationToken)
where T : IRecognizerConvert, new()
{
var text = turnContext.Activity.Text;
var mockResult = TestUtterances.GetValueOrDefault(text, DefaultIntent);
return Task.FromResult((T)mockResult);
}
}
}
| 34.929825
| 135
| 0.68006
|
[
"MIT"
] |
dipanjan77/AI
|
solutions/Virtual-Assistant/src/csharp/microsoft.bot.solutions/Testing/Fakes/MockLuisRecognizer.cs
| 1,993
|
C#
|
using System;
using Canon.Eos.Framework.Interfaces;
namespace Canon.Eos.Framework
{
public abstract class EosDisposable : IDisposable, IEosAssertable
{
~EosDisposable()
{
this.Dispose(false);
}
internal protected void CheckDisposed()
{
if (this.IsDisposed)
throw new ObjectDisposedException(this.GetType().Name);
}
internal protected bool IsDisposed { get; private set; }
internal protected virtual void DisposeManaged() { }
internal protected virtual void DisposeUnmanaged() { }
private void Dispose(bool disposing)
{
if (!this.IsDisposed)
{
if (disposing)
this.DisposeManaged();
this.DisposeUnmanaged();
this.IsDisposed = true;
}
}
public void Dispose()
{
this.Dispose(true);
//GC.SuppressFinalize(this);
}
}
}
| 23.744186
| 71
| 0.537708
|
[
"MIT"
] |
BresciMa/digiCamControl
|
Canon.Eos.Framework/EosDisposable.cs
| 1,023
|
C#
|
using System;
using System.Text;
using GammaJul.ReSharper.ForTea.Psi.Directives;
using GammaJul.ReSharper.ForTea.Tree;
using JetBrains.Annotations;
using JetBrains.Application;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.Util;
namespace GammaJul.ReSharper.ForTea.Psi {
/// <summary>This class generates a code-behind file from C# embedded statements and directives in the T4 file.</summary>
internal sealed class T4CSharpCodeGenerator : IRecursiveElementProcessor {
internal const string CodeCommentStart = "/*_T4\x200CCodeStart_*/";
internal const string CodeCommentEnd = "/*_T4\x200CCodeEnd_*/";
internal const string ClassName = "Generated\x200CTransformation";
internal const string DefaultBaseClassName = "Microsoft.VisualStudio.TextTemplating.TextTransformation";
internal const string TransformTextMethodName = "TransformText";
[NotNull] private readonly IT4File _file;
[NotNull] private readonly DirectiveInfoManager _directiveInfoManager;
[NotNull] private readonly GenerationResult _usingsResult;
[NotNull] private readonly GenerationResult _parametersResult;
[NotNull] private readonly GenerationResult _inheritsResult;
[NotNull] private readonly GenerationResult _transformTextResult;
[NotNull] private readonly GenerationResult _featureResult;
private int _includeDepth;
private bool _rootFeatureStarted;
private bool _hasHost;
bool IRecursiveElementProcessor.InteriorShouldBeProcessed(ITreeNode element)
=> element is IT4CodeBlock
|| element is IT4Include;
void IRecursiveElementProcessor.ProcessBeforeInterior(ITreeNode element) {
if (element is IT4Include)
++_includeDepth;
}
void IRecursiveElementProcessor.ProcessAfterInterior(ITreeNode element) {
switch (element) {
case IT4Include _:
--_includeDepth;
return;
case IT4Directive directive:
HandleDirective(directive);
return;
case IT4CodeBlock codeBlock:
HandleCodeBlock(codeBlock);
break;
}
}
bool IRecursiveElementProcessor.ProcessingIsFinished {
get {
InterruptableActivityCookie.CheckAndThrow();
return false;
}
}
/// <summary>Handles a directive in the tree.</summary>
/// <param name="directive">The directive.</param>
private void HandleDirective([NotNull] IT4Directive directive) {
if (directive.IsSpecificDirective(_directiveInfoManager.Import))
HandleImportDirective(directive);
else if (directive.IsSpecificDirective(_directiveInfoManager.Template))
HandleTemplateDirective(directive);
else if (directive.IsSpecificDirective(_directiveInfoManager.Parameter))
HandleParameterDirective(directive);
}
/// <summary>Handles an import directive, equivalent of an using directive in C#.</summary>
/// <param name="directive">The import directive.</param>
private void HandleImportDirective([NotNull] IT4Directive directive) {
Pair<IT4Token, string> ns = directive.GetAttributeValueIgnoreOnlyWhitespace(_directiveInfoManager.Import.NamespaceAttribute.Name);
if (ns.First == null || ns.Second == null)
return;
_usingsResult.Builder.Append("using ");
_usingsResult.AppendMapped(ns.Second, ns.First.GetTreeTextRange());
_usingsResult.Builder.AppendLine(";");
}
/// <summary>Handles a template directive, determining if we should output a Host property and use a base class.</summary>
/// <param name="directive">The template directive.</param>
private void HandleTemplateDirective([NotNull] IT4Directive directive) {
string value = directive.GetAttributeValue(_directiveInfoManager.Template.HostSpecificAttribute.Name);
_hasHost = Boolean.TrueString.Equals(value, StringComparison.OrdinalIgnoreCase);
(IT4Token classNameToken, string className) = directive.GetAttributeValueIgnoreOnlyWhitespace(_directiveInfoManager.Template.InheritsAttribute.Name);
if (classNameToken != null && className != null)
_inheritsResult.AppendMapped(className, classNameToken.GetTreeTextRange());
}
/// <summary>Handles a parameter directive, outputting an extra property.</summary>
/// <param name="directive">The parameter directive.</param>
private void HandleParameterDirective([NotNull] IT4Directive directive) {
(IT4Token typeToken, string type) = directive.GetAttributeValueIgnoreOnlyWhitespace(_directiveInfoManager.Parameter.TypeAttribute.Name);
if (typeToken == null || type == null)
return;
(IT4Token nameToken, string name) = directive.GetAttributeValueIgnoreOnlyWhitespace(_directiveInfoManager.Parameter.NameAttribute.Name);
if (nameToken == null || name == null)
return;
StringBuilder builder = _parametersResult.Builder;
builder.Append("[System.CodeDom.Compiler.GeneratedCodeAttribute] private global::");
_parametersResult.AppendMapped(type, typeToken.GetTreeTextRange());
builder.Append(' ');
_parametersResult.AppendMapped(name, nameToken.GetTreeTextRange());
builder.Append(" { get { return default(global::");
builder.Append(type);
builder.AppendLine("); } }");
}
/// <summary>
/// Handles a code block: depending of whether it's a feature or transform text result,
/// it is not added to the same part of the C# file.
/// </summary>
/// <param name="codeBlock">The code block.</param>
private void HandleCodeBlock([NotNull] IT4CodeBlock codeBlock) {
IT4Token codeToken = codeBlock.GetCodeToken();
if (codeToken == null)
return;
GenerationResult result;
var expressionBlock = codeBlock as T4ExpressionBlock;
if (expressionBlock != null) {
result = _rootFeatureStarted && _includeDepth == 0 ? _featureResult : _transformTextResult;
result.Builder.Append("this.Write(__\x200CToString(");
}
else {
if (codeBlock is T4FeatureBlock) {
if (_includeDepth == 0)
_rootFeatureStarted = true;
result = _featureResult;
}
else
result = _transformTextResult;
}
result.Builder.Append(CodeCommentStart);
result.AppendMapped(codeToken);
result.Builder.Append(CodeCommentEnd);
if (expressionBlock != null)
result.Builder.Append("));");
result.Builder.AppendLine();
}
/// <summary>Gets the namespace of the current T4 file. This is always <c>null</c> for a standard (non-preprocessed) file.</summary>
/// <returns>A namespace, or <c>null</c>.</returns>
[CanBeNull]
private string GetNamespace() {
IPsiSourceFile sourceFile = _file.GetSourceFile();
IProjectFile projectFile = sourceFile?.ToProjectFile();
if (projectFile == null || !projectFile.IsPreprocessedT4Template())
return null;
string ns = projectFile.GetCustomToolNamespace();
if (!String.IsNullOrEmpty(ns))
return ns;
return sourceFile.Properties.GetDefaultNamespace();
}
/// <summary>Generates a new C# code behind.</summary>
/// <returns>An instance of <see cref="GenerationResult"/> containing the C# file.</returns>
[NotNull]
public GenerationResult Generate() {
_file.ProcessDescendants(this);
var result = new GenerationResult(_file);
StringBuilder builder = result.Builder;
string ns = GetNamespace();
bool hasNamespace = !String.IsNullOrEmpty(ns);
if (hasNamespace) {
builder.AppendFormat("namespace {0} {{", ns);
builder.AppendLine();
}
builder.AppendLine("using System;");
result.Append(_usingsResult);
builder.AppendFormat("[{0}]", SyntheticAttribute.Name);
builder.AppendLine();
builder.AppendFormat("public class {0} : ", ClassName);
if (_inheritsResult.Builder.Length == 0)
builder.Append(DefaultBaseClassName);
else {
result.Append(_inheritsResult);
}
builder.AppendLine(" {");
builder.AppendFormat("[{0}] private static string __\x200CToString(object value) {{ return null; }}", SyntheticAttribute.Name);
builder.AppendLine();
if (_hasHost)
builder.AppendLine("public virtual Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost Host { get; set; }");
result.Append(_parametersResult);
builder.AppendFormat("[System.CodeDom.Compiler.GeneratedCodeAttribute] public override string {0}() {{", TransformTextMethodName);
builder.AppendLine();
result.Append(_transformTextResult);
builder.AppendLine();
builder.AppendLine("return GenerationEnvironment.ToString();");
builder.AppendLine("}");
result.Append(_featureResult);
builder.AppendLine("}");
if (hasNamespace)
builder.AppendLine("}");
return result;
}
/// <summary>Initializes a new instance of the <see cref="T4CSharpCodeGenerator"/> class.</summary>
/// <param name="file">The associated T4 file whose C# code behind will be generated.</param>
/// <param name="directiveInfoManager">An instance of <see cref="DirectiveInfoManager"/>.</param>
public T4CSharpCodeGenerator([NotNull] IT4File file, [NotNull] DirectiveInfoManager directiveInfoManager) {
_file = file;
_directiveInfoManager = directiveInfoManager;
_usingsResult = new GenerationResult(file);
_parametersResult = new GenerationResult(file);
_inheritsResult = new GenerationResult(file);
_transformTextResult = new GenerationResult(file);
_featureResult = new GenerationResult(file);
}
}
}
| 39.446352
| 152
| 0.747035
|
[
"Apache-2.0"
] |
ForNeVeR/ForTea
|
dotnet/source/GammaJul.ReSharper.ForTea/Psi/T4CSharpCodeGenerator.cs
| 9,191
|
C#
|
using System;
using System.Threading.Tasks;
namespace loadify.Spotify
{
public static class SpotifyObject
{
public static Task<bool> WaitForInitialization(Func<bool> func)
{
return Task.Factory.StartNew(() =>
{
while (true)
{
if (func())
return true;
};
});
}
}
}
| 20.47619
| 71
| 0.446512
|
[
"MIT"
] |
LukiLeu/loadify
|
src/loadify/Spotify/SpotifyObject.cs
| 432
|
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("BoxViewCircle.Windows")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BoxViewCircle.Windows")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)]
| 36.482759
| 84
| 0.744802
|
[
"Apache-2.0"
] |
aliozgur/xamarin-forms-book-samples
|
Chapter21/BoxViewCircle/BoxViewCircle/BoxViewCircle.Windows/Properties/AssemblyInfo.cs
| 1,059
|
C#
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Ev.ServiceBus.Abstractions;
using Ev.ServiceBus.Management;
using Ev.ServiceBus.Reception;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Ev.ServiceBus
{
public class ServiceBusEngine
{
private readonly ILogger<ServiceBusEngine> _logger;
private readonly IOptions<ServiceBusOptions> _options;
private readonly IServiceProvider _provider;
private readonly ServiceBusRegistry _registry;
public ServiceBusEngine(ILogger<ServiceBusEngine> logger,
IOptions<ServiceBusOptions> options,
ServiceBusRegistry registry,
IServiceProvider provider)
{
_logger = logger;
_options = options;
_registry = registry;
_provider = provider;
}
public void StartAll()
{
_logger.LogInformation("[Ev.ServiceBus] Starting azure service bus clients");
if (_options.Value.Settings.Enabled == false)
{
_logger.LogInformation("[Ev.ServiceBus] Reception and dispatch of messages have been deactivated through configuration.");
}
if (_options.Value.Settings.Enabled && _options.Value.Settings.ReceiveMessages == false)
{
_logger.LogInformation("[Ev.ServiceBus] Reception of messages have been deactivated through configuration.");
}
BuildSenders();
BuildReceivers();
BuildReceptions();
BuildDispatches();
}
private void BuildDispatches()
{
var doubleRegistrations = _options.Value.DispatchRegistrations.GroupBy(o => o).Where(o => o.Count() > 1).ToArray();
if (doubleRegistrations.Any())
{
throw new MultiplePublicationRegistrationException(doubleRegistrations.Select(o => o.Key.ToString()).ToArray());
}
foreach (var group in _options.Value.DispatchRegistrations.GroupBy(o => o.PayloadType))
{
_registry.Register(group.Key, group.ToArray());
}
}
private void BuildReceptions()
{
var regs = _options.Value.ReceptionRegistrations.ToArray();
var duplicatedHandlers = regs.GroupBy(o => new { o.Options.ClientType,
o.Options.ResourceId, o.HandlerType }).Where(o => o.Count() > 1).ToArray();
if (duplicatedHandlers.Any())
{
throw new DuplicateSubscriptionHandlerDeclarationException(duplicatedHandlers.SelectMany(o => o).ToArray());
}
var duplicateEvenTypeIds = regs.GroupBy(o => new {o.Options.ClientType,
o.Options.ResourceId, EventTypeId = o.PayloadTypeId}).Where(o => o.Count() > 1).ToArray();
if (duplicateEvenTypeIds.Any())
{
throw new DuplicateEvenTypeIdDeclarationException(duplicateEvenTypeIds.SelectMany(o => o).ToArray());
}
foreach (var registration in regs)
{
_registry.Register(registration);
}
}
private void BuildReceivers()
{
// filtering out receivers that have no message handlers setup
var receivers = _options.Value.Receivers.Where(o => o.MessageHandlerType != null).ToArray();
var duplicateReceivers = receivers.Where(o => o.StrictMode)
.GroupBy(o => new { o.ResourceId, o.ClientType })
.Where(o => o.Count() > 1).ToArray();
// making sure there's not any duplicates in strict mode
if (duplicateReceivers.Any())
{
throw new DuplicateReceiverRegistrationException(duplicateReceivers
.Select(o => $"{o.Key.ClientType}|{o.Key.ResourceId}").ToArray());
}
var receiversByName = receivers.GroupBy(o => new { o.ResourceId, o.ClientType }).ToArray();
foreach (var groupByName in receiversByName)
{
// we group by connection to have one SenderWrapper by connection
// we order by StrictMode so their name will be resolved first and avoid exceptions
foreach (var groupByConnection in groupByName.GroupBy(o => o.ConnectionSettings)
.OrderByDescending(o => o.Any(opts => opts.StrictMode)))
{
RegisterReceiver(groupByConnection.ToArray());
}
}
}
private void RegisterReceiver(ReceiverOptions[] receivers)
{
var resourceId = receivers.First().ResourceId;
var clientType = receivers.First().ClientType;
if (_registry.IsReceiverResourceIdTaken(clientType, resourceId))
{
resourceId = GetNewReceiverResourceId(clientType, resourceId);
foreach (var sender in receivers)
{
sender.UpdateResourceId(resourceId);
}
}
var receiverWrapper = new ReceiverWrapper(receivers.Cast<IMessageReceiverOptions>().ToArray(),
_options.Value, _provider);
receiverWrapper.Initialize();
_registry.Register(receiverWrapper);
}
private string GetNewReceiverResourceId(ClientType clientType, string resourceId)
{
var newResourceId = resourceId;
var suffix = 2;
while (_registry.IsReceiverResourceIdTaken(clientType, newResourceId))
{
newResourceId = $"{resourceId}_{suffix}";
++suffix;
}
return newResourceId;
}
private void BuildSenders()
{
var senders = _options.Value.Senders;
var duplicateSenders = senders.Where(o => o.StrictMode)
.GroupBy(o => new { o.ResourceId, o.ClientType })
.Where(o => o.Count() > 1).ToArray();
// making sure there's not any duplicates in strict mode
if (duplicateSenders.Any())
{
throw new DuplicateSenderRegistrationException(duplicateSenders
.Select(o => $"{o.Key.ClientType}|{o.Key.ResourceId}").ToArray());
}
var sendersByName = senders.GroupBy(o => new { o.ResourceId, o.ClientType }).ToArray();
foreach (var groupByName in sendersByName)
{
// we group by connection to have one SenderWrapper by connection
// we order by StrictMode so their name will be resolved first and avoid exceptions
foreach (var groupByConnection in groupByName.GroupBy(o => o.ConnectionSettings)
.OrderByDescending(o => o.Any(opts => opts.StrictMode)))
{
RegisterSender(groupByConnection.ToArray());
}
}
}
private void RegisterSender(ClientOptions[] senders)
{
var resourceId = senders.First().ResourceId;
var clientType = senders.First().ClientType;
if (_registry.IsSenderResourceIdTaken(clientType, resourceId))
{
resourceId = GetNewSenderResourceId(clientType, resourceId);
foreach (var sender in senders)
{
sender.UpdateResourceId(resourceId);
}
}
var senderWrapper = new SenderWrapper(senders.Cast<IClientOptions>().ToArray(), _options.Value, _provider);
senderWrapper.Initialize();
_registry.Register(senderWrapper);
}
private string GetNewSenderResourceId(ClientType clientType, string resourceId)
{
var newResourceId = resourceId;
var suffix = 2;
while (_registry.IsSenderResourceIdTaken(clientType, newResourceId))
{
newResourceId = $"{resourceId}_{suffix}";
++suffix;
}
return newResourceId;
}
public async Task StopAll()
{
_logger.LogInformation("[Ev.ServiceBus] Stopping azure service bus clients");
await Task.WhenAll(_registry.GetAllSenders().Select(CloseSenderAsync).ToArray()).ConfigureAwait(false);
await Task.WhenAll(_registry.GetAllReceivers().Select(CloseReceiverAsync).ToArray()).ConfigureAwait(false);
}
private async Task CloseSenderAsync(SenderWrapper sender)
{
if (sender.SenderClient == null)
{
return;
}
if (sender.SenderClient.IsClosedOrClosing)
{
return;
}
try
{
await sender.SenderClient.CloseAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, $"[Ev.ServiceBus] Closing of client {sender.ResourceId} failed");
}
}
private async Task CloseReceiverAsync(ReceiverWrapper receiver)
{
if (receiver.ReceiverClient == null)
{
return;
}
if (receiver.ReceiverClient.IsClosedOrClosing)
{
return;
}
try
{
await receiver.ReceiverClient.CloseAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, $"[Ev.ServiceBus] Closing of client {receiver.ResourceId} failed");
}
}
}
}
| 37.88716
| 138
| 0.570812
|
[
"MIT"
] |
EcovadisCode/Ev.ServiceBus
|
src/Ev.ServiceBus/ServiceBusEngine.cs
| 9,739
|
C#
|
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.Integrations
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Display_OptionObjectType : INotifyPropertyChanged
{
private Display_OptionObjectIDType[] idField;
private string descriptorField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement("ID", Order = 0)]
public Display_OptionObjectIDType[] ID
{
get
{
return this.idField;
}
set
{
this.idField = value;
this.RaisePropertyChanged("ID");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Descriptor
{
get
{
return this.descriptorField;
}
set
{
this.descriptorField = value;
this.RaisePropertyChanged("Descriptor");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 21.934426
| 136
| 0.733184
|
[
"MIT"
] |
matteofabbri/Workday.WebServices
|
Workday.Integrations/Display_OptionObjectType.cs
| 1,338
|
C#
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TestCharts.Data;
using TestCharts.Services;
namespace TestCharts
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddTransient<IDashboardService, DashboardService>();
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();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// 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.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 35.693333
| 143
| 0.621965
|
[
"MIT"
] |
n3v3r94/JustChart
|
TestCharts/Startup.cs
| 2,679
|
C#
|
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.450)
// Version 5.450.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
[assembly: AssemblyVersion("5.450.738.0")]
[assembly: AssemblyFileVersion("5.450.738.0")]
[assembly: AssemblyInformationalVersion("5.450.738.0")]
[assembly: AssemblyCopyright("© Component Factory Pty Ltd, 2006 - 2016. Then modifications by Peter Wagner (aka Wagnerp) & Simon Coghlan (aka Smurf-IV) 2017 - 2020. All rights reserved.")]
[assembly: AssemblyProduct("Krypton Workspace")]
[assembly: AssemblyDefaultAlias("ComponentFactory.Krypton.Workspace.dll")]
[assembly: AssemblyTitle("ComponentFactory.Krypton.Workspace")]
[assembly: AssemblyCompany("Component Factory Pty Ltd, Peter Wagner (aka Wagnerp) & Simon Coghlan (aka Smurf-IV)")]
[assembly: AssemblyDescription("ComponentFactory.Krypton.Workspace")]
[assembly: AssemblyConfiguration("Production")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: StringFreezing]
[assembly: ComVisible(true)]
[assembly: CLSCompliant(true)]
[assembly: AllowPartiallyTrustedCallers()]
[assembly: Dependency("System", LoadHint.Always)]
[assembly: Dependency("System.Drawing", LoadHint.Always)]
[assembly: Dependency("System.Windows.Forms", LoadHint.Always)]
[assembly: Dependency("System.XML", LoadHint.Always)]
[assembly: Dependency("ComponentFactory.Krypton.Toolkit", LoadHint.Always)]
[assembly: Dependency("ComponentFactory.Krypton.Navigator", LoadHint.Always)]
[assembly: SecurityRules(SecurityRuleSet.Level1)]
| 57.175
| 188
| 0.728465
|
[
"BSD-3-Clause"
] |
Krypton-Suite-Legacy-Archive/Krypton-NET-5.450
|
Source/Krypton Components/ComponentFactory.Krypton.Workspace/Properties/AssemblyInfo.cs
| 2,291
|
C#
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace WebWithAngular.Migrations
{
public partial class Upgrade_ABP_381 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AbpUserTokens",
maxLength: 128,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 64,
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AbpUserTokens",
maxLength: 64,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 128,
oldNullable: true);
}
}
}
| 29.75
| 71
| 0.542017
|
[
"MIT"
] |
Rdh9810/ABPwithAngular
|
aspnet-core/src/WebWithAngular.EntityFrameworkCore/Migrations/20180731132139_Upgrade_ABP_3.8.1.cs
| 954
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class WCompany_payResult : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string timestamp = (Request.Headers["timestamp"] == null) ? "" : Request.Headers["timestamp"].ToString();
string tokenT = (Request.Headers["token"] == null) ? "" : Request.Headers["token"].ToString();
string param = string.Format("secretKey={0}×tamp={1}"
, PayConfig.secretKey, timestamp);
string token = FormsAuthentication.HashPasswordForStoringInConfigFile(param, "SHA1");
if (token == tokenT)
{
string requestNum = (Request["requestNum"] == null) ? "" : Request["requestNum"].ToString();
string orderNum = (Request["orderNum"] == null) ? "" : Request["orderNum"].ToString();
string orderAmount = (Request["orderAmount"] == null) ? "" : Request["orderAmount"].ToString();
string status = (Request["status"] == null) ? "" : Request["status"].ToString();
string completeTime = (Request["completeTime"] == null) ? "" : Request["completeTime"].ToString();
///
///TODO:获取到相关数据,做一系列操作
///
}
}
}
| 35.947368
| 113
| 0.61347
|
[
"MIT"
] |
dlbxiaoer/dlb
|
CShareDemo/payResult.aspx.cs
| 1,398
|
C#
|
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Altinn.Authorization.ABAC.Xacml;
using Altinn.Authorization.ABAC.Xacml.JsonProfile;
namespace App.IntegrationTests.Mocks.Services
{
public class PepAuthorizationMockSI : Altinn.Common.PEP.Interfaces.IPDP
{
public Task<XacmlJsonResponse> GetDecisionForRequest(XacmlJsonRequestRoot xacmlJsonRequest)
{
List<XacmlJsonCategory> resources = xacmlJsonRequest.Request.Resource;
XacmlJsonAttribute attribute = resources.Select(r => r.Attribute.Find(a => a.Value.Equals("endring-av-navn"))).FirstOrDefault();
// Create response and result
XacmlJsonResponse response = new XacmlJsonResponse();
response.Response = new List<XacmlJsonResult>();
XacmlJsonResult result = new XacmlJsonResult();
if (attribute != null)
{
// Set decision to permit
result.Decision = XacmlContextDecision.Permit.ToString();
response.Response.Add(result);
return Task.FromResult(response);
}
XacmlJsonAttribute attribute2 = resources.Select(r => r.Attribute.Find(a => a.Value.Equals("multiple-results"))).FirstOrDefault();
if (attribute2 != null)
{
// Set decision to permit
result.Decision = XacmlContextDecision.Permit.ToString();
response.Response.Add(result);
response.Response.Add(new XacmlJsonResult());
return Task.FromResult(response);
}
XacmlJsonAttribute attribute3 = resources.Select(r => r.Attribute.Find(a => a.Value.Equals("auth-level-2"))).FirstOrDefault();
if (attribute3 != null)
{
// Set decision to permit
result.Decision = XacmlContextDecision.Permit.ToString();
response.Response.Add(result);
// Add obligation to result with a minimum authentication level attribute
XacmlJsonObligationOrAdvice obligation = new XacmlJsonObligationOrAdvice();
obligation.AttributeAssignment = new List<XacmlJsonAttributeAssignment>();
XacmlJsonAttributeAssignment authenticationAttribute = new XacmlJsonAttributeAssignment()
{
Category = "urn:altinn:minimum-authenticationlevel",
Value = "2"
};
obligation.AttributeAssignment.Add(authenticationAttribute);
result.Obligations = new List<XacmlJsonObligationOrAdvice>();
result.Obligations.Add(obligation);
return Task.FromResult(response);
}
XacmlJsonAttribute attribute4 = resources.Select(r => r.Attribute.Find(a => a.Value.Equals("auth-level-3"))).FirstOrDefault();
if (attribute4 != null)
{
// Set decision to permit
result.Decision = XacmlContextDecision.Permit.ToString();
response.Response.Add(result);
// Add obligation to result with a minimum authentication level attribute
XacmlJsonObligationOrAdvice obligation = new XacmlJsonObligationOrAdvice();
obligation.AttributeAssignment = new List<XacmlJsonAttributeAssignment>();
XacmlJsonAttributeAssignment authenticationAttribute = new XacmlJsonAttributeAssignment()
{
Category = "urn:altinn:minimum-authenticationlevel",
Value = "3"
};
obligation.AttributeAssignment.Add(authenticationAttribute);
result.Obligations = new List<XacmlJsonObligationOrAdvice>();
result.Obligations.Add(obligation);
return Task.FromResult(response);
}
// Set decision to deny
result.Decision = XacmlContextDecision.Deny.ToString();
response.Response.Add(result);
return Task.FromResult(response);
}
public Task<bool> GetDecisionForUnvalidateRequest(XacmlJsonRequestRoot xacmlJsonRequest, ClaimsPrincipal user)
{
return Task.FromResult(true);
}
}
}
| 41.865385
| 142
| 0.617593
|
[
"BSD-3-Clause"
] |
andreas-rafaelsen/altinn-studio
|
src/Altinn.Apps/AppTemplates/AspNet/App.IntegrationTests/Mocks/Services/PepAuthorizationMockSI.cs
| 4,354
|
C#
|
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace Command.Business
{
/// <summary>
///
/// </summary>
public sealed class CommandExecuteResponse : CommandExecuteRequest
{
#region Fields
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CommandExecuteResponse" /> class.
/// </summary>
/// <param name="relatedRequest">The related request.</param>
public CommandExecuteResponse(CommandExecuteRequest relatedRequest)
{
if (relatedRequest != null)
{
Name = relatedRequest.Name;
Category = relatedRequest.Category;
Parameters = relatedRequest.Parameters;
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether [success].
/// </summary>
public bool Success { get; set; }
/// <summary>
/// Gets the response result.
/// </summary>
public object Response { get; set; }
#endregion
#region Methods
/// <summary>
/// Gets the body of the payload as an xml fragment.
/// </summary>
/// <returns></returns>
public override XElement GetPayloadAsXml()
{
XElement parameters = new XElement("Parameters");
foreach (CommandParameter parameter in Parameters)
parameters.Add(new XElement("Parameter", new XAttribute("Name", parameter.Name), new XAttribute("Value", parameter.Value)));
XElement response = null;
if (Response != null)
{
string xml = Serialize(Response);
response = XElement.Parse(xml);
}
XElement result = new XElement("CommandExecuteResponse",
new XElement("Category", Category),
new XElement("Name", Name),
parameters,
new XElement("Success", Success));
if (response != null) result.Add(response);
return result;
}
private string Serialize(object objectToSerialize)
{
if (objectToSerialize == null) return string.Empty;
using (MemoryStream stream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(objectToSerialize.GetType());
serializer.WriteObject(stream, objectToSerialize);
stream.Seek(0, SeekOrigin.Begin);
StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
#endregion
}
}
| 33.73494
| 140
| 0.558571
|
[
"MIT"
] |
rahilkidwai/CommandService
|
Command.Business/CommandExecuteResponse.cs
| 2,802
|
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the appstream-2016-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AppStream.Model
{
/// <summary>
/// Container for the parameters to the StopFleet operation.
/// Deactivates a fleet.
/// </summary>
public partial class StopFleetRequest : AmazonAppStreamRequest
{
private string _name;
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the fleet to deactivate.
/// </para>
/// </summary>
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;
}
}
}
| 28.070175
| 107
| 0.644375
|
[
"Apache-2.0"
] |
Bynder/aws-sdk-net
|
sdk/src/Services/AppStream/Generated/Model/StopFleetRequest.cs
| 1,600
|
C#
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace ProsperiDevLab.Data.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Currencies",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Code = table.Column<string>(type: "nvarchar(3)", maxLength: 3, nullable: false),
Symbol = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Currencies", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Customers",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(255)", maxLength: 255, nullable: false),
CNPJ = table.Column<string>(type: "nvarchar(14)", maxLength: 14, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Customers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Employees",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(255)", maxLength: 255, nullable: false),
CPF = table.Column<string>(type: "nvarchar(11)", maxLength: 11, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Employees", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Prices",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Value = table.Column<decimal>(type: "decimal(12,2)", precision: 12, scale: 2, nullable: false),
CurrencyId = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Prices", x => x.Id);
table.ForeignKey(
name: "FK_Prices_Currencies_CurrencyId",
column: x => x.CurrencyId,
principalTable: "Currencies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ServiceOrders",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Number = table.Column<string>(type: "nvarchar(63)", maxLength: 63, nullable: false),
ExecutionDate = table.Column<DateTime>(type: "datetime2", nullable: false),
PriceId = table.Column<long>(type: "bigint", nullable: false),
EmployeeId = table.Column<long>(type: "bigint", nullable: false),
CustomerId = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ServiceOrders", x => x.Id);
table.ForeignKey(
name: "FK_ServiceOrders_Customers_CustomerId",
column: x => x.CustomerId,
principalTable: "Customers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ServiceOrders_Employees_EmployeeId",
column: x => x.EmployeeId,
principalTable: "Employees",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ServiceOrders_Prices_PriceId",
column: x => x.PriceId,
principalTable: "Prices",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.InsertData(
table: "Currencies",
columns: new[] { "Id", "Code", "Name", "Symbol" },
values: new object[] { 1L, "BRL", "Real", "R$" });
migrationBuilder.InsertData(
table: "Currencies",
columns: new[] { "Id", "Code", "Name", "Symbol" },
values: new object[] { 2L, "USD", "Dollar", "$" });
migrationBuilder.InsertData(
table: "Currencies",
columns: new[] { "Id", "Code", "Name", "Symbol" },
values: new object[] { 3L, "EUR", "Euro", "€" });
migrationBuilder.CreateIndex(
name: "IX_Currencies_Code",
table: "Currencies",
column: "Code",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Customers_CNPJ",
table: "Customers",
column: "CNPJ",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Employees_CPF",
table: "Employees",
column: "CPF",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Prices_CurrencyId",
table: "Prices",
column: "CurrencyId");
migrationBuilder.CreateIndex(
name: "IX_ServiceOrders_CustomerId",
table: "ServiceOrders",
column: "CustomerId");
migrationBuilder.CreateIndex(
name: "IX_ServiceOrders_EmployeeId",
table: "ServiceOrders",
column: "EmployeeId");
migrationBuilder.CreateIndex(
name: "IX_ServiceOrders_Number",
table: "ServiceOrders",
column: "Number",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_ServiceOrders_PriceId",
table: "ServiceOrders",
column: "PriceId",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ServiceOrders");
migrationBuilder.DropTable(
name: "Customers");
migrationBuilder.DropTable(
name: "Employees");
migrationBuilder.DropTable(
name: "Prices");
migrationBuilder.DropTable(
name: "Currencies");
}
}
}
| 40.68617
| 115
| 0.47065
|
[
"MIT"
] |
lrmendess/ProsperiDevLab
|
ProsperiDevLab/Data/Migrations/20210607144919_Initial.cs
| 7,653
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Charlotte.GameCommons;
namespace Charlotte.Games.Surfaces
{
public class Surface_MessageWindow : Surface
{
public static bool Hide = false; // Game から制御される。
private double A = 1.0;
public Surface_MessageWindow()
{
this.Z = 60000;
}
public override void Draw()
{
const int h = 272;
DDUtils.Approach(ref this.A, Hide ? 0.0 : 1.0, 0.9);
DDDraw.SetAlpha(this.A);
DDDraw.DrawRect(Ground.I.Picture.MessageFrame_Message, 0, DDConsts.Screen_H - h, DDConsts.Screen_W, h);
DDDraw.Reset();
}
}
}
| 19.40625
| 106
| 0.698873
|
[
"MIT"
] |
soleil-taruto/Elsa
|
e20201017_NovelAdv_Base/Elsa20200001/Elsa20200001/Games/Surfaces/Surface_MessageWindow.cs
| 639
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace CallingDotNetFromJavaScript
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 22.793103
| 64
| 0.75643
|
[
"MIT"
] |
BlazorHub/blazor-university
|
src/JavaScriptInterop/CallingDotNetFromJavaScript/Program.cs
| 661
|
C#
|
//
namespace WeatherViewerApplication.Module
{
using Infrastructure;
using Prism.Modularity;
using Prism.Regions;
public class TopLevelModule : IModule
{
private readonly IRegionViewRegistry _regionViewRegistry;
public TopLevelModule(IRegionViewRegistry regionViewRegistry)
{
_regionViewRegistry = regionViewRegistry;
}
public void Initialize()
{
_regionViewRegistry.RegisterViewWithRegion(Constants.ContentRegion, typeof(Views.TopLevelContent));
}
}
}
| 25.454545
| 111
| 0.683929
|
[
"Apache-2.0"
] |
uk-mashfield/WeatherApp2
|
WeatherViewerApplication/Module/TopLevelModule.cs
| 562
|
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 Mosa.Tool.Debugger.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", "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>
/// 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("Mosa.Tool.Debugger.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 application_view_columns {
get {
object obj = ResourceManager.GetObject("application_view_columns", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap application_view_list {
get {
object obj = ResourceManager.GetObject("application_view_list", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_refresh {
get {
object obj = ResourceManager.GetObject("arrow_refresh", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap connect {
get {
object obj = ResourceManager.GetObject("connect", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_cursor {
get {
object obj = ResourceManager.GetObject("control_cursor", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_eject {
get {
object obj = ResourceManager.GetObject("control_eject", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_end {
get {
object obj = ResourceManager.GetObject("control_end", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_equalizer {
get {
object obj = ResourceManager.GetObject("control_equalizer", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_fastforward {
get {
object obj = ResourceManager.GetObject("control_fastforward", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_pause {
get {
object obj = ResourceManager.GetObject("control_pause", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_play {
get {
object obj = ResourceManager.GetObject("control_play", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_power {
get {
object obj = ResourceManager.GetObject("control_power", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_repeat {
get {
object obj = ResourceManager.GetObject("control_repeat", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_rewind {
get {
object obj = ResourceManager.GetObject("control_rewind", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_start {
get {
object obj = ResourceManager.GetObject("control_start", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap control_stop {
get {
object obj = ResourceManager.GetObject("control_stop", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap document_inspect {
get {
object obj = ResourceManager.GetObject("document_inspect", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap font_red_delete {
get {
object obj = ResourceManager.GetObject("font_red_delete", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_add {
get {
object obj = ResourceManager.GetObject("layer_add", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_create {
get {
object obj = ResourceManager.GetObject("layer_create", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_delete {
get {
object obj = ResourceManager.GetObject("layer_delete", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_edit {
get {
object obj = ResourceManager.GetObject("layer_edit", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_export {
get {
object obj = ResourceManager.GetObject("layer_export", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_group {
get {
object obj = ResourceManager.GetObject("layer_group", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_import {
get {
object obj = ResourceManager.GetObject("layer_import", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_open {
get {
object obj = ResourceManager.GetObject("layer_open", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_redraw {
get {
object obj = ResourceManager.GetObject("layer_redraw", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_remove {
get {
object obj = ResourceManager.GetObject("layer_remove", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap layer_save {
get {
object obj = ResourceManager.GetObject("layer_save", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap page_gear {
get {
object obj = ResourceManager.GetObject("page_gear", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap page_refresh {
get {
object obj = ResourceManager.GetObject("page_refresh", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap rocket {
get {
object obj = ResourceManager.GetObject("rocket", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap save_document {
get {
object obj = ResourceManager.GetObject("save_document", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap zoom_layer {
get {
object obj = ResourceManager.GetObject("zoom_layer", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 38.69802
| 184
| 0.5481
|
[
"BSD-3-Clause"
] |
napalmtorch/MOSA-Project
|
Source/Mosa.Tool.Debugger/Properties/Resources.Designer.cs
| 15,636
|
C#
|
namespace HOLMS.Types.Primitive {
public partial class ServerActionConfirmation {
public ServerActionConfirmation(bool result) {
ActionSuccessful = result;
}
}
}
| 22.222222
| 54
| 0.66
|
[
"MIT"
] |
PietroProperties/holms.platformclient.net
|
csharp/HOLMS.Platform/HOLMS.Platform/Types/Primitive/ServerActionConfirmation.cs
| 202
|
C#
|
using System.Windows;
namespace MinimalMVVM.Views
{
/// <summary>
/// Interaction logic for TwitterBrowser.xaml
/// </summary>
public partial class TwitterBrowserView : Window
{
public TwitterBrowserView()
{
InitializeComponent();
TwitterBrowserViewModel twitterBrowserViewModel = new TwitterBrowserViewModel();
this.DataContext = twitterBrowserViewModel;
}
}
}
| 24.888889
| 92
| 0.645089
|
[
"MIT"
] |
Pepsi4/MVVM-Twitter
|
MinimalMVVM/Views/TwitterBrowserView.xaml.cs
| 450
|
C#
|
using System;
namespace TheCodingMonkey.Serialization.Tests.Models
{
[TextSerializable]
public class CsvWithOptionsRecord
{
[TextField(0)]
public int Id { get; set; }
[TextField(1)]
public string Name { get; set; }
[TextField(2)]
public string Description { get; set; }
[TextField(3)]
public double Value { get; set; }
[TextField(4, Optional = true)]
public bool Enabled { get; set; }
}
}
| 25.578947
| 52
| 0.580247
|
[
"MIT"
] |
JTOne123/TextSerializer
|
Tests/Models/CsvWithOptionsRecord.cs
| 488
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindBarrierReinforcement.DataModels.NSPage04
{
public enum EZonePosition
{
Start,
Middle,
End
}
}
| 16.375
| 54
| 0.698473
|
[
"Apache-2.0"
] |
vbuweb123/windturbine3Dreinforcement
|
WindBarrierReinforcement/DataModels/NSPage04/EZonePosition.cs
| 264
|
C#
|
using System;
namespace NETAPI.Models
{
public class ResponseBase<T>
{
public bool Success { get; set; }
public string? Message { get; set; }
public virtual T? Data { get; set; }
public virtual Exception? Exception { get; set; }
}
}
| 21.461538
| 57
| 0.591398
|
[
"MIT"
] |
abnegate/dotnet-netapi
|
NETAPI/Model/Response.cs
| 281
|
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 cbpsDBjsonPOC.Properties {
/// <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", "4.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 ((resourceMan == null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("cbpsDBjsonPOC.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;
}
}
}
}
| 43.888889
| 180
| 0.607595
|
[
"MIT"
] |
SmilingAngelsTea/SATSONMaid
|
Properties/Resources.Designer.cs
| 2,767
|
C#
|
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApi.Entities
{
public class Patient
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DoB { get; set; }
public string NHSno { get; set; }
public string CPMSno { get; set; }
public string Notes { get; set; }
public virtual Appointment Appointment{get; set;}
}
}
| 25.45
| 57
| 0.59332
|
[
"MIT"
] |
whitie11/CTT_WebAPI
|
Entities/Patient.cs
| 509
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using Adaptive.ReactiveTrader.Client.Domain.Models.ReferenceData;
using Adaptive.ReactiveTrader.Client.Domain.ServiceClients;
namespace Adaptive.ReactiveTrader.Client.Domain.Repositories
{
class ReferenceDataRepository : IReferenceDataRepository
{
private readonly IReferenceDataServiceClient _referenceDataServiceClient;
private readonly ICurrencyPairUpdateFactory _currencyPairUpdateFactory;
public ReferenceDataRepository(IReferenceDataServiceClient referenceDataServiceClient, ICurrencyPairUpdateFactory currencyPairUpdateFactory)
{
_referenceDataServiceClient = referenceDataServiceClient;
_currencyPairUpdateFactory = currencyPairUpdateFactory;
}
public IObservable<IEnumerable<ICurrencyPairUpdate>> GetCurrencyPairsStream()
{
return Observable.Defer(() => _referenceDataServiceClient.GetCurrencyPairUpdatesStream())
.Where(updates => updates.Any())
.Select(updates => updates.Select(update => _currencyPairUpdateFactory.Create(update)))
.Catch(Observable.Return(new ICurrencyPairUpdate[0])) // if the stream errors (server disconnected), we push an empty list of ccy pairs
.Repeat() // and resubscribe
.Publish()
.RefCount();
}
}
}
| 45.424242
| 154
| 0.698466
|
[
"Apache-2.0"
] |
Applied-Duality/ReactiveTrader
|
src/Adaptive.ReactiveTrader.Client.Domain/Repositories/ReferenceDataRepository.cs
| 1,501
|
C#
|
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.Payroll.Interface
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Local_Person_Name_Detail_DataType : INotifyPropertyChanged
{
private string first_NameField;
private string middle_NameField;
private string last_NameField;
private string secondary_Last_NameField;
private string first_Name_2Field;
private string middle_Name_2Field;
private string last_Name_2Field;
private string secondary_Last_Name_2Field;
private string local_NameField;
private string local_ScriptField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement(Order = 0)]
public string First_Name
{
get
{
return this.first_NameField;
}
set
{
this.first_NameField = value;
this.RaisePropertyChanged("First_Name");
}
}
[XmlElement(Order = 1)]
public string Middle_Name
{
get
{
return this.middle_NameField;
}
set
{
this.middle_NameField = value;
this.RaisePropertyChanged("Middle_Name");
}
}
[XmlElement(Order = 2)]
public string Last_Name
{
get
{
return this.last_NameField;
}
set
{
this.last_NameField = value;
this.RaisePropertyChanged("Last_Name");
}
}
[XmlElement(Order = 3)]
public string Secondary_Last_Name
{
get
{
return this.secondary_Last_NameField;
}
set
{
this.secondary_Last_NameField = value;
this.RaisePropertyChanged("Secondary_Last_Name");
}
}
[XmlElement(Order = 4)]
public string First_Name_2
{
get
{
return this.first_Name_2Field;
}
set
{
this.first_Name_2Field = value;
this.RaisePropertyChanged("First_Name_2");
}
}
[XmlElement(Order = 5)]
public string Middle_Name_2
{
get
{
return this.middle_Name_2Field;
}
set
{
this.middle_Name_2Field = value;
this.RaisePropertyChanged("Middle_Name_2");
}
}
[XmlElement(Order = 6)]
public string Last_Name_2
{
get
{
return this.last_Name_2Field;
}
set
{
this.last_Name_2Field = value;
this.RaisePropertyChanged("Last_Name_2");
}
}
[XmlElement(Order = 7)]
public string Secondary_Last_Name_2
{
get
{
return this.secondary_Last_Name_2Field;
}
set
{
this.secondary_Last_Name_2Field = value;
this.RaisePropertyChanged("Secondary_Last_Name_2");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Local_Name
{
get
{
return this.local_NameField;
}
set
{
this.local_NameField = value;
this.RaisePropertyChanged("Local_Name");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Local_Script
{
get
{
return this.local_ScriptField;
}
set
{
this.local_ScriptField = value;
this.RaisePropertyChanged("Local_Script");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 18.248677
| 136
| 0.694114
|
[
"MIT"
] |
matteofabbri/Workday.WebServices
|
Workday.Payroll.Interface/Local_Person_Name_Detail_DataType.cs
| 3,449
|
C#
|
// <auto-generated/>
#pragma warning disable 1591
#pragma warning disable 0414
#pragma warning disable 0649
#pragma warning disable 0169
namespace Demo_04.Pages
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "E:\Packt\ch04\Demo_04\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "E:\Packt\ch04\Demo_04\_Imports.razor"
using System.Net.Http.Json;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "E:\Packt\ch04\Demo_04\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "E:\Packt\ch04\Demo_04\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "E:\Packt\ch04\Demo_04\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "E:\Packt\ch04\Demo_04\_Imports.razor"
using Microsoft.AspNetCore.Components.Web.Virtualization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "E:\Packt\ch04\Demo_04\_Imports.razor"
using Microsoft.AspNetCore.Components.WebAssembly.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "E:\Packt\ch04\Demo_04\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "E:\Packt\ch04\Demo_04\_Imports.razor"
using Demo_04;
#line default
#line hidden
#nullable disable
#nullable restore
#line 10 "E:\Packt\ch04\Demo_04\_Imports.razor"
using Demo_04.Shared;
#line default
#line hidden
#nullable disable
[Microsoft.AspNetCore.Components.RouteAttribute("/window")]
public partial class Window : Microsoft.AspNetCore.Components.ComponentBase
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
}
#pragma warning restore 1998
#nullable restore
#line 15 "E:\Packt\ch04\Demo_04\Pages\Window.razor"
private WindowSize windowSize = new WindowSize();
private async Task GetWindowSize()
{
windowSize = await js.InvokeAsync<WindowSize>(
"bweInterop.getWindowSize");
}
public class WindowSize
{
public int? Width { get; set; }
public int? Height { get; set; }
}
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Components.InjectAttribute] private IJSRuntime js { get; set; }
}
}
#pragma warning restore 1591
| 23.598291
| 118
| 0.749366
|
[
"MIT"
] |
PacktPublishing/Blazor-WebAssembly-Projects
|
Chapter04/Demo_04/obj/HPD/Debug/net5.0/RazorDeclaration/Pages/Window.razor.g.cs
| 2,761
|
C#
|
// <auto-generated>
// ReSharper disable ConvertPropertyToExpressionBody
// ReSharper disable DoNotCallOverridableMethodsInConstructor
// ReSharper disable EmptyNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable PartialMethodWithSinglePart
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable RedundantOverridenMember
// ReSharper disable UseNameofExpression
// TargetFrameworkVersion = 4.6
#pragma warning disable 1591 // Ignore "Missing XML Comment" warning
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Context
{
// PhoneNumberType
///<summary>
/// Type of phone number of a person.
///</summary>
[Table("PhoneNumberType", Schema = "Person")]
[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.37.2.0")]
public class Person_PhoneNumberType
{
///<summary>
/// Primary key for telephone number type records.
///</summary>
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(@"PhoneNumberTypeID", Order = 1, TypeName = "int")]
[Index(@"PK_PhoneNumberType_PhoneNumberTypeID", 1, IsUnique = true, IsClustered = true)]
[Required]
[Key]
[Display(Name = "Phone number type ID")]
public int PhoneNumberTypeId { get; set; } // PhoneNumberTypeID (Primary key)
///<summary>
/// Name of the telephone number type
///</summary>
[Column(@"Name", Order = 2, TypeName = "nvarchar")]
[Required(AllowEmptyStrings = true)]
[MaxLength(50)]
[StringLength(50)]
[Display(Name = "Name")]
public string Name { get; set; } // Name (length: 50)
///<summary>
/// Date and time the record was last updated.
///</summary>
[Column(@"ModifiedDate", Order = 3, TypeName = "datetime")]
[Required]
[DataType(DataType.DateTime)]
[Display(Name = "Modified date")]
public System.DateTime ModifiedDate { get; set; } // ModifiedDate
// Reverse navigation
/// <summary>
/// Child Person_PersonPhones where [PersonPhone].[PhoneNumberTypeID] point to this entity (FK_PersonPhone_PhoneNumberType_PhoneNumberTypeID)
/// </summary>
public virtual System.Collections.Generic.ICollection<Person_PersonPhone> Person_PersonPhones { get; set; } // PersonPhone.FK_PersonPhone_PhoneNumberType_PhoneNumberTypeID
public Person_PhoneNumberType()
{
ModifiedDate = System.DateTime.Now;
Person_PersonPhones = new System.Collections.Generic.List<Person_PersonPhone>();
}
}
}
// </auto-generated>
| 36.826667
| 179
| 0.672339
|
[
"MIT"
] |
enriqueescobar-askida/Kinito.AdventureWorks2017
|
Context/Person_PhoneNumberType.cs
| 2,762
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HallOfBeorn.Models.LotR.Sets.Core
{
public class EscapeFromDolGuldurNightmareSet : CardSet
{
protected override void Initialize()
{
Name = "Escape From Dol Guldur Nightmare";
Abbreviation = "EFDGN";
SetType = Models.SetType.Nightmare_Expansion;
Cycle = "NIGHTMARE";
Number = 2002;
Cards.Add(new LotRCard()
{
Title = "Escape from Dol Guldur Nightmare",
Id = "3E562129-6B4E-4DA9-B7DD-8165BB91931B",
CardType = CardType.Nightmare_Setup,
Text = "You are playing Nightmare mode.\r\n\r\nForced: When stage 1B is revealed, the number of random heroes captured is determined by the number of players, as follows: 1-2 players = 1 hero captured, 3 players = 2 heroes captured, 4 players = 3 heroes captured. All captured heroes are turned face down and considered \"the prisoner,\" cannot be used, cannot be damaged, and do not collect resources until they are rescued, (A single player cannot have more than 1 hero captured by this effect.)",
OppositeText =
@"Begin with the standard quest deck and encounter deck for the Escape from Dol Guldur scenario found in the LOTR LCG core set.
Remove the following cards, in the specified quantities, from the standard encounter deck:
2x Dol Guldur Orcs
2x Enchanted ~Stream
1x Great ~Forest Web
3x Mountains of ~Mirkwood
2x Caught in a Web
1x The Necromancer's Reach
1x Necromancer's Pass
2x Under the ~Shadow
2x Tower ~Gate
1x Iron Shackles
Then, shuffle the encounter cards in this Nightmare Deck into the remainder of the standard Escape from Dol Guldur encounter deck.
Finally, flip this setup card over and place it next to the quest deck. Its effects remain active throughout the game, which is now ready to begin.",
EncounterSet = "Escape from Dol Guldur Nightmare",
Quantity = 1,
CardNumber = 1,
Artist = Artist.Jim_Pavelec
});
Cards.Add(new LotRCard()
{
Title = "Torture Master",
Id = "0C6DB523-94DC-4893-9A96-F2D631D9CB3A",
CardType = CardType.Enemy,
EngagementCost = 45,
Threat = 5,
Attack = 1,
Defense = 2,
HitPoints = 4,
Traits = new List<string> { "Dol Guldur.", "Orc." },
Text = "When Revealed: Add 1 resource token to each Dol Guldur location in play.",
Shadow = "Shadow: Any hero damaged but not defeated by this attack is turned face down, as a \"prisoner.\" Then, if the players are on stage 3, return to stage 2B of the quest.",
EncounterSet = "Escape from Dol Guldur Nightmare",
Quantity = 3,
CardNumber = 2,
Artist = Artist.Rafal_Hrynkiewicz
});
addEnemy("Crazed Captive", "Escape from Dol Guldur Nightmare", 13, 2, 1, 3, 1)
.WithTraits("Captive.")
.WithKeywords("Doomed 1.")
.WithTextLine("Doomed 1.")
.WithTextLine("Forced: If Crazed Captive is defeated, raise each players threat by 7.")
.WithShadow("Shadow: If attacking enemy is not defeated this phase, raise defending player's threat by 7 at the end of the phase.")
.WithInfo(3, 2, Artist.Magali_Villeneuve);
Cards.Add(new LotRCard()
{
Title = "Spider of Dol Guldur",
Id = "D1EB44E3-8ABA-4024-B858-82C9A4EBF374",
CardType = CardType.Enemy,
EngagementCost = 28,
Threat = 3,
Attack = 3,
Defense = 3,
HitPoints = 6,
Traits = new List<string> { "Creature.", "Spider.", "Dol Guldur." },
Text = "If there are any unclaimed objectives in play, Spider of ~Dol Guldur gains surge.",
Shadow = "Shadow: Attacking enemy gets +3 Attack for each unclaimed objective in play.",
EncounterSet = "Escape from Dol Guldur Nightmare",
Quantity = 3,
CardNumber = 4,
Artist = Artist.Andrew_Ryan
});
Cards.Add(new LotRCard()
{
Title = "Torture Chamber",
Id = "CC2D3C5B-E751-4B2D-8177-A9D8792FA4C0",
CardType = CardType.Location,
Threat = 3,
QuestPoints = 6,
Traits = new List<string> { "Dol Guldur." },
Text = "If Torture Chamber has 4 or more resource tokens on it, all \"prisoners\" were killed, and the players have lost the game.\r\n\r\nForced: At the end of each round, place 1 resource token on each Dol Guldur location in play.",
EncounterSet = "Escape from Dol Guldur Nightmare",
Quantity = 2,
CardNumber = 5,
Artist = Artist.Ben_Zweifel
});
Cards.Add(new LotRCard()
{
Title = "Dungeon Labyrinth",
Id = "4780DEFF-40C9-4DEC-BFD8-83D892C76A91",
CardType = CardType.Location,
Threat = 1,
QuestPoints = 4,
Traits = new List<string> { "Dol Guldur." },
Text =
@"Dungeon Labyrinth gets +1 Threat and +1 quest point for each resource token on it
Forced: At the end of each round, place 1 resource token on Dungeon Labyrinth for each player in the game.",
FlavorText = "\"Some here will remember that many years ago I myself dared to pass the doors of the Necromancer in Dol Guldur...\" -Gandalf, The Fellowship of the Ring",
EncounterSet = "Escape from Dol Guldur Nightmare",
Quantity = 3,
CardNumber = 6,
Artist = Artist.S_C_Watson
});
Cards.Add(new LotRCard()
{
Title = "Sentinel of Shadow",
Id = "0323B0F5-7726-4F0C-891E-A9F970E1974F",
CardType = CardType.Treachery,
Text = "When Revealed: The staging area gets +X Threat until the end of the phase, where X is twice the number of players in the game. If the players quest unsuccessfully this phase, put the ~Nazgûl of ~Dol Guldur into play (from any out of play area), engaged with the first player. (Cannot be canceled.)",
EncounterSet = "Escape from Dol Guldur Nightmare",
Quantity = 2,
CardNumber = 7,
Artist = Artist.Rafal_Hrynkiewicz
});
addTreachery("Catacomb Inspection", "Escape from Dol Guldur Nightmare")
.WithKeywords("Surge.")
.WithTextLine("Surge.")
.WithTextLine("When Revealed: Add 1 resource token to each Dol Guldur location in play.")
.WithShadow("Shadow: If there is a Dol Guldur location in the staging area, move 1 resource token from each of your heroes' resource pools to that location. (Resolve this effect for each Dol Guldur location.)")
.WithInfo(8, 2, Artist.Rafal_Hrynkiewicz);
Cards.Add(new LotRCard()
{
Title = "Dark Interrogation",
Id = "2DC13AE9-73DD-4F80-AF8F-29E4E4BA7E7A",
CardType = CardType.Treachery,
Text = "When Revealed: Each player must choose and discard cards from hand until he has only 2 cards in hand. (Each player with 2 or fewer cards in hand must instead reveal 1 card from the encounter deck.)",
Shadow = "Shadow: Discard each card you control that has at least 1 copy of itself in your discard pile. (If this attack is undefended, each player must resolve this effect.)",
EncounterSet = "Escape from Dol Guldur Nightmare",
Quantity = 2,
CardNumber = 9,
Artist = Artist.Magali_Villeneuve
});
}
}
}
| 51.9375
| 515
| 0.578821
|
[
"MIT"
] |
danpoage/hall-of-beorn
|
src/HallOfBeorn/Models/LotR/Sets/Core/EscapeFromDolGuldurNightmareSet.cs
| 8,313
|
C#
|
// Part of FreeLibSet.
// See copyright notices in "license" file in the FreeLibSet root directory.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FreeLibSet.Forms;
using FreeLibSet.Data;
using FreeLibSet.Data.Docs;
using FreeLibSet.Config;
namespace FreeLibSet.Forms.Docs
{
internal partial class YearGridFilterForm : Form
{
#region Конструктор
public YearGridFilterForm()
{
InitializeComponent();
Icon = EFPApp.MainImageIcon("Filter");
EFPFormProvider efpForm = new EFPFormProvider(this);
efpMode = new EFPRadioButtons(efpForm, rbNoFilter);
efpYear = new EFPIntEditBox(efpForm, edYear);
efpYear.Control.Increment = 1;
efpYear.Minimum = 1900;
efpYear.Maximum = 2099;
efpYear.EnabledEx = efpMode[1].CheckedEx;
}
#endregion
#region Поля
public EFPRadioButtons efpMode;
public EFPIntEditBox efpYear;
#endregion
}
/// <summary>
/// Фильтр по году для числового поля или поля типа "Дата"
/// </summary>
public class YearGridFilter : YearCommonFilter, IEFPGridFilter, IEFPScrollableGridFilter
{
#region Конструкторы
/// <summary>
/// Конструктор для числового поля
/// </summary>
/// <param name="columnName">Имя поля</param>
public YearGridFilter(string columnName)
: base(columnName)
{
}
/// <summary>
/// Конструктор для поля типа "Дата" или числового поля
/// </summary>
/// <param name="columnName">Имя поля</param>
/// <param name="isDateColumn">Если true, то поле имеет тип "Дата".
/// Если false, то поле является числовым</param>
public YearGridFilter(string columnName, bool isDateColumn)
: base(columnName, isDateColumn)
{
}
#endregion
#region Переопределенные методы и свойства
/// <summary>
/// Текстовое представление фильтра в правой части таблички фильтров.
/// Пустая строка означает отсутствие фильтра (IsEmpty=true).
/// </summary>
public virtual string FilterText
{
get
{
if (Value.HasValue)
return Value.ToString();
else
return string.Empty;
}
}
/// <summary>
/// Сохраняем год между вызовами
/// </summary>
private static int _PrevYear = DateTime.Today.Year;
/// <summary>
/// Показывает блок диалога для редактирования фильтра
/// </summary>
/// <returns>True, если пользователь установил фильтр</returns>
public virtual bool ShowFilterDialog(EFPDialogPosition dialogPosition)
{
YearGridFilterForm Form = new YearGridFilterForm();
Form.Text = DisplayName;
Form.efpYear.Value = _PrevYear;
if (Value.HasValue)
{
Form.efpMode.SelectedIndex = 1;
Form.efpYear.Value = Value.Value;
}
else
Form.efpMode.SelectedIndex = 0;
if (EFPApp.ShowDialog(Form, true, dialogPosition) != DialogResult.OK)
return false;
if (Form.efpMode.SelectedIndex == 0)
Value = null;
else
Value = Form.efpYear.Value;
_PrevYear = Form.efpYear.Value;
return true;
}
#endregion
#region IScrollableGridFilter Members
/// <summary>
/// Возвращает true, если фильтр установлен
/// </summary>
public bool CanScrollUp
{
get { return Value != 0 && Value > 1; }
}
/// <summary>
/// Возвращает true, если фильтр установлен
/// </summary>
public bool CanScrollDown
{
get { return Value != 0 && Value < 9999; }
}
/// <summary>
/// Уменьшает год на 1
/// </summary>
public void ScrollUp()
{
Value--;
}
/// <summary>
/// Увеличивает год на 1
/// </summary>
public void ScrollDown()
{
Value++;
}
#endregion
}
/// <summary>
/// Фильтр на попадание года в интервал.
/// В таблице должно быть два числовых поля, задающих первый и последний год.
/// Строка проходит фильтр, если заданный в фильтре год (Value) попадает в диапазон.
/// Обрабатываются значения типа NULL, задающие открытые интервалы
/// </summary>
public class YearRangeInclusionGridFilter : YearRangeInclusionCommonFilter, IEFPGridFilter, IEFPScrollableGridFilter
{
#region Конструкторы
/// <summary>
/// Конструктор для числового поля
/// </summary>
/// <param name="firstYearFieldName"></param>
/// <param name="lastYearFieldName"></param>
public YearRangeInclusionGridFilter(string firstYearFieldName, string lastYearFieldName)
: base(firstYearFieldName, lastYearFieldName)
{
}
#endregion
#region Переопределенные методы и свойства
/// <summary>
/// Текстовое представление фильтра в правой части таблички фильтров.
/// Пустая строка означает отсутствие фильтра (IsEmpty=true).
/// </summary>
public virtual string FilterText
{
get
{
if (Value == 0)
return string.Empty;
else
return Value.ToString();
}
}
/// <summary>
/// Сохраняем год между вызовами
/// </summary>
private static int _PrevYear = DateTime.Today.Year;
/// <summary>
/// Показывает блок диалога для редактирования фильтра
/// </summary>
/// <returns>True, если пользователь установил фильтр</returns>
public virtual bool ShowFilterDialog(EFPDialogPosition dialogPosition)
{
YearGridFilterForm Form = new YearGridFilterForm();
Form.Text = DisplayName;
Form.efpYear.Value = _PrevYear;
if (Value == 0)
Form.efpMode.SelectedIndex = 0;
else
{
Form.efpMode.SelectedIndex = 1;
Form.efpYear.Value = Value;
}
if (EFPApp.ShowDialog(Form, true, dialogPosition) != DialogResult.OK)
return false;
if (Form.efpMode.SelectedIndex == 0)
Value = 0;
else
Value = Form.efpYear.Value;
_PrevYear = Form.efpYear.Value;
return true;
}
#endregion
#region IScrollableGridFilter Members
/// <summary>
/// Возвращает true, если фильтр установлен
/// </summary>
public bool CanScrollUp
{
get { return Value != 0 && Value > 1; }
}
/// <summary>
/// Возвращает true, если фильтр установлен
/// </summary>
public bool CanScrollDown
{
get { return Value != 0 && Value < 9999; }
}
/// <summary>
/// Уменьшает год на 1
/// </summary>
public void ScrollUp()
{
Value--;
}
/// <summary>
/// Увеличивает год на 1
/// </summary>
public void ScrollDown()
{
Value++;
}
#endregion
}
}
| 23.97153
| 118
| 0.625297
|
[
"BSD-2-Clause"
] |
a94827/FreeLibSet
|
ExtDBDocForms/YearGridFilterForm.cs
| 7,811
|
C#
|
using BotSharp.Core.Engines.Dialogflow.Http;
using BotSharp.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
namespace BotSharp.Core.Engines.Dialogflow
{
public class AIDataService
{
private readonly AIConfiguration config;
public string SessionId { get; }
public AIDataService(AIConfiguration config)
{
this.config = config;
if (string.IsNullOrEmpty(config.SessionId))
{
SessionId = Guid.NewGuid().ToString();
}
else
{
SessionId = config.SessionId;
}
}
public AIResponse Request(AIRequest request)
{
request.Language = config.Language.code;
request.Timezone = TimeZone.CurrentTimeZone.StandardName;
request.SessionId = SessionId;
try
{
var httpRequest = (HttpWebRequest)WebRequest.Create(config.RequestUrl);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/json; charset=utf-8";
httpRequest.Accept = "application/json";
httpRequest.Headers.Add("Authorization", "Bearer " + config.ClientAccessToken);
var jsonSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);
if (config.DebugLog)
{
Debug.WriteLine("Request: " + jsonRequest);
}
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(jsonRequest);
streamWriter.Close();
}
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
if (config.DebugLog)
{
Debug.WriteLine("Response: " + result);
}
var aiResponse = JsonConvert.DeserializeObject<AIResponse>(result);
CheckForErrors(aiResponse);
return aiResponse;
}
}
catch (Exception e)
{
throw new AIServiceException(e);
}
}
public AIResponse VoiceRequest(Stream voiceStream, RequestExtras requestExtras = null)
{
var request = new AIRequest();
request.Language = config.Language.code;
request.Timezone = TimeZone.CurrentTimeZone.StandardName;
request.SessionId = SessionId;
if (requestExtras != null)
{
requestExtras.CopyTo(request);
}
try
{
var httpRequest = (HttpWebRequest)WebRequest.Create(config.RequestUrl);
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.Headers.Add("Authorization", "Bearer " + config.ClientAccessToken);
var jsonSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);
if (config.DebugLog)
{
Debug.WriteLine("Request: " + jsonRequest);
}
var multipartClient = new MultipartHttpClient(httpRequest);
multipartClient.connect();
multipartClient.addStringPart("request", jsonRequest);
multipartClient.addFilePart("voiceData", "voice.wav", voiceStream);
multipartClient.finish();
var responseJsonString = multipartClient.getResponse();
if (config.DebugLog)
{
Debug.WriteLine("Response: " + responseJsonString);
}
var aiResponse = JsonConvert.DeserializeObject<AIResponse>(responseJsonString);
CheckForErrors(aiResponse);
return aiResponse;
}
catch (Exception e)
{
throw new AIServiceException(e);
}
}
public bool ResetContexts()
{
var cleanRequest = new AIRequest("empty_query_for_resetting_contexts");
cleanRequest.ResetContexts = true;
try
{
var response = Request(cleanRequest);
return !response.IsError;
}
catch (AIServiceException e)
{
Debug.WriteLine("Exception while contexts clean." + e);
return false;
}
}
static void CheckForErrors(AIResponse aiResponse)
{
if (aiResponse == null)
{
throw new AIServiceException("API.AI response parsed as null. Check debug log for details.");
}
if (aiResponse.IsError)
{
throw new AIServiceException(aiResponse);
}
}
}
}
| 31.521978
| 109
| 0.5346
|
[
"Apache-2.0"
] |
david0718/BotSharp
|
BotSharp.Core/Engines/Dialogflow/AIDataService.cs
| 5,739
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedSharp.Events.Sys.Interfaces
{
/// <summary>
/// Extension for the existing interface, just to support unsubscribing as a standard.
/// </summary>
public interface IEventSource<TItem> : IObservable<TItem>
{
/// <summary>
/// Performs the unsubscribe process. Mostly used for internal needs.
/// I do not recommend to use it explicitly, you have <see cref="IDisposable"/> object for it.
/// </summary>
bool Unsubscribe(IObserver<TItem> observer);
}
}
| 30.666667
| 102
| 0.677019
|
[
"MIT"
] |
Red-Sharp-Group/Weak-Referenced-Infrastructure
|
RedSharp.Events.System/Interfaces/IEventSource.cs
| 646
|
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("Engine")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MEDYA")]
[assembly: AssemblyProduct("Engine")]
[assembly: AssemblyCopyright("Copyright © MEDYA 2006")]
[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("16a8a23e-30e4-4c4f-af9e-9a8f37f3b24f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 36.294118
| 84
| 0.750405
|
[
"MIT",
"Unlicense"
] |
NuLL3rr0r/en-fa-phrase-dictionary
|
TextEngine/Engine/Properties/AssemblyInfo.cs
| 1,237
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.