content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.AccessControl;
using System.Security.Principal;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Dtyp;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Fscc;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb;
using Microsoft.Protocols.TestTools.StackSdk.Security.SspiLib;
using Microsoft.Protocols.TestTools.StackSdk.Security.SspiService;
using NamespaceSmb = Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb;
using Smb2 = Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
namespace Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter
{
/// <summary>
/// Communicate with NTFS implemented machine in SMB protocol
/// </summary>
public class SmbTransportAdapter : ManagedAdapterBase, ITransportAdapter
{
#region Define fields
private string domainName;
private string serverName;
private string userName;
private string password;
private string shareName;
private ushort fileId;
private ushort portNumber;
private ushort sessionId;
private ushort treeId;
private IpVersion ipVersion;
private SmbClient smbClient;
private TimeSpan timeout;
private UInt32 bufferSize;
private FSATestConfig testConfig;
// The following suppression is adopted because this field will be used by reflection.
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
private ITestSite site;
// The following suppression is adopted because this field will be used by reflection.
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
private UInt32 maxConnection;
private bool isSendSignedRequest;
/// <summary>
/// The identifier of the connection to get.
/// </summary>
private const int ConnectionId = 0;
#endregion
#region Define properties
/// <summary>
/// The timeout for the client waiting for the server response.
/// </summary>
public TimeSpan Timeout
{
set
{
this.timeout = value;
}
}
/// <summary>
/// Number in bytes of the net protocols' client buffer.
/// </summary>
public UInt32 BufferSize
{
set
{
this.bufferSize = value;
}
}
/// <summary>
/// IpVersion of the protocols
/// </summary>
public IpVersion IPVersion
{
set
{
this.ipVersion = value;
}
}
/// <summary>
/// Port number of the protocols
/// </summary>
public ushort Port
{
set
{
this.portNumber = value;
}
}
/// <summary>
/// Domain name connected
/// </summary>
public string Domain
{
set
{
this.domainName = value;
}
}
/// <summary>
/// Server name connected
/// </summary>
public string ServerName
{
set
{
this.serverName = value;
}
}
/// <summary>
/// User name being used
/// </summary>
public string UserName
{
set
{
this.userName = value;
}
}
/// <summary>
/// Password of the user being used
/// </summary>
public string Password
{
set
{
this.password = value;
}
}
/// <summary>
/// Number of maximum connection
/// </summary>
public UInt32 MaxConnection
{
set
{
this.maxConnection = value;
}
}
/// <summary>
/// Share name being connecting
/// </summary>
public string ShareName
{
set
{
this.shareName = value;
}
}
/// <summary>
/// To specify if use pass-through information level code
/// </summary>
public bool IsUsePassThroughInfoLevelCode
{
get
{
return this.smbClient.Capability.IsUsePassThrough;
}
set
{
this.smbClient.Capability.IsUsePassThrough = value;
}
}
/// <summary>
/// To specify if the transport sends signed request to server.
/// </summary>
public bool IsSendSignedRequest
{
get { return this.isSendSignedRequest; }
set { this.isSendSignedRequest = value; }
}
#endregion
#region Adapter initialization and cleanup
public SmbTransportAdapter(FSATestConfig fsaTestConfig)
{
this.testConfig = fsaTestConfig;
}
/// <summary>
/// Initialize this adapter, will be called by PTF automatically
/// </summary>
/// <param name="testSite">ITestSite type object, will be set by PTF automatically</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
this.site = testSite;
this.smbClient = null;
TestTools.StackSdk.Security.KerberosLib.KerberosContext.KDCComputerName = testConfig.DCServerName;
TestTools.StackSdk.Security.KerberosLib.KerberosContext.KDCPort = testConfig.KDCPort;
}
/// <summary>
/// Disconnect from share and release object
/// </summary>
/// <param name="disposing">bool, indicates it is disposing status</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (this.smbClient != null)
{
this.smbClient.Dispose();
this.smbClient = null;
}
}
/// <summary>
/// Initialize a tcp connection with server
/// </summary>
/// <param name="isWindows">the flag is true if the OS is windows</param>
public void Initialize(bool isWindows)
{
//Initialize SMBClientSDK and connect to share
this.smbClient = new SmbClient();
this.site.Log.Add(LogEntryKind.Debug, "Connect to server {0}.", this.serverName);
this.smbClient.Connect(this.serverName, (int)this.portNumber, this.ipVersion, (int)this.bufferSize);
MessageStatus status = MessageStatus.SUCCESS;
status = this.Negotiate();
if (status != MessageStatus.SUCCESS)
{
throw new InvalidOperationException("Negotiate failed:" + status.ToString());
}
status = this.SessionSetup(isWindows);
if (status != MessageStatus.SUCCESS)
{
throw new InvalidOperationException("session setup failed:" + status.ToString());
}
status = this.TreeConnect();
if (status != MessageStatus.SUCCESS)
{
throw new InvalidOperationException("treeconeect failed:" + status.ToString());
}
}
/// <summary>
/// Calling this method will disconnect current connection and
/// create a new connect to a share as specified as in the properties.
/// </summary>
public override void Reset()
{
base.Reset();
if (this.smbClient != null)
{
this.TreeDisconnect();
this.LogOff();
this.smbClient.Disconnect();
this.smbClient.Dispose();
this.smbClient = null;
}
}
# endregion
#region Protected methods
/// <summary>
/// Negotiate method, will be called automatically by initialize and reset method
/// </summary>
/// <returns>NTStatus code</returns>
protected MessageStatus Negotiate()
{
string[] dialetNameString = { DialectNameString.PCNET1,
DialectNameString.LANMAN10,
DialectNameString.WFW10,
DialectNameString.LANMAN12,
DialectNameString.LANMAN21,
DialectNameString.NTLANMAN
};
SmbPacket packet = this.smbClient.CreateNegotiateRequest(SignState.NONE, dialetNameString);
this.smbClient.SendPacket(packet);
SmbPacket response = this.smbClient.ExpectPacket(this.timeout);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_NEGOTIATE)
{
throw new InvalidOperationException("No negotiate response.");
}
return (MessageStatus)response.SmbHeader.Status;
}
/// <summary>
/// SessionSetup method, will be called automatically by initialize and reset method
/// </summary>
/// <returns>NTStatus code</returns>
/// <param name="isWindows">the flag is true if the OS is windows</param>
protected MessageStatus SessionSetup(bool isWindows)
{
SmbPacket response = null;
SmbPacket packet = this.smbClient.CreateFirstSessionSetupRequest(
SmbSecurityPackage.NTLM,
this.serverName,
this.domainName,
this.userName,
this.password);
this.smbClient.SendPacket(packet);
response = this.smbClient.ExpectPacket(this.timeout);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_SESSION_SETUP_ANDX)
{
throw new InvalidOperationException("No session setup 1 response.");
}
this.sessionId = response.SmbHeader.Uid;
if (!isWindows)
{
SmbClientConnection connection = this.smbClient.Context.Connection;
connection.GssApi = new SspiClientSecurityContext(
SecurityPackageType.Ntlm,
new AccountCredential(
this.domainName,
this.userName,
this.password),
"cifs/" + this.serverName,
ClientSecurityContextAttribute.Connection,
SecurityTargetDataRepresentation.SecurityNetworkDrep);
this.smbClient.Context.AddOrUpdateConnection(connection);
}
packet = this.smbClient.CreateSecondSessionSetupRequest((ushort)this.sessionId, SmbSecurityPackage.NTLM);
this.smbClient.SendPacket(packet);
response = this.smbClient.ExpectPacket(this.timeout);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_SESSION_SETUP_ANDX)
{
throw new InvalidOperationException("No session setup 2 response.");
}
return (MessageStatus)response.SmbHeader.Status;
}
/// <summary>
/// TreeConnect method, will be called automatically by initialize and reset method
/// </summary>
/// <returns>NTStatus code</returns>
protected MessageStatus TreeConnect()
{
string sharePath = @"\\" + this.serverName + @"\" + this.shareName;
SmbPacket packet = this.smbClient.CreateTreeConnectRequest((ushort)this.sessionId, sharePath);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbTreeConnectAndxResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_TREE_CONNECT_ANDX)
{
throw new InvalidOperationException("No tree_connect_andx response.");
}
this.treeId = response.SmbHeader.Tid;
return (MessageStatus)response.SmbHeader.Status;
}
/// <summary>
/// TreeDisconnect method, will be called automatically by initialize and reset method
/// </summary>
/// <returns>NTStatus code</returns>
protected MessageStatus TreeDisconnect()
{
SmbPacket packet = this.smbClient.CreateTreeDisconnectRequest(this.treeId);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbTreeDisconnectResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_TREE_DISCONNECT)
{
throw new InvalidOperationException("No tree_disconnect_andx response.");
}
return (MessageStatus)response.SmbHeader.Status;
}
/// <summary>
/// Logoff method, will be called automatically by initialize and reset method
/// </summary>
/// <returns>NTStatus code</returns>
protected MessageStatus LogOff()
{
SmbPacket packet = this.smbClient.CreateLogoffRequest(this.sessionId);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbLogoffAndxResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_LOGOFF_ANDX)
{
throw new InvalidOperationException("No logoff response.");
}
return (MessageStatus)response.SmbHeader.Status;
}
#endregion
#region Implementing ITransportAdapter methods
#region 3.1.5.1 Server Requests an Open of a File
/// <summary>
/// Create a new file or open an existing file.
/// </summary>
/// <param name="fileName">The name of the data file or directory to be created or opened</param>
/// <param name="fileAttribute">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <param name="desiredAccess">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13.1</param>
/// <param name="shareAccess">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <param name="createOptions">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <param name="createDisposition">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <param name="createAction">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus CreateFile(
string fileName,
UInt32 fileAttribute,
UInt32 desiredAccess,
UInt32 shareAccess,
UInt32 createOptions,
UInt32 createDisposition,
out UInt32 createAction
)
{
SmbPacket packet = this.smbClient.CreateCreateRequest(
(ushort)this.treeId,
fileName,
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs.NtTransactDesiredAccess)desiredAccess,
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs.SMB_EXT_FILE_ATTR)fileAttribute,
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs.NtTransactShareAccess)shareAccess,
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs.NtTransactCreateDisposition)createDisposition,
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.NtTransactCreateOptions)createOptions,
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs.NtTransactImpersonationLevel.SEC_ANONYMOUS,
CreateFlags.NT_CREATE_REQUEST_OPBATCH);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbNtCreateAndxResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_NT_CREATE_ANDX)
{
throw new InvalidOperationException("No create response.");
}
if (response is Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbNtCreateAndxResponsePacket)
{
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbNtCreateAndxResponsePacket createResponse =
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbNtCreateAndxResponsePacket)response;
createAction = (uint)createResponse.SmbParameters.CreationAction;
this.fileId = createResponse.SmbParameters.FID;
return MessageStatus.SUCCESS;
}
else
{
createAction = (uint)CreateAction.CREATED;
return (MessageStatus)response.SmbHeader.Status;
}
}
/// <summary>
/// Create a new file or open an existing file.
/// </summary>
/// <param name="fileName">The name of the data file or directory to be created or opened</param>
/// <param name="fileAttribute">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <param name="desiredAccess">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13.1</param>
/// <param name="shareAccess">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <param name="createOptions">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <param name="createDisposition">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <param name="createAction">A bitmask for the open operation, as specified in [MS-SMB2] section 2.2.13</param>
/// <param name="fileId">The fileId for the open.</param>
/// <param name="treeId">The treeId for the open.</param>
/// <param name="sessionId">The sessionId for the open.</param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus CreateFile(
string fileName,
UInt32 fileAttribute,
UInt32 desiredAccess,
UInt32 shareAccess,
UInt32 createOptions,
UInt32 createDisposition,
out UInt32 createAction,
out Smb2.FILEID fileId,
out uint treeId,
out ulong sessionId
)
{
fileId = Smb2.FILEID.Zero;
treeId = 0;
sessionId = 0;
createAction = (uint)CreateAction.NULL;
return MessageStatus.SUCCESS;
}
#endregion
#region 3.1.5.2 Server Requests a Read
/// <summary>
/// Read the file which is opened most recently
/// </summary>
/// <param name="offset">The position in byte to read start</param>
/// <param name="byteCount">The maximum value of byte number to read</param>
/// <param name="isNonCached">Indicate whether make a cached for the operation in the server. </param>
/// <param name="outBuffer">The output data of this control operation</param>
/// <returns>NTstatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus Read(UInt64 offset, UInt32 byteCount, bool isNonCached, out byte[] outBuffer)
{
SmbPacket packet = this.smbClient.CreateReadRequest(this.fileId, (ushort)byteCount, (uint)offset);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbReadAndxResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_READ_ANDX)
{
throw new InvalidOperationException("No read response.");
}
if (response is Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbReadAndxResponsePacket)
{
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbReadAndxResponsePacket readResponse =
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbReadAndxResponsePacket)response;
outBuffer = readResponse.SmbData.Data;
return MessageStatus.SUCCESS;
}
else
{
outBuffer = new byte[0];
return (MessageStatus)response.SmbHeader.Status;
}
}
#endregion
#region 3.1.5.3 Server Requests a Write
/// <summary>
/// Write the file which is opened most recently
/// </summary>
/// <param name="buffer">Bytes to be written in the file</param>
/// <param name="offset">The offset of the file from where client wants to start writing</param>
/// <param name="isWriteThrough">If true, the write should be treated in a write-through fashion</param>
/// <param name="isNonCached">If true, the write should be sent directly to the disk instead of the cache</param>
/// <param name="bytesWritten">The number of the bytes written</param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus Write(byte[] buffer, UInt64 offset, bool isWriteThrough, bool isNonCached, out UInt64 bytesWritten)
{
SmbPacket packet = this.smbClient.CreateWriteRequest(this.fileId, (uint)offset, buffer);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbWriteAndxResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_WRITE_ANDX)
{
throw new InvalidOperationException("No write response.");
}
if (response is Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbWriteAndxResponsePacket)
{
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbWriteAndxResponsePacket writeResponse =
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbWriteAndxResponsePacket)response;
bytesWritten = writeResponse.SmbParameters.Count;
return MessageStatus.SUCCESS;
}
else
{
bytesWritten = 0; //If fail, the number of byte written will be 0
return (MessageStatus)response.SmbHeader.Status;
}
}
#endregion
#region 3.1.5.4 Server Requests Closing an Open
/// <summary>
/// Close the open object that was lately created
/// </summary>
/// <returns>NTStatus code</returns>
public MessageStatus CloseFile()
{
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbCloseRequestPacket packet =
this.smbClient.CreateCloseRequest(this.fileId);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbCloseResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_CLOSE)
{
throw new InvalidOperationException("No close response.");
}
return (MessageStatus)response.SmbHeader.Status;
}
#endregion
#region 3.1.5.5 Server Requests Querying a Directory
/// <summary>
/// Query an existing directory with specific file name pattern. Supported by SMB but still need to be completed.
/// </summary>
/// <param name="fileInformationClass">The type of information to be queried, as specified in [MS-FSCC] section 2.4</param>
/// <param name="maxOutPutSize">The maximum number of bytes to return</param>
/// <param name="restartScan">If true, indicating the enumeration of the directory should be restarted</param>
/// <param name="returnSingleEntry">Indicate whether return a single entry or not</param>
/// <param name="fileIndex">An index number from which to resume the enumeration</param>
/// <param name="fileNamePattern">A Unicode string containing the file name pattern to match. "* ?" must be treated as wildcards</param>
/// <param name="outBuffer">The query result</param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus QueryDirectory(
byte fileInformationClass,
UInt32 maxOutPutSize,
bool restartScan,
bool returnSingleEntry,
uint fileIndex,
string fileNamePattern,
out byte[] outBuffer
)
{
SmbPacket packet = this.smbClient.CreateTrans2QueryPathInformationRequest(
this.treeId,
fileNamePattern,
Trans2SmbParametersFlags.NONE,
(QueryInformationLevel)(fileInformationClass),
(ushort)maxOutPutSize,
true);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbTrans2QueryPathInformationResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_TRANSACTION2)
{
throw new InvalidOperationException("No query directory response.");
}
if (response is Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbTrans2QueryPathInformationResponsePacket)
{
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbTrans2QueryPathInformationResponsePacket queryDirectoryResponse =
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbTrans2QueryPathInformationResponsePacket)response;
outBuffer = queryDirectoryResponse.SmbData.Trans2_Data;
return MessageStatus.SUCCESS;
}
else
{
outBuffer = null;
return (MessageStatus)response.SmbHeader.Status;
}
}
/// <summary>
/// Query an existing directory with specific file name pattern.
/// </summary>
/// <param name="fileId">The fileId for the open.</param>
/// <param name="treeId">The treeId for the open.</param>
/// <param name="sessionId">The sessionId for the open.</param>
/// <param name="fileInformationClass">The type of information to be queried, as specified in [MS-FSCC] section 2.4</param>
/// <param name="maxOutPutSize">The maximum number of bytes to return</param>
/// <param name="restartScan">If true, indicating the enumeration of the directory should be restarted</param>
/// <param name="returnSingleEntry">If true, indicate return an single entry of the query</param>
/// <param name="fileIndex">An index number from which to resume the enumeration</param>
/// <param name="fileNamePattern">A Unicode string containing the file name pattern to match. "* ?" must be treated as wildcards</param>
/// <param name="outBuffer">The query result</param>
/// <returns>NTStatus code</returns>
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus QueryDirectory(
Smb2.FILEID fileId,
uint treeId,
ulong sessionId,
byte fileInformationClass,
UInt32 maxOutPutSize,
bool restartScan,
bool returnSingleEntry,
uint fileIndex,
string fileNamePattern,
out byte[] outBuffer
)
{
//No implementation for SMBTransportadapter
outBuffer = null;
return MessageStatus.SUCCESS;
}
#endregion
#region 3.1.5.6 Server Requests Flushing Cached Data
/// <summary>
/// Flush all persistent attributes to stable storage. Not supported by SMB.
/// </summary>
/// <returns>NTStatus code</returns>
public MessageStatus FlushCachedData()
{
return MessageStatus.NOT_SUPPORTED;
}
#endregion
#region 3.1.5.7 Server Requests a Byte-Range Lock
/// <summary>
/// Lock range of a file. Not supported by SMB.
/// </summary>
/// <param name="offset">The start position of bytes to be locked</param>
/// <param name="length">The bytes size to be locked</param>
/// <param name="exclusiveLock">
/// NONE = 0,
/// LOCKFLAG_SHARED_LOCK = 1,
/// LOCKFLAG_EXCLUSIVE_LOCK = 2,
/// LOCKFLAG_UNLOCK = 4,
/// LOCKFLAG_FAIL_IMMEDIATELY = 16,
/// </param>
/// <param name="failImmediately">If the range is locked. Indicate whether the operation failed at once or wait for the range been unlocked.</param>
/// <returns>NTStatus code</returns>
public MessageStatus LockByteRange(
UInt64 offset,
UInt64 length,
bool exclusiveLock,
bool failImmediately)
{
return MessageStatus.NOT_SUPPORTED;
}
#endregion
#region 3.1.5.8 Server Requests an Unlock of a Byte-Range
/// <summary>
/// Unlock a range of a file. Not supported by SMB.
/// </summary>
/// <param name="offset">The start position of bytes to be unlocked</param>
/// <param name="length">The bytes size to be unlocked</param>
/// <returns>NTStatus code</returns>
public MessageStatus UnlockByteRange(UInt64 offset, UInt64 length)
{
return MessageStatus.NOT_SUPPORTED;
}
#endregion
#region 3.1.5.9 Server Requests an FsControl Request
/// <summary>
/// Send control code to latest opened file
/// </summary>
/// <param name="ctlCode">The control code to be sent, as specified in [FSCC] section 2.3</param>
/// <param name="maxOutBufferSize">The maximum number of byte to output</param>
/// <param name="inBuffer">The input data of this control operation</param>
/// <param name="outBuffer">The output data of this control operation</param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus IOControl(UInt32 ctlCode, UInt32 maxOutBufferSize, byte[] inBuffer, out byte[] outBuffer)
{
testConfig.CheckFSCTL(ctlCode);
outBuffer = null;
//Set isFlag to 0 to apply a share root handle as SMB described.
SmbNtTransactIoctlRequestPacket packet = this.smbClient.CreateNTTransIOCtlRequest(this.fileId, true, 0, ctlCode, inBuffer);
SMB_COM_NT_TRANSACT_Request_SMB_Parameters smbParameter = new SMB_COM_NT_TRANSACT_Request_SMB_Parameters();
smbParameter.DataCount = packet.SmbParameters.DataCount;
smbParameter.DataOffset = packet.SmbParameters.DataOffset;
smbParameter.Function = packet.SmbParameters.Function;
smbParameter.MaxDataCount = maxOutBufferSize;
smbParameter.MaxParameterCount = packet.SmbParameters.MaxParameterCount;
smbParameter.MaxSetupCount = packet.SmbParameters.MaxSetupCount;
smbParameter.ParameterCount = packet.SmbParameters.ParameterCount;
smbParameter.ParameterOffset = packet.SmbParameters.ParameterOffset;
smbParameter.Reserved1 = packet.SmbParameters.Reserved1;
smbParameter.Setup = packet.SmbParameters.Setup;
smbParameter.SetupCount = packet.SmbParameters.SetupCount;
smbParameter.TotalDataCount = packet.SmbParameters.TotalDataCount;
smbParameter.TotalParameterCount = packet.SmbParameters.TotalParameterCount;
smbParameter.WordCount = packet.SmbParameters.WordCount;
Type smbType = typeof(SmbNtTransactIoctlRequestPacket);
smbType.GetProperty("SmbParameters").SetValue(packet, smbParameter, null);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbNtTransactIoctlResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_NT_TRANSACT)
{
throw new InvalidOperationException("No read response.");
}
if (response is Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbNtTransactIoctlResponsePacket)
{
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbNtTransactIoctlResponsePacket ioctlResponse
= (Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbNtTransactIoctlResponsePacket)response;
outBuffer = ioctlResponse.SmbData.Data;
}
else if (response is SmbErrorResponsePacket)
{
SmbErrorResponsePacket errorResponse = (SmbErrorResponsePacket)response;
outBuffer = null;
return (MessageStatus)errorResponse.SmbHeader.Status;
}
return (MessageStatus)response.SmbHeader.Status;
}
#endregion
#region 3.1.5.10 Server Requests Change Notifications for a Directory
/// <summary>
/// Send or receive file change notification to latest opened file
/// </summary>
/// <param name="maxOutPutSize">Specify the maximum number of byte to be returned </param>
/// <param name="watchTree">Indicates whether the directory should be monitored recursively</param>
/// <param name="completionFilter">Indicates the filter of the notification</param>
/// <param name="outBuffer">Array of bytes containing the notification data</param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus ChangeNotification(UInt32 maxOutPutSize, bool watchTree, UInt32 completionFilter, out byte[] outBuffer)
{
outBuffer = null;
CifsClientConfig cifsClientConfig = new CifsClientConfig();
CifsClient cifsClient = new CifsClient(cifsClientConfig);
// Set the messageId to 1.
SmbPacket packet =
cifsClient.CreateNtTransactNotifyChangeRequest(
1,
this.sessionId,
this.treeId,
(SmbFlags)smbClient.Capability.Flag,
(SmbFlags2)smbClient.Capability.Flags2,
smbClient.Capability.MaxSetupCount,
smbClient.Capability.MaxParameterCount,
smbClient.Capability.MaxDataCount,
this.fileId,
CompletionFilter.FILE_NOTIFY_CHANGE_CREATION
| CompletionFilter.FILE_NOTIFY_CHANGE_NAME
| CompletionFilter.FILE_NOTIFY_CHANGE_FILE_NAME,
true);
SendSmbPacket(packet);
packet = smbClient.CreateCreateRequest(
this.treeId,
Site.Properties.Get("FSA.ExistingFolder"),
(NtTransactDesiredAccess)0x1,
(SMB_EXT_FILE_ATTR)0x80,
(NtTransactShareAccess)0x1,
(NtTransactCreateDisposition)0x3,
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.NtTransactCreateOptions)0x1,
NtTransactImpersonationLevel.SEC_IMPERSONATE,
CreateFlags.NT_CREATE_REQUEST_OPLOCK);
SendSmbPacket(packet);
SmbPacket response = smbClient.ExpectPacket(this.timeout);
if (response is SmbNtTransactNotifyChangeResponsePacket)
{
SmbNtTransactNotifyChangeResponsePacket changeNotifyResponse = (SmbNtTransactNotifyChangeResponsePacket)response;
return (MessageStatus)changeNotifyResponse.SmbHeader.Status;
}
else if (response is SmbErrorResponsePacket)
{
SmbErrorResponsePacket errorResponse = (SmbErrorResponsePacket)response;
outBuffer = null;
return (MessageStatus)errorResponse.SmbHeader.Status;
}
else
{
outBuffer = null;
return MessageStatus.INVALID_PARAMETER;
}
}
#endregion
#region 3.1.5.11 Server Requests a Query of File Information
/// <summary>
/// Query information of the latest opened file
/// </summary>
/// <param name="maxOutPutSize">Specify the maximum number of byte to be returned</param>
/// <param name="fileInfomationClass">The type of the information, as specified in [MS-FSCC] section 2.4</param>
/// <param name="buffer">Data in bytes, includes the file information query parameters.</param>
/// <param name="outBuffer">Array of bytes containing the file information. The structure of these bytes is
/// base on FileInformationClass, as specified in [MS-FSCC] section 2.4</param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus QueryFileInformation(
UInt32 maxOutPutSize,
UInt32 fileInfomationClass,
byte[] buffer,
out byte[] outBuffer)
{
SmbPacket packet = this.smbClient.CreateTrans2QueryFileInformationRequest(
this.fileId,
Trans2SmbParametersFlags.NONE,
(ushort)maxOutPutSize,
(QueryInformationLevel)fileInfomationClass,
null);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbTrans2QueryFileInformationResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_TRANSACTION2)
{
throw new InvalidOperationException("No query file information response.");
}
if (response is Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbTrans2QueryFileInformationResponsePacket)
{
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbTrans2QueryFileInformationResponsePacket queryFileResponse =
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbTrans2QueryFileInformationResponsePacket)response;
outBuffer = queryFileResponse.SmbData.Trans2_Data;
return MessageStatus.SUCCESS;
}
else
{
outBuffer = null;
return (MessageStatus)response.SmbHeader.Status;
}
}
#endregion
#region 3.1.5.12 Server Requests a Query of File System Information
/// <summary>
/// Query system information of the latest opened file
/// </summary>
/// <param name="maxOutputSize">Specify the maximum byte number to be returned</param>
/// <param name="fsInformationClass">The type of the system information, as specified in [MS-FSCC] section 2.5</param>
/// <param name="outBuffer">The retrieved file information in bytes.
/// Array of bytes containing the file system information. The structure of these bytes is
/// base on FileSystemInformationClass, as specified in [MS-FSCC] section 2.5</param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus QueryFileSystemInformation(
UInt32 maxOutputSize,
UInt32 fsInformationClass,
out byte[] outBuffer)
{
SmbPacket packet = this.smbClient.CreateTrans2QueryFileSystemInformationRequest(
this.treeId,
(ushort)maxOutputSize,
Trans2SmbParametersFlags.NONE,
(QueryFSInformationLevel)fsInformationClass);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbTrans2QueryFsInformationResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_TRANSACTION2)
{
throw new InvalidOperationException("No query file system information response.");
}
if (response is Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbTrans2QueryFsInformationResponsePacket)
{
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbTrans2QueryFsInformationResponsePacket queryFsResponse =
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbTrans2QueryFsInformationResponsePacket)response;
outBuffer = queryFsResponse.SmbData.Trans2_Data;
return MessageStatus.SUCCESS;
}
else
{
outBuffer = null;
return (MessageStatus)response.SmbHeader.Status;
}
}
#endregion
#region 3.1.5.13 Server Requests a Query of Security Information
/// <summary>
/// Query security information of the latest opened file
/// </summary>
/// <param name="maxOutPutSize">Specify the maximum bytes number to be returned</param>
/// <param name="securityInformation">The type of the system information,
/// as specified in [MS-DTYP] section 2.4.7</param>
/// <param name="outBuffer">
/// Array of bytes containing the file system information, as defined in [MS-DTYP] section 2.4.6
/// </param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus QuerySecurityInformation(
UInt32 maxOutPutSize,
UInt32 securityInformation,
out byte[] outBuffer)
{
outBuffer = null;
CifsClientConfig cifsClientConfig = new CifsClientConfig();
CifsClient cifsClient = new CifsClient(cifsClientConfig);
// Set the messageId to 1.
SmbNtTransactQuerySecurityDescRequestPacket packet =
cifsClient.CreateNtTransactQuerySecurityDescRequest(
1,
this.sessionId,
this.treeId,
(SmbFlags)smbClient.Capability.Flag,
(SmbFlags2)smbClient.Capability.Flags2,
smbClient.Capability.MaxSetupCount,
smbClient.Capability.MaxParameterCount,
smbClient.Capability.MaxDataCount,
this.fileId,
(NtTransactSecurityInformation)securityInformation);
SmbPacket response = this.SendPacketAndExpectResponse<SmbNtTransactQuerySecurityDescResponsePacket>(packet);
if (response is SmbNtTransactQuerySecurityDescResponsePacket)
{
SmbNtTransactQuerySecurityDescResponsePacket querySecurityResponse = (SmbNtTransactQuerySecurityDescResponsePacket)response;
RawSecurityDescriptor ReceivedSD = new RawSecurityDescriptor(" ");
outBuffer = new byte[ReceivedSD.BinaryLength];
//Read the data from index 0.
ReceivedSD.GetBinaryForm(outBuffer, 0);
return (MessageStatus)querySecurityResponse.SmbHeader.Status;
}
else if (response is SmbErrorResponsePacket)
{
SmbErrorResponsePacket errorResponse = (SmbErrorResponsePacket)response;
outBuffer = null;
return (MessageStatus)errorResponse.SmbHeader.Status;
}
else
{
outBuffer = null;
return MessageStatus.INVALID_PARAMETER;
}
}
#endregion
#region 3.1.5.14 Server Requests Setting of File Information
/// <summary>
/// Apply specific information of the latest opened file
/// </summary>
/// <param name="fileInfomationClass">Array of bytes containing the file information. The structure of these bytes is
/// base on FileInformationClass, as specified in [MS-FSCC] section 2.4
/// </param>
/// <param name="buffer">
/// Array of bytes containing the file information. The structure of these bytes is
/// base on FileInformationClass, as specified in [MS-FSCC] section 2.4
/// </param>
/// <returns>NTStatus code</returns>
public MessageStatus SetFileInformation(
UInt32 fileInfomationClass,
byte[] buffer)
{
SmbPacket packet = this.smbClient.CreateTrans2SetFileInformationRequest(
this.fileId,
Trans2SmbParametersFlags.NONE,
(SetInformationLevel)fileInfomationClass,
buffer);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbTrans2SetFileInformationResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_TRANSACTION2)
{
throw new InvalidOperationException("No set file information response.");
}
else if (response is SmbErrorResponsePacket)
{
SmbErrorResponsePacket errorResponse = (SmbErrorResponsePacket)response;
return (MessageStatus)errorResponse.SmbHeader.Status;
}
return (MessageStatus)response.SmbHeader.Status;
}
#endregion
#region 3.1.5.15 Server Requests Setting of File System Information
/// <summary>
/// Apply specific system information of the latest opened file
/// </summary>
/// <param name="fsInformationClass">The type of the system information, as specified in [MS-FSCC] section 2.5</param>
/// <param name="buffer">
/// Array of bytes containing the file system information. The structure of these bytes is
/// base on FileInformationClass, as specified in [MS-FSCC] section 2.4
/// </param>
/// <returns>NTStatus code</returns>
public MessageStatus SetFileSystemInformation(
UInt32 fsInformationClass,
byte[] buffer)
{
SmbPacket packet = this.smbClient.CreateTrans2SetFileSystemInformationRequest(
this.fileId,
Trans2SmbParametersFlags.NONE,
(QueryFSInformationLevel)fsInformationClass,
buffer);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbTrans2SetFsInformationResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_TRANSACTION2)
{
throw new InvalidOperationException("No set file system information response.");
}
else if (response is SmbErrorResponsePacket)
{
SmbErrorResponsePacket errorResponse = (SmbErrorResponsePacket)response;
return (MessageStatus)errorResponse.SmbHeader.Status;
}
return (MessageStatus)response.SmbHeader.Status;
}
#endregion
#region 3.1.5.16 Server Requests Setting of Security Information
/// <summary>
/// Apply security information of the latest opened file
/// </summary>
/// <param name="securityInformation">The type of the system information,
/// as specified in [MS-DTYP] section 2.4.7</param>
/// <param name="buffer">
/// Array of bytes containing the file system information, as defined in [MS-DTYP] section 2.4.6
/// </param>
/// <returns>NTStatus code</returns>
/// Disable warning CA1800 because it will affect the implementation of Adapter
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public MessageStatus SetSecurityInformation(
UInt32 securityInformation,
byte[] buffer)
{
// ReceivedSD from buffer
RawSecurityDescriptor ReceivedSD = new RawSecurityDescriptor(" ");
ReceivedSD.GetBinaryForm(buffer, 0);
CifsClientConfig cifsClientConfig = new CifsClientConfig();
CifsClient cifsClient = new CifsClient(cifsClientConfig);
// Set the messageId to 1.
SmbNtTransactSetSecurityDescRequestPacket packet =
cifsClient.CreateNtTransactSetSecurityDescRequest(
1,
this.sessionId,
this.treeId,
(SmbFlags)smbClient.Capability.Flag,
(SmbFlags2)smbClient.Capability.Flags2,
smbClient.Capability.MaxSetupCount,
smbClient.Capability.MaxParameterCount,
smbClient.Capability.MaxDataCount,
this.fileId,
(NtTransactSecurityInformation)securityInformation,
ReceivedSD);
SmbPacket response = this.SendPacketAndExpectResponse<SmbNtTransactSetSecurityDescResponsePacket>(packet);
if (response is SmbNtTransactSetSecurityDescResponsePacket)
{
SmbNtTransactSetSecurityDescResponsePacket querySecurityResponse =
(SmbNtTransactSetSecurityDescResponsePacket)response;
return (MessageStatus)querySecurityResponse.SmbHeader.Status;
}
else if (response is SmbErrorResponsePacket)
{
SmbErrorResponsePacket errorResponse = (SmbErrorResponsePacket)response;
buffer = null;
return (MessageStatus)errorResponse.SmbHeader.Status;
}
else
{
buffer = null;
return MessageStatus.INVALID_PARAMETER;
}
}
#endregion
#region 3.1.5.20 Server Requests Querying Quota Information
/// <summary>
/// Query Quota Information
/// </summary>
/// <param name="maxOutputBufferSize">Specify the maximum byte number to be returned.</param>
/// <param name="quotaInformationClass">FileInfoClass for Quota Information.</param>
/// <param name="inputBuffer">The input buffer in bytes, includes the quota information query parameters.</param>
/// <param name="outputBuffer">An array of one or more FILE_QUOTA_INFORMATION structures as specified in [MS-FSCC] section 2.4.33.</param>
/// <returns>NTSTATUS code.</returns>
public MessageStatus QueryQuotaInformation(
UInt32 maxOutputBufferSize,
UInt32 quotaInformationClass,
byte[] inputBuffer,
out byte[] outputBuffer)
{
SMB_QUERY_QUOTA_INFO smbQueryQuotaInfo = TypeMarshal.ToStruct<SMB_QUERY_QUOTA_INFO>(inputBuffer);
SmbPacket packet = this.smbClient.CreateNTTransQueryQuotaRequest(
this.fileId,
smbQueryQuotaInfo.ReturnSingleEntry > 0,
smbQueryQuotaInfo.RestartScan > 0,
(int)smbQueryQuotaInfo.SidListLength,
(int)smbQueryQuotaInfo.StartSidLength,
(int)smbQueryQuotaInfo.StartSidOffset);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbNtTransQueryQuotaResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_NT_TRANSACT)
{
throw new InvalidOperationException("No query quota information response.");
}
if (response is Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbNtTransQueryQuotaResponsePacket)
{
Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbNtTransQueryQuotaResponsePacket queryFsResponse =
(Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb.SmbNtTransQueryQuotaResponsePacket)response;
outputBuffer = queryFsResponse.SmbData.Data;
return MessageStatus.SUCCESS;
}
else
{
outputBuffer = null;
return (MessageStatus)response.SmbHeader.Status;
}
}
#endregion
#region 3.1.5.21 Server Requests Setting Quota Information
/// <summary>
/// Set Quota Information
/// </summary>
/// <param name="quotaInformationClass">FileInfoClass for Quota Information.</param>
/// <param name="inputBuffer">The input buffer in bytes, includes the quota information query parameters.</param>
/// <returns>NTSTATUS code.</returns>
public MessageStatus SetQuotaInformation(
UInt32 quotaInformationClass,
byte[] inputBuffer)
{
FILE_QUOTA_INFORMATION fileQuotaInfo = TypeMarshal.ToStruct<FILE_QUOTA_INFORMATION>(inputBuffer);
DateTime dateTime = DtypUtility.ToDateTime(fileQuotaInfo.ChangeTime);
SmbPacket packet = this.smbClient.CreateNTTransSetQuotaRequest(
this.fileId,
fileQuotaInfo.NextEntryOffset,
(ulong)dateTime.ToFileTimeUtc(),
(ulong)fileQuotaInfo.QuotaUsed,
(ulong)fileQuotaInfo.QuotaThreshold,
(ulong)fileQuotaInfo.QuotaLimit,
fileQuotaInfo.Sid);
SmbPacket response = this.SendPacketAndExpectResponse<NamespaceSmb.SmbNtTransSetQuotaResponsePacket>(packet);
if (response.SmbHeader.Command != SmbCommand.SMB_COM_NT_TRANSACT)
{
throw new InvalidOperationException("No set quota information response.");
}
else if (response is SmbErrorResponsePacket)
{
SmbErrorResponsePacket errorResponse = (SmbErrorResponsePacket)response;
return (MessageStatus)errorResponse.SmbHeader.Status;
}
return (MessageStatus)response.SmbHeader.Status;
}
#endregion
#endregion
#region SMB Transport Utility
private void SendSmbPacket(SmbPacket packet)
{
if (isSendSignedRequest)
{
CifsClientPerConnection connection =
this.smbClient.Context.GetConnection(ConnectionId);
CifsClientPerSession session = this.smbClient.Context.GetSession(ConnectionId, (ushort)this.sessionId);
packet.Sign(connection.ClientNextSendSequenceNumber, session.SessionKey);
}
this.smbClient.SendPacket(packet);
}
private SmbPacket SendPacketAndExpectResponse<T>(SmbPacket packet) where T : SmbPacket, new()
{
SendSmbPacket(packet);
DateTime endTime = DateTime.Now.Add(this.timeout);
do
{
SmbPacket response = this.smbClient.ExpectPacket(this.timeout);
if (response is T || response is SmbErrorResponsePacket)
{
return response;
}
} while (DateTime.Now < endTime);
throw new TimeoutException("This is timeout when waiting for the response of " + packet.ToString());
}
#endregion
}
}
| 43.432473 | 156 | 0.617916 | [
"MIT"
] | G-arj/WindowsProtocolTestSuites | TestSuites/FileServer/src/FSA/Adapter/SmbTransportAdapter.cs | 57,246 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace IdxSistemas.Models
{
[Table("ENTRADA_ANTECIPADA")]
public class EntradaAntecipada : BaseModel
{
[Required]
[MaxLength(8)]
public string NotaFiscal { get; set; }
[Required]
[MaxLength(4)]
public string Fornecedor { get; set; }
[ForeignKey("Fornecedor")]
public virtual Fornecedor Fornecedores { get; set; }
[MaxLength(1)]
public string ClassificacaoFiscal { get; set; }
[Required]
[MaxLength(14)]
public string Produto { get; set; }
[ForeignKey("Produto")]
public virtual Produto Produtos { get; set; }
[Required]
[MaxLength(2)]
public string Secao { get; set; }
[MaxLength(14)]
public string ProdutoPrincipal { get; set; }
[MaxLength(30)]
[Required]
public string DescricaoProduto { get; set; }
[MaxLength(20)]
[Required]
public string DescricaoEtiqueta1 { get; set; }
[MaxLength(20)]
public string DescricaoEtiqueta2 { get; set; }
public double? PrecoVista { get; set; } = 0.00;
public double? PrecoPrazo { get; set; } = 0.00;
[Required]
[MaxLength(2)]
public string Loja { get; set; }
public double? PrecoCusto { get; set; } = 0.00;
public int? Quantidade { get; set; } = 0;
[Column(TypeName = "date")]
public DateTime? DataEntrada { get; set; }
}
}
| 23.275362 | 60 | 0.57721 | [
"Unlicense"
] | IDX-Sistemas/S4-Varejo-Backend | Models/Models/EntradaAntecipada.cs | 1,606 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace CalendarsTester.Converters
{
public class EnumToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Enum.ToObject(targetType, value);
}
}
}
| 25.125 | 103 | 0.694859 | [
"MIT"
] | TheAlmightyBob/CalendarsTester | CalendarsTester/CalendarsTester/Converters/EnumToIntConverter.cs | 605 | 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("IntervalTreeLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("IntervalTreeLib")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[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("f6ae3660-91aa-4b0b-bd5e-09aea40cf4d9")]
// 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.405405 | 84 | 0.749472 | [
"EPL-1.0",
"BSD-3-Clause"
] | Kentalot/intervaltree | IntervalTreeLib/Properties/AssemblyInfo.cs | 1,424 | C# |
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using WizBot.Common.Attributes;
using WizBot.Modules.Gambling.Common;
using WizBot.Extensions;
using WizBot.Modules.Gambling.Common.Connect4;
using WizBot.Modules.Gambling.Services;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WizBot.Common;
using WizBot.Services;
namespace WizBot.Modules.Gambling
{
public partial class Gambling
{
[Group]
public class Connect4Commands : GamblingSubmodule<GamblingService>
{
private readonly DiscordSocketClient _client;
private readonly ICurrencyService _cs;
private static readonly string[] numbers = new string[] { ":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:" };
public Connect4Commands(DiscordSocketClient client, ICurrencyService cs, GamblingConfigService gamb)
: base(gamb)
{
_client = client;
_cs = cs;
}
[WizBotCommand, Aliases]
[RequireContext(ContextType.Guild)]
[WizBotOptionsAttribute(typeof(Connect4Game.Options))]
public async Task Connect4(params string[] args)
{
var (options, _) = OptionsParser.ParseFrom(new Connect4Game.Options(), args);
if (!await CheckBetOptional(options.Bet).ConfigureAwait(false))
return;
var newGame = new Connect4Game(ctx.User.Id, ctx.User.ToString(), options, _cs);
Connect4Game game;
if ((game = _service.Connect4Games.GetOrAdd(ctx.Channel.Id, newGame)) != newGame)
{
if (game.CurrentPhase != Connect4Game.Phase.Joining)
return;
newGame.Dispose();
//means game already exists, try to join
var joined = await game.Join(ctx.User.Id, ctx.User.ToString(), options.Bet).ConfigureAwait(false);
return;
}
if (options.Bet > 0)
{
if (!await _cs.RemoveAsync(ctx.User.Id, "Connect4-bet", options.Bet, true).ConfigureAwait(false))
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
_service.Connect4Games.TryRemove(ctx.Channel.Id, out _);
game.Dispose();
return;
}
}
game.OnGameStateUpdated += Game_OnGameStateUpdated;
game.OnGameFailedToStart += Game_OnGameFailedToStart;
game.OnGameEnded += Game_OnGameEnded;
_client.MessageReceived += _client_MessageReceived;
game.Initialize();
if (options.Bet == 0)
{
await ReplyConfirmLocalizedAsync(strs.connect4_created).ConfigureAwait(false);
}
else
{
await ReplyErrorLocalizedAsync(strs.connect4_created_bet(options.Bet + CurrencySign));
}
Task _client_MessageReceived(SocketMessage arg)
{
if (ctx.Channel.Id != arg.Channel.Id)
return Task.CompletedTask;
var _ = Task.Run(async () =>
{
bool success = false;
if (int.TryParse(arg.Content, out var col))
{
success = await game.Input(arg.Author.Id, col).ConfigureAwait(false);
}
if (success)
try { await arg.DeleteAsync().ConfigureAwait(false); } catch { }
else
{
if (game.CurrentPhase == Connect4Game.Phase.Joining
|| game.CurrentPhase == Connect4Game.Phase.Ended)
{
return;
}
RepostCounter++;
if (RepostCounter == 0)
try { msg = await ctx.Channel.SendMessageAsync("", embed: (Embed)msg.Embeds.First()).ConfigureAwait(false); } catch { }
}
});
return Task.CompletedTask;
}
Task Game_OnGameFailedToStart(Connect4Game arg)
{
if (_service.Connect4Games.TryRemove(ctx.Channel.Id, out var toDispose))
{
_client.MessageReceived -= _client_MessageReceived;
toDispose.Dispose();
}
return ErrorLocalizedAsync(strs.connect4_failed_to_start);
}
Task Game_OnGameEnded(Connect4Game arg, Connect4Game.Result result)
{
if (_service.Connect4Games.TryRemove(ctx.Channel.Id, out var toDispose))
{
_client.MessageReceived -= _client_MessageReceived;
toDispose.Dispose();
}
string title;
if (result == Connect4Game.Result.CurrentPlayerWon)
{
title = GetText(strs.connect4_won(Format.Bold(arg.CurrentPlayer.Username), Format.Bold(arg.OtherPlayer.Username)));
}
else if (result == Connect4Game.Result.OtherPlayerWon)
{
title = GetText(strs.connect4_won(Format.Bold(arg.OtherPlayer.Username), Format.Bold(arg.CurrentPlayer.Username)));
}
else
title = GetText(strs.connect4_draw);
return msg.ModifyAsync(x => x.Embed = _eb.Create()
.WithTitle(title)
.WithDescription(GetGameStateText(game))
.WithOkColor()
.Build());
}
}
private IUserMessage msg;
private int _repostCounter = 0;
private int RepostCounter
{
get => _repostCounter;
set
{
if (value < 0 || value > 7)
_repostCounter = 0;
else _repostCounter = value;
}
}
private async Task Game_OnGameStateUpdated(Connect4Game game)
{
var embed = _eb.Create()
.WithTitle($"{game.CurrentPlayer.Username} vs {game.OtherPlayer.Username}")
.WithDescription(GetGameStateText(game))
.WithOkColor();
if (msg is null)
msg = await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
else
await msg.ModifyAsync(x => x.Embed = embed.Build()).ConfigureAwait(false);
}
private string GetGameStateText(Connect4Game game)
{
var sb = new StringBuilder();
if (game.CurrentPhase == Connect4Game.Phase.P1Move ||
game.CurrentPhase == Connect4Game.Phase.P2Move)
sb.AppendLine(GetText(strs.connect4_player_to_move(Format.Bold(game.CurrentPlayer.Username))));
for (int i = Connect4Game.NumberOfRows; i > 0; i--)
{
for (int j = 0; j < Connect4Game.NumberOfColumns; j++)
{
var cur = game.GameState[i + (j * Connect4Game.NumberOfRows) - 1];
if (cur == Connect4Game.Field.Empty)
sb.Append("⚫"); //black circle
else if (cur == Connect4Game.Field.P1)
sb.Append("🔴"); //red circle
else
sb.Append("🔵"); //blue circle
}
sb.AppendLine();
}
for (int i = 0; i < Connect4Game.NumberOfColumns; i++)
{
sb.Append(numbers[i]);
}
return sb.ToString();
}
}
}
}
| 40.414286 | 151 | 0.480853 | [
"MIT"
] | Wizkiller96/WizBot | src/WizBot/Modules/Gambling/Connect4Commands.cs | 8,497 | C# |
using CamnLib.DbModels;
namespace CamnLib
{
public class InMemoryLog
{
private readonly System.Collections.Concurrent.ConcurrentQueue<UserAction> queue = new System.Collections.Concurrent.ConcurrentQueue<UserAction>();
public void Log(UserAction action)
{
queue.Enqueue(action);
}
public bool IsEmpty()
{
return queue.IsEmpty;
}
public UserAction Get()
{
if (queue.TryDequeue(out UserAction a))
{
return a;
}
return null;
}
}
}
| 17.466667 | 151 | 0.637405 | [
"MIT"
] | dnvgithub/camn | CamnLib/InMemoryLog.cs | 526 | C# |
using OpenTK;
namespace ChronosEngine.Interfaces {
public interface ICamera {
#region Methods
/// <summary>
/// Updates this camera
/// </summary>
/// <param name="time">
/// A <see cref="System.Double"/> containg the amount of time since the last update
/// </param>
void Update(double time);
void UpdateMouse(double time);
/// <summary>
/// Returns the Projection matrix for this camera
/// </summary>
/// <param name="matrix">
/// A <see cref="Matrix4"/> containing the Projection matrix
/// </param>
void GetProjectionMatrix(out Matrix4 matrix);
/// <summary>
/// Returns the Modelview Matrix for this camera
/// </summary>
/// <param name="matrix">
/// A <see cref="Matrix4"/> containing the Modelview Matrix
/// </param>
void GetViewMatrix(out Matrix4 matrix);
/// <summary>
/// Returns the Modelview Matrix multiplied by the Projection matrix
/// </summary>
/// <param name="result">
/// A <see cref="Matrix4"/> containg the multiplied matrices
/// </param>
void GetViewProjectionMatrix(out Matrix4 matrix);
#endregion
}
}
| 24.511111 | 85 | 0.655485 | [
"BSD-2-Clause"
] | chronium/ChronosEngine | ChronosEngine/Interfaces/ICamera.cs | 1,105 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace Dejkstra
{
class Program
{
static void Main()
{
StreamReader sr = new StreamReader("file.in");
StreamWriter sw = new StreamWriter("file.out");
int n;
String s;
int.TryParse(sr.ReadLine(),out n);
int[,] g = new int[n,n];
for (int i = 0; i < n; i++)
{
s = sr.ReadLine();
for (int j = 0; j < n; j++)
{
var allNums = Regex.Matches(@s, @"\d+");
g[i,j] = int.Parse(allNums[j].Value);
}
}
int[] d = new int[n];
for (int i = 0; i < n; i++)
d[i] = 200000;
d[0] = 0;
bool[] mark = new bool[n];
for (int i = 0; i < n; i++)
mark[i] = false;
int min=1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!mark[j] && d[j]<d[min])
{
min=j;
}
}
mark[min]=true;
sw.WriteLine((i+1)+")y = x" + (min + 1)+";");
for(int j = 0; j < n; j++)
{
if (!mark[j])
{
if ((d[min] + g[min, j]) < d[j])
{
sw.WriteLine("d(x" + (j + 1) + ") = min{" + inf(d[j]) + ", " + inf(d[min]) + "+" + inf(g[min, j]) + "} = " + (d[min] + g[min, j]) + ";");
d[j] = d[min] + g[min, j];
}
else
sw.WriteLine("d(x" + (j + 1) + ") = min{" + inf(d[j]) + ", " + inf(d[min]) + "+" + inf(g[min, j]) + "} = " + inf(d[j]) + ";");
}
}
for (int k = min; k < n; k++)
if(!mark[k]) min=k;
}
//for (int i = 0; i < n; i++)
//sw.WriteLine(d[i]);
sw.WriteLine("The shortest path: " + d[d.Length-1]);
sw.Close();
}
private static String inf(int i)
{
String s;
if (i == 200000)
s = "b";
else
s = i.ToString();
return s;
}
}
}
| 29.744186 | 165 | 0.311181 | [
"MIT"
] | simeonovanton/TelerikALPHA_nov2017 | 05.DSA/Graphs/Dijkstra.cs | 2,558 | C# |
using System.Collections.Generic;
using System.Linq;
namespace Fare
{
/// <summary>
/// Special automata operations.
/// </summary>
internal static class SpecialOperations
{
/// <summary>
/// Reverses the language of the given (non-singleton) automaton while returning the set of
/// new initial states.
/// </summary>
/// <param name="a">The automaton.</param>
/// <returns></returns>
internal static HashSet<State> Reverse(Automaton a)
{
// Reverse all edges.
var m = new Dictionary<State, HashSet<Transition>>();
HashSet<State> states = a.GetStates();
HashSet<State> accept = a.GetAcceptStates();
foreach (State r in states)
{
m.Add(r, new HashSet<Transition>());
r.Accept = false;
}
foreach (State r in states)
{
foreach (Transition t in r.Transitions)
{
m[t.To].Add(new Transition(t.Min, t.Max, r));
}
}
foreach (State r in states)
{
r.Transitions = m[r].ToList();
}
// Make new initial+final states.
a.Initial.Accept = true;
a.Initial = new State();
foreach (State r in accept)
{
a.Initial.AddEpsilon(r); // Ensures that all initial states are reachable.
}
a.IsDeterministic = false;
return accept;
}
}
}
| 29.054545 | 100 | 0.491865 | [
"MIT"
] | karoldeland/AutoFixture | Src/AutoFixture/Fare/SpecialOperations.cs | 1,600 | C# |
using System;
using System.Linq;
using System.Text;
using EventStore.Core.Data;
using EventStore.Core.Tests;
using EventStore.Projections.Core.Messages;
using NUnit.Framework;
using ResolvedEvent = EventStore.Projections.Core.Services.Processing.ResolvedEvent;
using EventStore.Projections.Core.Services;
namespace EventStore.Projections.Core.Tests.Services.core_projection {
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
public class when_the_projection_with_pending_writes_is_stopped<TLogFormat, TStreamId> : TestFixtureWithCoreProjectionStarted<TLogFormat, TStreamId> {
protected override void Given() {
_checkpointHandledThreshold = 2;
NoStream("$projections-projection-result");
NoStream("$projections-projection-order");
AllWritesToSucceed("$projections-projection-order");
NoStream("$projections-projection-checkpoint");
NoStream(FakeProjectionStateHandler._emit1StreamId);
AllWritesQueueUp();
}
protected override void When() {
//projection subscribes here
_bus.Publish(
EventReaderSubscriptionMessage.CommittedEventReceived.Sample(
new ResolvedEvent(
"/event_category/1", -1, "/event_category/1", -1, false, new TFPos(120, 110),
Guid.NewGuid(), "handle_this_type", false, "data1",
"metadata"), _subscriptionId, 0));
_bus.Publish(
EventReaderSubscriptionMessage.CommittedEventReceived.Sample(
new ResolvedEvent(
"/event_category/1", -1, "/event_category/1", -1, false, new TFPos(140, 130),
Guid.NewGuid(), "handle_this_type", false, "data2",
"metadata"), _subscriptionId, 1));
_bus.Publish(
EventReaderSubscriptionMessage.CommittedEventReceived.Sample(
new ResolvedEvent(
"/event_category/1", -1, "/event_category/1", -1, false, new TFPos(160, 150),
Guid.NewGuid(), "handle_this_type", false, "data3",
"metadata"), _subscriptionId, 2));
_coreProjection.Stop();
}
[Test]
public void a_projection_checkpoint_event_is_published() {
AllWriteComplete();
Assert.AreEqual(
1,
_writeEventHandler.HandledMessages.Count(v =>
v.Events.Any(e => e.EventType == ProjectionEventTypes.ProjectionCheckpoint)));
}
[Test]
public void other_events_are_not_written_after_the_checkpoint_write() {
AllWriteComplete();
var index =
_writeEventHandler.HandledMessages.FindIndex(
v => v.Events.Any(e => e.EventType == ProjectionEventTypes.ProjectionCheckpoint));
Assert.AreEqual(index + 1, _writeEventHandler.HandledMessages.Count());
}
}
}
| 38.208955 | 151 | 0.743359 | [
"Apache-2.0",
"CC0-1.0"
] | BearerPipelineTest/EventStore | src/EventStore.Projections.Core.Tests/Services/core_projection/when_the_projection_with_pending_writes_is_stopped.cs | 2,560 | C# |
using Ship;
using System;
using System.Collections.Generic;
using System.Linq;
using Tokens;
using UnityEngine;
namespace RulesList
{
public class EndPhaseCleanupRule
{
public EndPhaseCleanupRule()
{
SubscribeEvents();
}
private void SubscribeEvents()
{
Phases.Events.OnRoundStart += InitializeAll;
Phases.Events.OnRoundEnd += RegisterClearAll;
}
private void InitializeAll()
{
foreach (var ship in Roster.AllShips.Values)
{
ship.IsCannotAttackSecondTime = false;
}
}
private void RegisterClearAll()
{
Triggers.RegisterTrigger(new Trigger
{
Name = "End of the round: Clear all",
TriggerOwner = Players.PlayerNo.Player1,
TriggerType = TriggerTypes.OnRoundEnd,
EventHandler = EndPhaseClearAll
});
}
public void EndPhaseClearAll(object sender, System.EventArgs e)
{
List<GenericToken> tokensList = new List<GenericToken>();
foreach (var shipHolder in Roster.AllShips.Values)
{
ClearShipFlags(shipHolder);
ClearAssignedManeuvers(shipHolder);
shipHolder.ClearAlreadyExecutedActions();
List<GenericToken> allShipTokens = shipHolder.Tokens.GetAllTokens();
if (allShipTokens != null) tokensList.AddRange(allShipTokens.Where(n => n.Host.ShouldRemoveTokenInEndPhase(n)));
}
foreach (var shipHolder in Roster.Reserve)
{
ClearShipFlags(shipHolder);
ClearAssignedManeuvers(shipHolder);
shipHolder.ClearAlreadyExecutedActions();
List<GenericToken> allShipTokens = shipHolder.Tokens.GetAllTokens();
if (allShipTokens != null) tokensList.AddRange(allShipTokens.Where(n => n.Host.ShouldRemoveTokenInEndPhase(n)));
}
ClearShipTokens(tokensList, Triggers.FinishTrigger);
}
private void ClearShipTokens(List<GenericToken> tokensList, Action callback)
{
ActionsHolder.RemoveTokens(tokensList, callback);
}
private void ClearShipFlags(GenericShip ship)
{
ship.IsAttackPerformed = false;
ship.IsManeuverPerformed = false;
ship.IsSkipsActionSubPhase = false;
ship.IsBombAlreadyDropped = false;
ship.IsCannotAttackSecondTime = false;
ship.IsSystemsAbilityInactive = false;
ship.AlwaysShowAssignedManeuver = false;
ClearUsedArcs(ship);
}
private void ClearUsedArcs(GenericShip ship)
{
foreach (var arc in ship.ArcsInfo.Arcs)
{
arc.WasUsedForAttackThisRound = false;
}
foreach (var arc in ship.SectorsInfo.Arcs)
{
arc.WasUsedForAttackThisRound = false;
}
}
private void ClearAssignedManeuvers(GenericShip ship)
{
ship.ClearAssignedManeuver();
}
}
}
| 29.972222 | 128 | 0.579549 | [
"MIT"
] | belk/FlyCasual | Assets/Scripts/Model/Rules/RulesList/EndPhaseCleanupRule.cs | 3,239 | C# |
using NFluent;
using NUnit.Framework;
using pbrt.Core;
using pbrt.Media;
namespace Pbrt.Tests.Core
{
[TestFixture]
public class RayTests
{
[Test]
public void BasicTest()
{
var o = new Point3F(1.23f, 2.34f, 3.45f);
var d = new Vector3F(1, 0, -1);
var med = HomogeneousMedium.Default();
var ray = new Ray(o, d, 1000, 0, med);
Check.That(ray.O).IsEqualTo(o);
Check.That(ray.D).IsEqualTo(d);
Check.That(ray.TMax).IsEqualTo(1000);
Check.That(ray.Time).IsEqualTo(0);
Check.That(ray.Medium).IsSameReferenceAs(med);
Check.That(ray.HasNaNs).IsFalse();
Check.That(ray.At(1)).IsEqualTo(new Point3F(2.23f, 2.34f, 2.45f));
}
[Test]
[TestCase(0,0,0,0,0,0, false)]
[TestCase(0,0,0,0,0,float.NaN, true)]
[TestCase(0,0,0,0,float.NaN,0, true)]
[TestCase(0,0,0,float.NaN,0,0, true)]
[TestCase(0,0,float.NaN,0,0,0, true)]
[TestCase(0,float.NaN, 0,0,0,0,true)]
[TestCase(float.NaN, 0,0,0,0,0,true)]
public void HasNaNsTest(float ox, float oy, float oz, float dx, float dy, float dz, bool hasNaNs)
{
var o = new Point3F(ox, oy, oz);
var d = new Vector3F(dx, dy, dz);
var med = HomogeneousMedium.Default();
var ray = new Ray(o, d, 1000, 0, med);
Check.That(ray.HasNaNs).IsEqualTo(hasNaNs);
}
[Test]
public void ConstructorTest()
{
var ray = new Ray();
Check.That(ray.O).IsNull();
Check.That(ray.D).IsNull();
Check.That(ray.TMax).Not.IsFinite();
Check.That(ray.Time).IsEqualTo(0);
Check.That(ray.Medium).IsNull();
}
}
} | 32.910714 | 105 | 0.526858 | [
"Unlicense"
] | fremag/pbrt | pbrt/Pbrt.Tests/Core/RayTests.cs | 1,843 | C# |
using UnityEngine;
using UnityEngine.Rendering;
public class ChromaticAberrationEffect : MonoBehaviour
{
public static ChromaticAberrationEffect Instance { get; private set; }
private Volume volume;
private void Awake()
{
Instance = this;
volume = GetComponent<Volume>();
}
private void Update()
{
if(volume.weight > 0)
{
float decreaseSpeed = 1f;
volume.weight -= decreaseSpeed * Time.deltaTime;
}
}
public void SetWeight(float weight)
{
volume.weight = weight;
}
} | 19.633333 | 74 | 0.606112 | [
"MIT"
] | rafaelalma92/malaga-jam-21 | MálagaJam21/Assets/Scripts/Managers/ChromaticAberrationEffect.cs | 591 | 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 System.Runtime.Serialization;
using JetBrains.Annotations;
using UnitsNet.InternalHelpers;
using UnitsNet.Units;
#nullable enable
// ReSharper disable once CheckNamespace
namespace UnitsNet
{
/// <inheritdoc />
/// <summary>
/// A unit that represents a fractional change in size in response to a change in temperature.
/// </summary>
[DataContract]
public partial struct CoefficientOfThermalExpansion : IQuantity<CoefficientOfThermalExpansionUnit>, IEquatable<CoefficientOfThermalExpansion>, IComparable, IComparable<CoefficientOfThermalExpansion>, IConvertible, IFormattable
{
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
[DataMember(Name = "Value", Order = 0)]
private readonly double _value;
/// <summary>
/// The unit this quantity was constructed with.
/// </summary>
[DataMember(Name = "Unit", Order = 1)]
private readonly CoefficientOfThermalExpansionUnit? _unit;
static CoefficientOfThermalExpansion()
{
BaseDimensions = new BaseDimensions(0, 0, 0, 0, -1, 0, 0);
BaseUnit = CoefficientOfThermalExpansionUnit.InverseKelvin;
MaxValue = new CoefficientOfThermalExpansion(double.MaxValue, BaseUnit);
MinValue = new CoefficientOfThermalExpansion(double.MinValue, BaseUnit);
QuantityType = QuantityType.CoefficientOfThermalExpansion;
Units = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast<CoefficientOfThermalExpansionUnit>().Except(new CoefficientOfThermalExpansionUnit[]{ CoefficientOfThermalExpansionUnit.Undefined }).ToArray();
Zero = new CoefficientOfThermalExpansion(0, BaseUnit);
Info = new QuantityInfo<CoefficientOfThermalExpansionUnit>("CoefficientOfThermalExpansion",
new UnitInfo<CoefficientOfThermalExpansionUnit>[]
{
new UnitInfo<CoefficientOfThermalExpansionUnit>(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, "InverseDegreeCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius)),
new UnitInfo<CoefficientOfThermalExpansionUnit>(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, "InverseDegreeFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit)),
new UnitInfo<CoefficientOfThermalExpansionUnit>(CoefficientOfThermalExpansionUnit.InverseKelvin, "InverseKelvin", new BaseUnits(temperature: TemperatureUnit.Kelvin)),
},
BaseUnit, Zero, BaseDimensions, QuantityType.CoefficientOfThermalExpansion);
DefaultConversionFunctions = new UnitConverter();
RegisterDefaultConversions(DefaultConversionFunctions);
}
/// <summary>
/// Creates the quantity with the given numeric value and unit.
/// </summary>
/// <param name="value">The numeric value to construct this quantity with.</param>
/// <param name="unit">The unit representation to construct this quantity with.</param>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public CoefficientOfThermalExpansion(double value, CoefficientOfThermalExpansionUnit unit)
{
if (unit == CoefficientOfThermalExpansionUnit.Undefined)
throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit));
_value = Guard.EnsureValidNumber(value, nameof(value));
_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="value">The numeric value to construct 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 CoefficientOfThermalExpansion(double value, UnitSystem unitSystem)
{
if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
_value = Guard.EnsureValidNumber(value, nameof(value));
_unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
}
#region Static Properties
/// <summary>
/// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="CoefficientOfThermalExpansion" /> instances.
/// </summary>
public static UnitConverter DefaultConversionFunctions { get; }
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
public static QuantityInfo<CoefficientOfThermalExpansionUnit> Info { get; }
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public static BaseDimensions BaseDimensions { get; }
/// <summary>
/// The base unit of CoefficientOfThermalExpansion, which is InverseKelvin. All conversions go via this value.
/// </summary>
public static CoefficientOfThermalExpansionUnit BaseUnit { get; }
/// <summary>
/// Represents the largest possible value of CoefficientOfThermalExpansion
/// </summary>
[Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")]
public static CoefficientOfThermalExpansion MaxValue { get; }
/// <summary>
/// Represents the smallest possible value of CoefficientOfThermalExpansion
/// </summary>
[Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")]
public static CoefficientOfThermalExpansion MinValue { get; }
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
[Obsolete("QuantityType will be removed in the future. Use the Info property instead.")]
public static QuantityType QuantityType { get; }
/// <summary>
/// All units of measurement for the CoefficientOfThermalExpansion quantity.
/// </summary>
public static CoefficientOfThermalExpansionUnit[] Units { get; }
/// <summary>
/// Gets an instance of this quantity with a value of 0 in the base unit InverseKelvin.
/// </summary>
public static CoefficientOfThermalExpansion Zero { get; }
#endregion
#region Properties
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
public double Value => _value;
Enum IQuantity.Unit => Unit;
/// <inheritdoc />
public CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit);
/// <inheritdoc />
public QuantityInfo<CoefficientOfThermalExpansionUnit> QuantityInfo => Info;
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
QuantityInfo IQuantity.QuantityInfo => Info;
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
[Obsolete("QuantityType will be removed in the future. Use the Info property instead.")]
public QuantityType Type => QuantityType.CoefficientOfThermalExpansion;
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public BaseDimensions Dimensions => CoefficientOfThermalExpansion.BaseDimensions;
#endregion
#region Conversion Properties
/// <summary>
/// Gets a <see cref="double"/> value of this quantity converted into <see cref="CoefficientOfThermalExpansionUnit.InverseDegreeCelsius"/>
/// </summary>
public double InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius);
/// <summary>
/// Gets a <see cref="double"/> value of this quantity converted into <see cref="CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit"/>
/// </summary>
public double InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit);
/// <summary>
/// Gets a <see cref="double"/> value of this quantity converted into <see cref="CoefficientOfThermalExpansionUnit.InverseKelvin"/>
/// </summary>
public double InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin);
#endregion
#region Static Methods
/// <summary>
/// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance.
/// </summary>
/// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param>
internal static void RegisterDefaultConversions(UnitConverter unitConverter)
{
// Register in unit converter: BaseUnit -> CoefficientOfThermalExpansionUnit
unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, quantity => new CoefficientOfThermalExpansion(quantity.Value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius));
unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, quantity => new CoefficientOfThermalExpansion(quantity.Value * 5 / 9, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit));
// Register in unit converter: BaseUnit <-> BaseUnit
unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => quantity);
// Register in unit converter: CoefficientOfThermalExpansionUnit -> BaseUnit
unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => new CoefficientOfThermalExpansion(quantity.Value, CoefficientOfThermalExpansionUnit.InverseKelvin));
unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => new CoefficientOfThermalExpansion(quantity.Value * 9 / 5, CoefficientOfThermalExpansionUnit.InverseKelvin));
}
internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache)
{
unitAbbreviationsCache.PerformAbbreviationMapping(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"°C⁻¹", "1/°C"});
unitAbbreviationsCache.PerformAbbreviationMapping(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, new CultureInfo("en-US"), false, true, new string[]{"°F⁻¹", "1/°F"});
unitAbbreviationsCache.PerformAbbreviationMapping(CoefficientOfThermalExpansionUnit.InverseKelvin, new CultureInfo("en-US"), false, true, new string[]{"K⁻¹", "1/K"});
}
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
public static string GetAbbreviation(CoefficientOfThermalExpansionUnit 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(CoefficientOfThermalExpansionUnit unit, IFormatProvider? provider)
{
return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider);
}
#endregion
#region Static Factory Methods
/// <summary>
/// Creates a <see cref="CoefficientOfThermalExpansion"/> from <see cref="CoefficientOfThermalExpansionUnit.InverseDegreeCelsius"/>.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(QuantityValue inversedegreecelsius)
{
double value = (double) inversedegreecelsius;
return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius);
}
/// <summary>
/// Creates a <see cref="CoefficientOfThermalExpansion"/> from <see cref="CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit"/>.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(QuantityValue inversedegreefahrenheit)
{
double value = (double) inversedegreefahrenheit;
return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit);
}
/// <summary>
/// Creates a <see cref="CoefficientOfThermalExpansion"/> from <see cref="CoefficientOfThermalExpansionUnit.InverseKelvin"/>.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static CoefficientOfThermalExpansion FromInverseKelvin(QuantityValue inversekelvin)
{
double value = (double) inversekelvin;
return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseKelvin);
}
/// <summary>
/// Dynamically convert from value and unit enum <see cref="CoefficientOfThermalExpansionUnit" /> to <see cref="CoefficientOfThermalExpansion" />.
/// </summary>
/// <param name="value">Value to convert from.</param>
/// <param name="fromUnit">Unit to convert from.</param>
/// <returns>CoefficientOfThermalExpansion unit value.</returns>
public static CoefficientOfThermalExpansion From(QuantityValue value, CoefficientOfThermalExpansionUnit fromUnit)
{
return new CoefficientOfThermalExpansion((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 CoefficientOfThermalExpansion 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 CoefficientOfThermalExpansion Parse(string str, IFormatProvider? provider)
{
return QuantityParser.Default.Parse<CoefficientOfThermalExpansion, CoefficientOfThermalExpansionUnit>(
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(string? str, out CoefficientOfThermalExpansion 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(string? str, IFormatProvider? provider, out CoefficientOfThermalExpansion result)
{
return QuantityParser.Default.TryParse<CoefficientOfThermalExpansion, CoefficientOfThermalExpansionUnit>(
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 CoefficientOfThermalExpansionUnit 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>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</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 CoefficientOfThermalExpansionUnit ParseUnit(string str, IFormatProvider? provider)
{
return UnitParser.Default.Parse<CoefficientOfThermalExpansionUnit>(str, provider);
}
/// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.CoefficientOfThermalExpansionUnit)"/>
public static bool TryParseUnit(string str, out CoefficientOfThermalExpansionUnit 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 CoefficientOfThermalExpansionUnit unit)
{
return UnitParser.Default.TryParse<CoefficientOfThermalExpansionUnit>(str, provider, out unit);
}
#endregion
#region Arithmetic Operators
/// <summary>Negate the value.</summary>
public static CoefficientOfThermalExpansion operator -(CoefficientOfThermalExpansion right)
{
return new CoefficientOfThermalExpansion(-right.Value, right.Unit);
}
/// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from adding two <see cref="CoefficientOfThermalExpansion"/>.</summary>
public static CoefficientOfThermalExpansion operator +(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right)
{
return new CoefficientOfThermalExpansion(left.Value + right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from subtracting two <see cref="CoefficientOfThermalExpansion"/>.</summary>
public static CoefficientOfThermalExpansion operator -(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right)
{
return new CoefficientOfThermalExpansion(left.Value - right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from multiplying value and <see cref="CoefficientOfThermalExpansion"/>.</summary>
public static CoefficientOfThermalExpansion operator *(double left, CoefficientOfThermalExpansion right)
{
return new CoefficientOfThermalExpansion(left * right.Value, right.Unit);
}
/// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from multiplying value and <see cref="CoefficientOfThermalExpansion"/>.</summary>
public static CoefficientOfThermalExpansion operator *(CoefficientOfThermalExpansion left, double right)
{
return new CoefficientOfThermalExpansion(left.Value * right, left.Unit);
}
/// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from dividing <see cref="CoefficientOfThermalExpansion"/> by value.</summary>
public static CoefficientOfThermalExpansion operator /(CoefficientOfThermalExpansion left, double right)
{
return new CoefficientOfThermalExpansion(left.Value / right, left.Unit);
}
/// <summary>Get ratio value from dividing <see cref="CoefficientOfThermalExpansion"/> by <see cref="CoefficientOfThermalExpansion"/>.</summary>
public static double operator /(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right)
{
return left.InverseKelvin / right.InverseKelvin;
}
#endregion
#region Equality / IComparable
/// <summary>Returns true if less or equal to.</summary>
public static bool operator <=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right)
{
return left.Value <= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than or equal to.</summary>
public static bool operator >=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right)
{
return left.Value >= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if less than.</summary>
public static bool operator <(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right)
{
return left.Value < right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than.</summary>
public static bool operator >(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right)
{
return left.Value > right.GetValueAs(left.Unit);
}
/// <summary>Returns true if exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(CoefficientOfThermalExpansion, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator ==(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right)
{
return left.Equals(right);
}
/// <summary>Returns true if not exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(CoefficientOfThermalExpansion, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator !=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right)
{
return !(left == right);
}
/// <inheritdoc />
public int CompareTo(object obj)
{
if (obj is null) throw new ArgumentNullException(nameof(obj));
if (!(obj is CoefficientOfThermalExpansion objCoefficientOfThermalExpansion)) throw new ArgumentException("Expected type CoefficientOfThermalExpansion.", nameof(obj));
return CompareTo(objCoefficientOfThermalExpansion);
}
/// <inheritdoc />
public int CompareTo(CoefficientOfThermalExpansion other)
{
return _value.CompareTo(other.GetValueAs(this.Unit));
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(CoefficientOfThermalExpansion, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public override bool Equals(object obj)
{
if (obj is null || !(obj is CoefficientOfThermalExpansion objCoefficientOfThermalExpansion))
return false;
return Equals(objCoefficientOfThermalExpansion);
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(CoefficientOfThermalExpansion, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public bool Equals(CoefficientOfThermalExpansion other)
{
return _value.Equals(other.GetValueAs(this.Unit));
}
/// <summary>
/// <para>
/// Compare equality to another CoefficientOfThermalExpansion 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(CoefficientOfThermalExpansion 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 CoefficientOfThermalExpansion.</returns>
public override int GetHashCode()
{
return new { Info.Name, 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(CoefficientOfThermalExpansionUnit 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 is null)
throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
if (firstUnitInfo == 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 CoefficientOfThermalExpansionUnit unitAsCoefficientOfThermalExpansionUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit));
return As(unitAsCoefficientOfThermalExpansionUnit);
}
/// <summary>
/// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation <paramref name="unit" />.
/// </summary>
/// <param name="unit">The unit to convert to.</param>
/// <returns>A CoefficientOfThermalExpansion with the specified unit.</returns>
public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit)
{
return ToUnit(unit, DefaultConversionFunctions);
}
/// <summary>
/// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />.
/// </summary>
/// <param name="unit">The unit to convert to.</param>
/// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param>
/// <returns>A CoefficientOfThermalExpansion with the specified unit.</returns>
public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit, UnitConverter unitConverter)
{
if (Unit == unit)
{
// Already in requested units.
return this;
}
else if (unitConverter.TryGetConversionFunction((typeof(CoefficientOfThermalExpansion), Unit, typeof(CoefficientOfThermalExpansion), unit), out var conversionFunction))
{
// Direct conversion to requested unit found. Return the converted quantity.
var converted = conversionFunction(this);
return (CoefficientOfThermalExpansion)converted;
}
else if (Unit != BaseUnit)
{
// Direct conversion to requested unit NOT found. Convert to BaseUnit, and then from BaseUnit to requested unit.
var inBaseUnits = ToUnit(BaseUnit);
return inBaseUnits.ToUnit(unit);
}
else
{
throw new NotImplementedException($"Can not convert {Unit} to {unit}.");
}
}
/// <inheritdoc />
IQuantity IQuantity.ToUnit(Enum unit)
{
if (!(unit is CoefficientOfThermalExpansionUnit unitAsCoefficientOfThermalExpansionUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit));
return ToUnit(unitAsCoefficientOfThermalExpansionUnit, DefaultConversionFunctions);
}
/// <inheritdoc />
IQuantity IQuantity.ToUnit(Enum unit, UnitConverter unitConverter)
{
if (!(unit is CoefficientOfThermalExpansionUnit unitAsCoefficientOfThermalExpansionUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit));
return ToUnit(unitAsCoefficientOfThermalExpansionUnit, unitConverter);
}
/// <inheritdoc cref="IQuantity.ToUnit(UnitSystem)"/>
public CoefficientOfThermalExpansion ToUnit(UnitSystem unitSystem)
{
if (unitSystem is null)
throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
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<CoefficientOfThermalExpansionUnit> IQuantity<CoefficientOfThermalExpansionUnit>.ToUnit(CoefficientOfThermalExpansionUnit unit) => ToUnit(unit);
/// <inheritdoc />
IQuantity<CoefficientOfThermalExpansionUnit> IQuantity<CoefficientOfThermalExpansionUnit>.ToUnit(CoefficientOfThermalExpansionUnit unit, UnitConverter unitConverter) => ToUnit(unit, unitConverter);
/// <inheritdoc />
IQuantity<CoefficientOfThermalExpansionUnit> IQuantity<CoefficientOfThermalExpansionUnit>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem);
private double GetValueAs(CoefficientOfThermalExpansionUnit unit)
{
var converted = ToUnit(unit);
return (double)converted.Value;
}
#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(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(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 implicitly 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(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="provider">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? provider)
{
return QuantityFormatter.Format<CoefficientOfThermalExpansionUnit>(this, format, provider);
}
#endregion
#region IConvertible Methods
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to bool is not supported.");
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to char is not supported.");
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} 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(CoefficientOfThermalExpansion))
return this;
else if (conversionType == typeof(CoefficientOfThermalExpansionUnit))
return Unit;
else if (conversionType == typeof(QuantityType))
return CoefficientOfThermalExpansion.QuantityType;
else if (conversionType == typeof(QuantityInfo))
return CoefficientOfThermalExpansion.Info;
else if (conversionType == typeof(BaseDimensions))
return CoefficientOfThermalExpansion.BaseDimensions;
else
throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} 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
}
}
| 49.899151 | 317 | 0.652782 | [
"MIT-feh"
] | mikepharesjr/UnitsNet | UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs | 47,018 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using MyDriving.DataObjects;
namespace MyDriving.DataStore.Abstractions
{
public interface ITripStore : IBaseStore<Trip>
{
}
} | 27 | 85 | 0.727273 | [
"MIT"
] | 04diiguyi/openhack-devops-team | MobileApps/MyDriving/MyDriving.DataStore.Abstractions/ITripStore.cs | 299 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Halcyon.HAL.Attributes;
using Threax.AspNetCore.Halcyon.Ext;
namespace DevApp.InputModels
{
public partial class ValueInput
{
//You can add your own customizations here. These will not be overwritten by the model generator.
//See ValueInput.Generated for the generated code
}
} | 28.375 | 105 | 0.768722 | [
"Apache-2.0"
] | threax/AspNetCore.Swashbuckle.Convention | src/DevApp/InputModels/ValueInput.cs | 454 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace exploitation_csrf.Areas.Identity.Pages.Account.Manage
{
public class ChangePasswordModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<ChangePasswordModel> _logger;
public ChangePasswordModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<ChangePasswordModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
[TempData]
public string StatusMessage { get; set; }
public class InputModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (!hasPassword)
{
return RedirectToPage("./SetPassword");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
if (!changePasswordResult.Succeeded)
{
foreach (var error in changePasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
await _signInManager.RefreshSignInAsync(user);
_logger.LogInformation("User changed their password successfully.");
StatusMessage = "Your password has been changed.";
return RedirectToPage();
}
}
}
| 33.821782 | 129 | 0.591335 | [
"MIT"
] | PacktPublishing/Writing-Secure-Code-in-ASP.NET | cross_site_request_forgery/exploitation_csrf/exploitation_csrf/Areas/Identity/Pages/Account/Manage/ChangePassword.cshtml.cs | 3,416 | C# |
// <auto-generated />
using System;
using FlashTest.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace FlashTest.Migrations
{
[DbContext(typeof(FlashTestDbContext))]
[Migration("20200604091046_Upgraded_To_Abp_5_9")]
partial class Upgraded_To_Abp_5_9
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration")
.HasColumnType("int");
b.Property<DateTime>("ExecutionTime")
.HasColumnType("datetime2");
b.Property<int?>("ImpersonatorTenantId")
.HasColumnType("int");
b.Property<long?>("ImpersonatorUserId")
.HasColumnType("bigint");
b.Property<string>("MethodName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<string>("ReturnValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("ServiceName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsGranted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<long?>("UserLinkId")
.HasColumnType("bigint");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("LoginProvider")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<byte>("Result")
.HasColumnType("tinyint");
b.Property<string>("TenancyName")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("UserNameOrEmailAddress")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<long>("OrganizationUnitId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime?>("ExpireDate")
.HasColumnType("datetime2");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsAbandoned")
.HasColumnType("bit");
b.Property<string>("JobArgs")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime")
.HasColumnType("datetime2");
b.Property<DateTime>("NextTryTime")
.HasColumnType("datetime2");
b.Property<byte>("Priority")
.HasColumnType("tinyint");
b.Property<short>("TryCount")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name", "UserId")
.IsUnique();
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.DynamicEntityParameters.DynamicParameter", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("InputType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ParameterName")
.HasColumnType("nvarchar(450)");
b.Property<string>("Permission")
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ParameterName", "TenantId")
.IsUnique()
.HasFilter("[ParameterName] IS NOT NULL AND [TenantId] IS NOT NULL");
b.ToTable("AbpDynamicParameters");
});
modelBuilder.Entity("Abp.DynamicEntityParameters.DynamicParameterValue", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("DynamicParameterId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("DynamicParameterId");
b.ToTable("AbpDynamicParameterValues");
});
modelBuilder.Entity("Abp.DynamicEntityParameters.EntityDynamicParameter", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("DynamicParameterId")
.HasColumnType("int");
b.Property<string>("EntityFullName")
.HasColumnType("nvarchar(450)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DynamicParameterId");
b.HasIndex("EntityFullName", "DynamicParameterId", "TenantId")
.IsUnique()
.HasFilter("[EntityFullName] IS NOT NULL AND [TenantId] IS NOT NULL");
b.ToTable("AbpEntityDynamicParameters");
});
modelBuilder.Entity("Abp.DynamicEntityParameters.EntityDynamicParameterValue", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("EntityDynamicParameterId")
.HasColumnType("int");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("EntityDynamicParameterId");
b.ToTable("AbpEntityDynamicParameterValues");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("ChangeTime")
.HasColumnType("datetime2");
b.Property<byte>("ChangeType")
.HasColumnType("tinyint");
b.Property<long>("EntityChangeSetId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(48)")
.HasMaxLength(48);
b.Property<string>("EntityTypeFullName")
.HasColumnType("nvarchar(192)")
.HasMaxLength(192);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("EntityChangeSetId");
b.HasIndex("EntityTypeFullName", "EntityId");
b.ToTable("AbpEntityChanges");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<string>("ExtensionData")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ImpersonatorTenantId")
.HasColumnType("int");
b.Property<long?>("ImpersonatorUserId")
.HasColumnType("bigint");
b.Property<string>("Reason")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "CreationTime");
b.HasIndex("TenantId", "Reason");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpEntityChangeSets");
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<long>("EntityChangeId")
.HasColumnType("bigint");
b.Property<string>("NewValue")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("OriginalValue")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("PropertyName")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("PropertyTypeFullName")
.HasColumnType("nvarchar(192)")
.HasMaxLength(192);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("EntityChangeId");
b.ToTable("AbpEntityPropertyChanges");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("Icon")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsDisabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<string>("TenantIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int>("State")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<Guid>("TenantNotificationId")
.HasColumnType("uniqueidentifier");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(95)")
.HasMaxLength(95);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<long?>("ParentId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnitRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<long>("OrganizationUnitId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "RoleId");
b.ToTable("AbpOrganizationUnitRoles");
});
modelBuilder.Entity("Abp.Webhooks.WebhookEvent", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("WebhookName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("AbpWebhookEvents");
});
modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<string>("Response")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ResponseStatusCode")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<Guid>("WebhookEventId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("WebhookSubscriptionId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("WebhookEventId");
b.ToTable("AbpWebhookSendAttempts");
});
modelBuilder.Entity("Abp.Webhooks.WebhookSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Headers")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("Secret")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("WebhookUri")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Webhooks")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("AbpWebhookSubscriptions");
});
modelBuilder.Entity("FlashTest.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)")
.HasMaxLength(5000);
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDefault")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsStatic")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("FlashTest.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("AuthenticationSource")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsEmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsLockoutEnabled")
.HasColumnType("bit");
b.Property<bool>("IsPhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsTwoFactorEnabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LockoutEndDateUtc")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("FlashTest.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ConnectionString")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("EditionId")
.HasColumnType("int");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId")
.HasColumnType("int");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("FlashTest.Authorization.Roles.Role", null)
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("FlashTest.Authorization.Users.User", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("FlashTest.Authorization.Users.User", null)
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("FlashTest.Authorization.Users.User", null)
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("FlashTest.Authorization.Users.User", null)
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("FlashTest.Authorization.Users.User", null)
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.DynamicEntityParameters.DynamicParameterValue", b =>
{
b.HasOne("Abp.DynamicEntityParameters.DynamicParameter", "DynamicParameter")
.WithMany("DynamicParameterValues")
.HasForeignKey("DynamicParameterId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.DynamicEntityParameters.EntityDynamicParameter", b =>
{
b.HasOne("Abp.DynamicEntityParameters.DynamicParameter", "DynamicParameter")
.WithMany()
.HasForeignKey("DynamicParameterId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.DynamicEntityParameters.EntityDynamicParameterValue", b =>
{
b.HasOne("Abp.DynamicEntityParameters.EntityDynamicParameter", "EntityDynamicParameter")
.WithMany()
.HasForeignKey("EntityDynamicParameterId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChangeSet", null)
.WithMany("EntityChanges")
.HasForeignKey("EntityChangeSetId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChange", null)
.WithMany("PropertyChanges")
.HasForeignKey("EntityChangeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b =>
{
b.HasOne("Abp.Webhooks.WebhookEvent", "WebhookEvent")
.WithMany()
.HasForeignKey("WebhookEventId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("FlashTest.Authorization.Roles.Role", b =>
{
b.HasOne("FlashTest.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("FlashTest.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("FlashTest.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("FlashTest.Authorization.Users.User", b =>
{
b.HasOne("FlashTest.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("FlashTest.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("FlashTest.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("FlashTest.MultiTenancy.Tenant", b =>
{
b.HasOne("FlashTest.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("FlashTest.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("FlashTest.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("FlashTest.Authorization.Roles.Role", null)
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("FlashTest.Authorization.Users.User", null)
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.043288 | 125 | 0.446423 | [
"MIT"
] | sagarshelkeneo/client_flashtest | aspnet-core/src/FlashTest.EntityFrameworkCore/Migrations/20200604091046_Upgraded_To_Abp_5_9.Designer.cs | 67,606 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using xavierHTML.CSS;
using xavierHTML.CSS.Style;
using xavierHTML.DOM;
using xavierHTML.DOM.Elements;
using xavierHTML.Layout;
using xavierHTML.Layout.BoxModel;
namespace Surf.Rasterization
{
public class DisplayList : IReadOnlyList<DisplayCommand>
{
private readonly List<DisplayCommand> _list = new List<DisplayCommand>();
private StyledNode _styleTree;
private Rectangle _viewport;
private DisplayList() {}
public DisplayList(Document document, Rectangle viewport)
{
_viewport = viewport;
Render(document);
}
public static readonly DisplayList Empty = new DisplayList();
public IEnumerator<DisplayCommand> GetEnumerator() => _list.AsReadOnly().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public int Count => _list.Count;
public DisplayCommand this[int index] => _list[index];
public Rectangle Viewport
{
get => _viewport;
set
{
_viewport = value;
LayoutAndRender();
}
}
public void Render(Document document)
{
var styleRules = document.Stylesheets.Aggregate(
new List<Rule>(),
(rules, stylesheet) =>
{
rules.AddRange(stylesheet.Rules);
return rules;
});
_styleTree = StyledNode.FromElement(document.DocumentElement, styleRules);
LayoutAndRender();
}
private void LayoutAndRender()
{
_list.Clear();
if (_styleTree == null) return;
var layoutTree = Box.FromStyledNode(_styleTree);
PrintLayoutTree(layoutTree);
layoutTree.Layout(_viewport.Size);
Render(layoutTree);
}
private void PrintLayoutTree(Box box, int level = 0)
{
var label = box is NodeBox node
? node.Style.Node is Element element
? element.TagName
: node.Style.Node.ToString()
: "[Anon]";
Console.WriteLine(label.PadLeft(level));
foreach (var child in box.Children)
{
PrintLayoutTree(child, level += 1);
}
}
private void Render(Box box)
{
if (box == null) return;
var isBoxOpaque = box is NodeBox nodeBox &&
nodeBox.Style.BackgroundColor.A > 0 &&
nodeBox.Style.BorderColor.A > 0;
if (isBoxOpaque)
_list.Add(new SolidColor((NodeBox) box));
foreach (var child in box.Children)
{
Render(child);
}
}
}
}
| 28.339623 | 97 | 0.536951 | [
"BSD-3-Clause"
] | chances/surf | Surf/Rasterization/DisplayList.cs | 3,004 | C# |
using System;
using System.Collections.Generic;
using System.Maui;
using NUnit.Framework;
namespace System.Maui.Xaml.UnitTests.A
{
public partial class Bz31234 : ContentPage
{
public Bz31234 ()
{
InitializeComponent ();
}
public Bz31234 (bool useCompiledXaml)
{
//this stub will be replaced at compile time
}
[TestFixture]
public class Tests
{
[TestCase(true), TestCase(false)]
public void ShouldPass (bool useCompiledXaml)
{
new Bz31234 (useCompiledXaml);
Assert.Pass ();
}
}
}
} | 16.181818 | 48 | 0.689139 | [
"MIT"
] | AswinPG/maui | System.Maui.Xaml.UnitTests/Issues/Bz31234/A/Bz31234.xaml.cs | 534 | C# |
using System;
namespace Session04.OnionArchitecture.Core.Contracts
{
public class Class1
{
}
}
| 12.111111 | 52 | 0.697248 | [
"Apache-2.0"
] | IMICTO/dotnetcore3 | Session04/Session04.OnionArchitecture/Session04.OnionArchitecture.Core.Contracts/Class1.cs | 111 | C# |
using System;
using System.Runtime.InteropServices;
using System.Text;
using ApiHooker.Utils;
namespace ApiHooker
{
public class ProcessManager
{
protected ProcessManager() { }
public ProcessInformation ProcessInformation { get; protected set; }
public System.Diagnostics.Process Process { get; protected set; }
public RemoteMemoryManager MemoryManager { get; protected set; }
public string InjectedDllPath { get; protected set; }
public uint InjectedDllBaseAddr { get; protected set; }
protected ProcessManager(ProcessInformation procInfo)
{
ProcessInformation = procInfo;
Process = System.Diagnostics.Process.GetProcessById(ProcessInformation.dwProcessId);
MemoryManager = new RemoteMemoryManager(ProcessInformation.hProcess);
}
public static ProcessManager LaunchSuspended(string exePath, string arguments = "", string workingDirectory = null)
{
exePath = FileUtils.GetFullPath(exePath);
var commandLine = exePath + (String.IsNullOrEmpty(arguments) ? "" : " " + arguments);
workingDirectory = workingDirectory ?? Environment.CurrentDirectory;
ProcessInformation procInfo;
var flags = ProcessCreationFlags.CreateSuspended | ProcessCreationFlags.CreateNewConsole;
if (!WinApi.CreateProcess(exePath, commandLine, null, null, false, flags, IntPtr.Zero, workingDirectory, new StartupInfo { wShowWindow = 1 }, out procInfo))
throw new Exception("Could not create process!");
return new ProcessManager(procInfo);
}
public uint CallRemoteFunction(long funcAddr, IntPtr data, bool wait = true)
{
uint threadId;
var newThreadHandle = WinApi.CreateRemoteThread(ProcessInformation.hProcess, IntPtr.Zero, 0, new IntPtr(funcAddr), data, 0, out threadId);
if (!wait)
return 0;
WinApi.WaitForSingleObject(newThreadHandle, (uint)WaitForSingleObjectTimeout.Infinite);
uint returnValue;
if (!WinApi.GetExitCodeThread(newThreadHandle, out returnValue))
throw new Exception("Could not get return value after calling remote function!");
return returnValue;
}
static long GetProcAddr(string libraryPath, string funcName, bool absolute = false)
{
var baseAddr = WinApi.LoadLibrary(libraryPath);
var absAddr = WinApi.GetProcAddress(baseAddr, funcName).ToInt64();
return absolute ? absAddr : absAddr - baseAddr.ToInt64();
}
public void InjectDll(string injectionDllPath)
{
InjectedDllPath = injectionDllPath;
var hLoadLibrary = GetProcAddr("kernel32.dll", "LoadLibraryA", true);
InjectedDllBaseAddr = CallRemoteFunction(hLoadLibrary, MemoryManager.Copy(injectionDllPath));
}
[StructLayout(LayoutKind.Sequential)]
struct InitParams
{
public UInt32 tcpPort;
}
public void InjectHookerLib(int tcpPort)
{
if (ProcessHelper.Is64Bit(Process.Handle))
throw new Exception("Injecting into 64-bit processes is not supported yet!");
var injDllPath = AppDomain.CurrentDomain.BaseDirectory + "ApiHookerInject_x86.dll";
InjectDll(injDllPath);
var initAddr = GetProcAddr(injDllPath, "Init");
CallRemoteFunction(InjectedDllBaseAddr + initAddr, MemoryManager.Copy(new InitParams { tcpPort = (uint)tcpPort }), false);
}
public void ResumeMainThread()
{
WinApi.ResumeThread(ProcessInformation.hThread);
}
}
} | 41.505376 | 169 | 0.640155 | [
"MIT"
] | koczkatamas/apihooker | WindowsController/Process/ProcessManager.cs | 3,860 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PenguinKingStats : MonoBehaviour
{
public Camera mcamera;
public GameObject pkdamagetext;
GameObject penguinking;
GameObject pkbody;
public float startingHealth = 100;
public float currentHealth = 100;
public Slider pkhealthSlider;
public Canvas pkHealthCanvas;
public float speed = 4;
public float defense = 1;
public float attack = 5;
public int level = 1;
public int maxlevel = 70;
public int experience = 0;
public int experienceleft = 10;
public bool isDead;
void Awake()
{
penguinking = GameObject.Find("PenguinKing");
pkbody = GameObject.Find("PenguinKingBody");
currentHealth = startingHealth;
pkhealthSlider.value = pkhealthSlider.maxValue;
}
void Update()
{
}
public void Restore(float amount)
{
currentHealth += amount;
pkhealthSlider.value = currentHealth;
if (currentHealth >= startingHealth)
{
currentHealth = startingHealth;
pkhealthSlider.value = currentHealth;
}
}
void InitDamageText(string damagetaken)
{
GameObject temp = Instantiate(pkdamagetext) as GameObject;
RectTransform tempRect = temp.GetComponent<RectTransform>();
temp.transform.SetParent(transform.Find("pmHealthCanvas"));
tempRect.transform.position = pkbody.transform.position + Vector3.up * 15;
tempRect.transform.localScale = pkdamagetext.transform.localScale;
tempRect.transform.rotation = mcamera.transform.rotation;
temp.GetComponent<Text>().text = damagetaken;
temp.SetActive(true);
temp.GetComponent<Animator>().SetTrigger("pkhit");
Destroy(temp.gameObject, 1);
}
float takendamage;
public void TakeDamage(float amount)
{
if (amount - defense >= 0)
{
currentHealth -= amount- defense;
pkhealthSlider.value = currentHealth;
}
if (currentHealth <= 0 && !isDead)
{
isDead = true;
Death();
}
}
public void Death()
{
pkHealthCanvas.enabled = false;
penguinking.SetActive(false);
}
}
| 20.833333 | 82 | 0.621474 | [
"MIT"
] | nitrogendragon/2017-Capstone | Assets/BoardGameScripts/Enemystats/PenguinKingStats.cs | 2,377 | C# |
using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Schema.NET
{
/// <summary>
/// A video file.
/// </summary>
[DataContract]
public partial class VideoObject : MediaObject
{
public interface IMusicBy : IWrapper { }
public interface IMusicBy<T> : IMusicBy { new T Data { get; set; } }
public class MusicByMusicGroup : IMusicBy<MusicGroup>
{
object IWrapper.Data { get { return Data; } set { Data = (MusicGroup) value; } }
public virtual MusicGroup Data { get; set; }
public MusicByMusicGroup () { }
public MusicByMusicGroup (MusicGroup data) { Data = data; }
public static implicit operator MusicByMusicGroup (MusicGroup data) { return new MusicByMusicGroup (data); }
}
public class MusicByPerson : IMusicBy<Person>
{
object IWrapper.Data { get { return Data; } set { Data = (Person) value; } }
public virtual Person Data { get; set; }
public MusicByPerson () { }
public MusicByPerson (Person data) { Data = data; }
public static implicit operator MusicByPerson (Person data) { return new MusicByPerson (data); }
}
/// <summary>
/// Gets the name of the type as specified by schema.org.
/// </summary>
[DataMember(Name = "@type", Order = 1)]
public override string Type => "VideoObject";
/// <summary>
/// An actor, e.g. in tv, radio, movie, video games etc., or in an event. Actors can be associated with individual items or with a series, episode, clip.
/// </summary>
[DataMember(Name = "actor", Order = 306)]
[JsonConverter(typeof(ValuesConverter))]
public Values<Person>? Actor { get; set; }
/// <summary>
/// The caption for this object.
/// </summary>
[DataMember(Name = "caption", Order = 307)]
[JsonConverter(typeof(ValuesConverter))]
public Values<string>? Caption { get; set; }
/// <summary>
/// A director of e.g. tv, radio, movie, video gaming etc. content, or of an event. Directors can be associated with individual items or with a series, episode, clip.
/// </summary>
[DataMember(Name = "director", Order = 308)]
[JsonConverter(typeof(ValuesConverter))]
public Values<Person>? Director { get; set; }
/// <summary>
/// The composer of the soundtrack.
/// </summary>
[DataMember(Name = "musicBy", Order = 309)]
[JsonConverter(typeof(ValuesConverter))]
public Values<IMusicBy>? MusicBy { get; set; } //MusicGroup, Person
/// <summary>
/// Thumbnail image for an image or video.
/// </summary>
[DataMember(Name = "thumbnail", Order = 310)]
[JsonConverter(typeof(ValuesConverter))]
public Values<ImageObject>? Thumbnail { get; set; }
/// <summary>
/// If this MediaObject is an AudioObject or VideoObject, the transcript of that object.
/// </summary>
[DataMember(Name = "transcript", Order = 311)]
[JsonConverter(typeof(ValuesConverter))]
public Values<string>? Transcript { get; set; }
/// <summary>
/// The frame size of the video.
/// </summary>
[DataMember(Name = "videoFrameSize", Order = 312)]
[JsonConverter(typeof(ValuesConverter))]
public Values<string>? VideoFrameSize { get; set; }
/// <summary>
/// The quality of the video.
/// </summary>
[DataMember(Name = "videoQuality", Order = 313)]
[JsonConverter(typeof(ValuesConverter))]
public Values<string>? VideoQuality { get; set; }
}
}
| 39.134021 | 174 | 0.587724 | [
"MIT"
] | AndreSteenbergen/Schema.NET | Source/Schema.NET/core/VideoObject.cs | 3,796 | C# |
// <auto-generated />
namespace CustomMembershipSample.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.0-30225")]
public sealed partial class initial : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(initial));
string IMigrationMetadata.Id
{
get { return "201403242318260_initial"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 27.166667 | 90 | 0.619632 | [
"Apache-2.0"
] | ASCITSOL/asp.net | samples/aspnet/Identity/CustomMembershipSample/CustomMembershipSample/Migrations/201403242318260_initial.Designer.cs | 815 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using NuGet.ProjectModel;
namespace Test.Utility.ProjectManagement
{
public static class DependencyGraphSpecTestUtilities
{
public static DependencyGraphSpec CreateMinimalDependencyGraphSpec(string projectPath, string outputPath)
{
var packageSpec = new PackageSpec();
packageSpec.FilePath = projectPath;
packageSpec.RestoreMetadata = new ProjectRestoreMetadata();
packageSpec.RestoreMetadata.ProjectUniqueName = projectPath;
packageSpec.RestoreMetadata.ProjectStyle = ProjectStyle.PackageReference;
packageSpec.RestoreMetadata.ProjectPath = projectPath;
packageSpec.RestoreMetadata.OutputPath = outputPath;
packageSpec.RestoreMetadata.CacheFilePath = Path.Combine(outputPath, "project.nuget.cache");
var dgSpec = new DependencyGraphSpec();
dgSpec.AddProject(packageSpec);
return dgSpec;
}
}
}
| 39.655172 | 113 | 0.708696 | [
"Apache-2.0"
] | AntonC9018/NuGet.Client | test/TestUtilities/Test.Utility/ProjectManagement/DependencyGraphSpecTestUtilities.cs | 1,150 | 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
#region Usings
using System.Collections;
using System.Web.Caching;
using DotNetNuke.Services.Cache;
#endregion
namespace DotNetNuke.Common.Utilities
{
/// -----------------------------------------------------------------------------
/// Project: DotNetNuke
/// Namespace: DotNetNuke.Common.Utilities
/// Class: CacheItemArgs
/// -----------------------------------------------------------------------------
/// <summary>
/// The CacheItemArgs class provides an EventArgs implementation for the
/// CacheItemExpiredCallback delegate
/// </summary>
/// -----------------------------------------------------------------------------
public class CacheItemArgs
{
private ArrayList _paramList;
///-----------------------------------------------------------------------------
/// <summary>
/// Constructs a new CacheItemArgs Object
/// </summary>
/// <param name="key"></param>
///-----------------------------------------------------------------------------
public CacheItemArgs(string key)
: this(key, 20, CacheItemPriority.Default, null)
{
}
///-----------------------------------------------------------------------------
/// <summary>
/// Constructs a new CacheItemArgs Object
/// </summary>
/// <param name="key"></param>
/// <param name="timeout"></param>
///-----------------------------------------------------------------------------
public CacheItemArgs(string key, int timeout)
: this(key, timeout, CacheItemPriority.Default, null)
{
}
///-----------------------------------------------------------------------------
/// <summary>
/// Constructs a new CacheItemArgs Object
/// </summary>
/// <param name="key"></param>
/// <param name="priority"></param>
///-----------------------------------------------------------------------------
public CacheItemArgs(string key, CacheItemPriority priority)
: this(key, 20, priority, null)
{
}
///-----------------------------------------------------------------------------
/// <summary>
/// Constructs a new CacheItemArgs Object
/// </summary>
/// <param name="key"></param>
/// <param name="timeout"></param>
/// <param name="priority"></param>
///-----------------------------------------------------------------------------
public CacheItemArgs(string key, int timeout, CacheItemPriority priority)
: this(key, timeout, priority, null)
{
}
///-----------------------------------------------------------------------------
/// <summary>
/// Constructs a new CacheItemArgs Object
/// </summary>
/// <param name="key"></param>
/// <param name="timeout"></param>
/// <param name="priority"></param>
/// <param name="parameters"></param>
///-----------------------------------------------------------------------------
public CacheItemArgs(string key, int timeout, CacheItemPriority priority, params object[] parameters)
{
CacheKey = key;
CacheTimeOut = timeout;
CachePriority = priority;
Params = parameters;
}
///-----------------------------------------------------------------------------
/// <summary>
/// Gets and sets the Cache Item's CacheItemRemovedCallback delegate
/// </summary>
///-----------------------------------------------------------------------------
public CacheItemRemovedCallback CacheCallback { get; set; }
///-----------------------------------------------------------------------------
/// <summary>
/// Gets and sets the Cache Item's CacheDependency
/// </summary>
///-----------------------------------------------------------------------------
public DNNCacheDependency CacheDependency { get; set; }
///-----------------------------------------------------------------------------
/// <summary>
/// Gets the Cache Item's Key
/// </summary>
///-----------------------------------------------------------------------------
public string CacheKey { get; set; }
///-----------------------------------------------------------------------------
/// <summary>
/// Gets the Cache Item's priority (defaults to Default)
/// </summary>
/// <remarks>Note: DotNetNuke currently doesn't support the ASP.NET Cache's
/// ItemPriority, but this is included for possible future use. </remarks>
///-----------------------------------------------------------------------------
public CacheItemPriority CachePriority { get; set; }
///-----------------------------------------------------------------------------
/// <summary>
/// Gets the Cache Item's Timeout
/// </summary>
///-----------------------------------------------------------------------------
public int CacheTimeOut { get; set; }
///-----------------------------------------------------------------------------
/// <summary>
/// Gets the Cache Item's Parameter List
/// </summary>
///-----------------------------------------------------------------------------
public ArrayList ParamList
{
get
{
if (_paramList == null)
{
_paramList = new ArrayList();
//add additional params to this list if its not null
if (Params != null)
{
foreach (object param in Params)
{
_paramList.Add(param);
}
}
}
return _paramList;
}
}
///-----------------------------------------------------------------------------
/// <summary>
/// Gets the Cache Item's Parameter Array
/// </summary>
///-----------------------------------------------------------------------------
public object[] Params { get; private set; }
public string ProcedureName { get; set; }
}
}
| 39.297619 | 109 | 0.351863 | [
"MIT"
] | Tychodewaard/Dnn.Platform | DNN Platform/Library/Common/Utilities/CacheItemArgs.cs | 6,604 | C# |
using System;
using NBitcoin;
using Stratis.Bitcoin.Features.Wallet.Helpers;
using Xunit;
namespace Stratis.Bitcoin.Features.Wallet.Tests
{
public class WalletHelpersTest
{
[Fact]
public void GetMainNetworkRetuirnsNetworkMain()
{
Network network = WalletHelpers.GetNetwork("main");
Assert.Equal(Network.Main, network);
}
[Fact]
public void GetMainNetNetworkRetuirnsNetworkMain()
{
Network network = WalletHelpers.GetNetwork("mainnet");
Assert.Equal(Network.Main, network);
}
[Fact]
public void GetTestNetworkRetuirnsNetworkTest()
{
Network network = WalletHelpers.GetNetwork("test");
Assert.Equal(Network.TestNet, network);
}
[Fact]
public void GetTestNetNetworkRetuirnsNetworkTest()
{
Network network = WalletHelpers.GetNetwork("testnet");
Assert.Equal(Network.TestNet, network);
}
[Fact]
public void GetNetworkIsCaseInsensitive()
{
Network testNetwork = WalletHelpers.GetNetwork("Test");
Assert.Equal(Network.TestNet, testNetwork);
Network mainNetwork = WalletHelpers.GetNetwork("MainNet");
Assert.Equal(Network.Main, mainNetwork);
}
[Fact]
public void WrongNetworkThrowsArgumentException()
{
var exception = Record.Exception(() => WalletHelpers.GetNetwork("myNetwork"));
Assert.NotNull(exception);
Assert.IsType<ArgumentException>(exception);
}
}
}
| 29.052632 | 90 | 0.604469 | [
"MIT"
] | obsidianplatform/ObsidianStratisNode | src/Stratis.Bitcoin.Features.Wallet.Tests/WalletHelpersTest.cs | 1,658 | C# |
using System;
namespace RandomNumbersAngular.Authentication.External
{
public class ExternalLoginProviderInfo
{
public string Name { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public Type ProviderApiType { get; set; }
public ExternalLoginProviderInfo(string name, string clientId, string clientSecret, Type providerApiType)
{
Name = name;
ClientId = clientId;
ClientSecret = clientSecret;
ProviderApiType = providerApiType;
}
}
}
| 24.958333 | 113 | 0.629382 | [
"MIT"
] | nesumtoj/RandomNumbersJS | aspnet-core/src/RandomNumbersAngular.Web.Core/Authentication/External/ExternalLoginProviderInfo.cs | 601 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.ServiceBus.Models;
namespace Azure.ResourceManager.ServiceBus
{
/// <summary> A class representing collection of ServiceBusSubscription and their operations over its parent. </summary>
public partial class ServiceBusSubscriptionCollection : ArmCollection, IEnumerable<ServiceBusSubscription>, IAsyncEnumerable<ServiceBusSubscription>
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly SubscriptionsRestOperations _subscriptionsRestClient;
/// <summary> Initializes a new instance of the <see cref="ServiceBusSubscriptionCollection"/> class for mocking. </summary>
protected ServiceBusSubscriptionCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="ServiceBusSubscriptionCollection"/> class. </summary>
/// <param name="parent"> The resource representing the parent resource. </param>
internal ServiceBusSubscriptionCollection(ArmResource parent) : base(parent)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
ClientOptions.TryGetApiVersion(ServiceBusSubscription.ResourceType, out string apiVersion);
_subscriptionsRestClient = new SubscriptionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri, apiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ServiceBusTopic.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ServiceBusTopic.ResourceType), nameof(id));
}
// Collection level operations.
/// <summary> Creates a topic subscription. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="subscriptionName"> The subscription name. </param>
/// <param name="parameters"> Parameters supplied to create a subscription resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="subscriptionName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionName"/> or <paramref name="parameters"/> is null. </exception>
public virtual ServiceBusSubscriptionCreateOrUpdateOperation CreateOrUpdate(bool waitForCompletion, string subscriptionName, ServiceBusSubscriptionData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionName, nameof(subscriptionName));
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _subscriptionsRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, subscriptionName, parameters, cancellationToken);
var operation = new ServiceBusSubscriptionCreateOrUpdateOperation(this, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates a topic subscription. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="subscriptionName"> The subscription name. </param>
/// <param name="parameters"> Parameters supplied to create a subscription resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="subscriptionName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionName"/> or <paramref name="parameters"/> is null. </exception>
public async virtual Task<ServiceBusSubscriptionCreateOrUpdateOperation> CreateOrUpdateAsync(bool waitForCompletion, string subscriptionName, ServiceBusSubscriptionData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionName, nameof(subscriptionName));
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _subscriptionsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, subscriptionName, parameters, cancellationToken).ConfigureAwait(false);
var operation = new ServiceBusSubscriptionCreateOrUpdateOperation(this, response);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Returns a subscription description for the specified topic. </summary>
/// <param name="subscriptionName"> The subscription name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="subscriptionName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionName"/> is null. </exception>
public virtual Response<ServiceBusSubscription> Get(string subscriptionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionName, nameof(subscriptionName));
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.Get");
scope.Start();
try
{
var response = _subscriptionsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, subscriptionName, cancellationToken);
if (response.Value == null)
throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new ServiceBusSubscription(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Returns a subscription description for the specified topic. </summary>
/// <param name="subscriptionName"> The subscription name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="subscriptionName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionName"/> is null. </exception>
public async virtual Task<Response<ServiceBusSubscription>> GetAsync(string subscriptionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionName, nameof(subscriptionName));
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.Get");
scope.Start();
try
{
var response = await _subscriptionsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, subscriptionName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new ServiceBusSubscription(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="subscriptionName"> The subscription name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="subscriptionName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionName"/> is null. </exception>
public virtual Response<ServiceBusSubscription> GetIfExists(string subscriptionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionName, nameof(subscriptionName));
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.GetIfExists");
scope.Start();
try
{
var response = _subscriptionsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, subscriptionName, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<ServiceBusSubscription>(null, response.GetRawResponse());
return Response.FromValue(new ServiceBusSubscription(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="subscriptionName"> The subscription name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="subscriptionName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionName"/> is null. </exception>
public async virtual Task<Response<ServiceBusSubscription>> GetIfExistsAsync(string subscriptionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionName, nameof(subscriptionName));
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.GetIfExists");
scope.Start();
try
{
var response = await _subscriptionsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, subscriptionName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<ServiceBusSubscription>(null, response.GetRawResponse());
return Response.FromValue(new ServiceBusSubscription(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="subscriptionName"> The subscription name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="subscriptionName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionName"/> is null. </exception>
public virtual Response<bool> Exists(string subscriptionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionName, nameof(subscriptionName));
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(subscriptionName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="subscriptionName"> The subscription name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="subscriptionName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionName"/> is null. </exception>
public async virtual Task<Response<bool>> ExistsAsync(string subscriptionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionName, nameof(subscriptionName));
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(subscriptionName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> List all the subscriptions under a specified topic. </summary>
/// <param name="skip"> Skip is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skip parameter that specifies a starting point to use for subsequent calls. </param>
/// <param name="top"> May be used to limit the number of results to the most recent N usageDetails. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="ServiceBusSubscription" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<ServiceBusSubscription> GetAll(int? skip = null, int? top = null, CancellationToken cancellationToken = default)
{
Page<ServiceBusSubscription> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.GetAll");
scope.Start();
try
{
var response = _subscriptionsRestClient.ListByTopic(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, skip, top, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new ServiceBusSubscription(this, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<ServiceBusSubscription> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.GetAll");
scope.Start();
try
{
var response = _subscriptionsRestClient.ListByTopicNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, skip, top, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new ServiceBusSubscription(this, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> List all the subscriptions under a specified topic. </summary>
/// <param name="skip"> Skip is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skip parameter that specifies a starting point to use for subsequent calls. </param>
/// <param name="top"> May be used to limit the number of results to the most recent N usageDetails. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="ServiceBusSubscription" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<ServiceBusSubscription> GetAllAsync(int? skip = null, int? top = null, CancellationToken cancellationToken = default)
{
async Task<Page<ServiceBusSubscription>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.GetAll");
scope.Start();
try
{
var response = await _subscriptionsRestClient.ListByTopicAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, skip, top, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new ServiceBusSubscription(this, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<ServiceBusSubscription>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ServiceBusSubscriptionCollection.GetAll");
scope.Start();
try
{
var response = await _subscriptionsRestClient.ListByTopicNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, skip, top, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new ServiceBusSubscription(this, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
IEnumerator<ServiceBusSubscription> IEnumerable<ServiceBusSubscription>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<ServiceBusSubscription> IAsyncEnumerable<ServiceBusSubscription>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
// Builders.
// public ArmBuilder<Azure.Core.ResourceIdentifier, ServiceBusSubscription, ServiceBusSubscriptionData> Construct() { }
}
}
| 56.162534 | 286 | 0.652327 | [
"MIT"
] | ElleTojaroon/azure-sdk-for-net | sdk/servicebus/Azure.ResourceManager.ServiceBus/src/Generated/ServiceBusSubscriptionCollection.cs | 20,387 | C# |
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Legion.Core.Messages.InMemory;
using Xunit;
namespace Legion.Core.Test.Messages.InMemory
{
public class InMemoryMessageStoreTest
{
[Fact]
public void StoredMessagesCanBeRetrieved()
{
var topic = "askldjfdg";
var topic2 = "askldjfasdasdg";
var message1 = new object();
var message2 = new object();
var message3 = new object();
var header1 = new Dictionary<string, byte[]>();
var header2 = new Dictionary<string, byte[]>();
var header3 = new Dictionary<string, byte[]>();
var messageStore = new InMemoryMessageStore();
var index1 = messageStore.AddMessage(topic, null, header1, message1);
var index2 = messageStore.AddMessage(topic2, null, header2, message2);
var index3 = messageStore.AddMessage(topic, null, header3, message3);
index1.Should().Be(0);
index2.Should().Be(0);
index3.Should().Be(1);
messageStore.GetMessage(topic, 0).Should().Be(message1);
messageStore.GetMessage(topic2, 0).Should().Be(message2);
messageStore.GetMessage(topic, 1).Should().Be(message3);
messageStore.GetMessageHeader(topic, 0).Should().BeSameAs(header1);
messageStore.GetMessageHeader(topic2, 0).Should().BeSameAs(header2);
messageStore.GetMessageHeader(topic, 1).Should().BeSameAs(header3);
messageStore.GetMessageKey(topic, 0).Should().BeNull();
messageStore.GetMessageKey(topic2, 0).Should().BeNull();
messageStore.GetMessageKey(topic, 1).Should().BeNull();
}
}
}
| 36.204082 | 82 | 0.619504 | [
"MIT"
] | Useurmind/Legion | Legion.Core.Test/Messages/InMemory/InMemoryMessageStoreTest.cs | 1,776 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MovieDeckApi.Data;
namespace MovieDeckApi.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20220611162144_InitialCreate")]
partial class InitialCreate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.14")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ProviderKey")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("MovieDeckApi.Models.Movie", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Plot")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("ReleaseDate")
.HasColumnType("datetime2");
b.Property<TimeSpan>("Runtime")
.HasColumnType("time");
b.Property<string>("Title")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Movies");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.599338 | 125 | 0.469397 | [
"MIT"
] | Iceto04/SoftUni | ASP.NET Core/05. Web API/MovieDeckApi/MovieDeckApi/Data/Migrations/20220611162144_InitialCreate.Designer.cs | 11,357 | C# |
using StreamlineMVVM;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace CatPersonSearcher
{
public class CatModel : ViewModelBase
{
// -----------------------------------------------------
private BitmapImage _Portrait = null;
public BitmapImage Portrait
{
get { return _Portrait; }
set
{
_Portrait = value;
OnPropertyChanged(new PropertyChangedEventArgs("Portrait"));
}
}
// -----------------------------------------------------
private string _Filename = null;
public string Filename
{
get { return _Filename; }
set
{
_Filename = value;
OnPropertyChanged(new PropertyChangedEventArgs("Filename"));
}
}
}
}
| 25.74359 | 76 | 0.500996 | [
"MIT"
] | pvpxan/CatPersonSearcher | CatPersonSearcher/Models/CatModel.cs | 1,006 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace UiPath.Web.Client20184.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class ODataQueryOptionsJobDto
{
/// <summary>
/// Initializes a new instance of the ODataQueryOptionsJobDto class.
/// </summary>
public ODataQueryOptionsJobDto()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ODataQueryOptionsJobDto class.
/// </summary>
public ODataQueryOptionsJobDto(object ifMatch = default(object), object ifNoneMatch = default(object), ODataQueryContext context = default(ODataQueryContext), object request = default(object), ODataRawQueryOptions rawValues = default(ODataRawQueryOptions), SelectExpandQueryOption selectExpand = default(SelectExpandQueryOption), ApplyQueryOption apply = default(ApplyQueryOption), FilterQueryOption filter = default(FilterQueryOption), OrderByQueryOption orderBy = default(OrderByQueryOption), SkipQueryOption skip = default(SkipQueryOption), TopQueryOption top = default(TopQueryOption), CountQueryOption count = default(CountQueryOption), object validator = default(object))
{
IfMatch = ifMatch;
IfNoneMatch = ifNoneMatch;
Context = context;
Request = request;
RawValues = rawValues;
SelectExpand = selectExpand;
Apply = apply;
Filter = filter;
OrderBy = orderBy;
Skip = skip;
Top = top;
Count = count;
Validator = validator;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "IfMatch")]
public object IfMatch { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "IfNoneMatch")]
public object IfNoneMatch { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Context")]
public ODataQueryContext Context { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Request")]
public object Request { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "RawValues")]
public ODataRawQueryOptions RawValues { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "SelectExpand")]
public SelectExpandQueryOption SelectExpand { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Apply")]
public ApplyQueryOption Apply { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Filter")]
public FilterQueryOption Filter { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "OrderBy")]
public OrderByQueryOption OrderBy { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Skip")]
public SkipQueryOption Skip { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Top")]
public TopQueryOption Top { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Count")]
public CountQueryOption Count { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Validator")]
public object Validator { get; set; }
}
}
| 34.73913 | 685 | 0.59975 | [
"MIT"
] | AFWberlin/orchestrator-powershell | UiPath.Web.Client/generated20184/Models/ODataQueryOptionsJobDto.cs | 3,995 | C# |
using OpenQA.Selenium;
using SeleniumWebdriver.ComponentHelper;
using SeleniumWebdriver.CustomException;
using SeleniumWebdriver.ExcelReader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SeleniumWebdriver.Keyword
{
public class DataEngine
{
private readonly int _keywordCol;
private readonly int _locatorTypeCol;
private readonly int _locatorValueCol;
private readonly int _parameterCol;
public DataEngine(int keywordCol = 2, int locatorTypeCol = 3, int locatorValueCol = 4, int parameterCol = 5)
{
this._keywordCol = keywordCol;
this._locatorTypeCol = locatorTypeCol;
this._locatorValueCol = locatorValueCol;
this._parameterCol = parameterCol;
}
private By GetElementLocator(string locatorType, string locatorValue)
{
switch (locatorType)
{
case "Id":
return By.Id(locatorValue);
case "XPath":
return By.XPath(locatorValue);
case "LinkText":
return By.LinkText(locatorValue);
case "ClassName":
return By.ClassName(locatorValue);
case "CssSelector":
return By.CssSelector(locatorValue);
case "Name":
return By.Name(locatorValue);
case "PartialLinkText":
return By.PartialLinkText(locatorValue);
default:
return By.Id(locatorValue);
}
}
public void PerformActions(string keyword, string locatorType, string locatorValue, params string[] parameters)
{
switch (keyword)
{
case "Click":
ButtonHelper.ClickOnButton(GetElementLocator(locatorType, locatorValue));
break;
case "SendKeys":
{
TextBoxHelper.ClearTextbox(GetElementLocator(locatorType, locatorValue));
TextBoxHelper.TypeInTextbox(GetElementLocator(locatorType, locatorValue), parameters[0]);
}
break;
case "Navigate":
NavigationHelper.NavigationToURL(parameters[0]);
break;
case "Select":
DropdownListHelper.SelectElement(GetElementLocator(locatorType, locatorValue), parameters[0]);
break;
case "WaitForEle":
GenericHelpers.WaitForElementInPage(GetElementLocator(locatorType, locatorValue),
TimeSpan.FromSeconds(60));
break;
default:
throw new NoSuchKeywordException("No such keyword found" + keyword);
}
}
public void ExecuteScripts(string xlPath, string sheetName)
{
int totalRows = ExcelReaderHelper.GetTotalExcelColumns(xlPath, sheetName);
for (int i = 1; i < totalRows; i++)
{
var keyword = ExcelReaderHelper.GetCellData(xlPath, sheetName, i, _keywordCol).ToString();
var locatorType = ExcelReaderHelper.GetCellData(xlPath, sheetName, i, _locatorTypeCol).ToString();
var locatorVal = ExcelReaderHelper.GetCellData(xlPath, sheetName, i, _locatorValueCol).ToString();
var para = ExcelReaderHelper.GetCellData(xlPath, sheetName, i, _parameterCol).ToString();
PerformActions(keyword, locatorType, locatorVal, para);
}
}
}
}
| 42.388889 | 119 | 0.564613 | [
"BSD-3-Clause"
] | thaotrant/SeleniumWebdriver | Keyword/DataEngine.cs | 3,817 | C# |
using FlatRedBall.Glue.CodeGeneration;
using FlatRedBall.Glue.CodeGeneration.CodeBuilder;
using FlatRedBall.Glue.Plugins.ExportedImplementations;
using FlatRedBall.Glue.SaveClasses;
using FlatRedBall.IO;
using Gum.DataTypes;
using GumPluginCore.CodeGeneration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GumPlugin.CodeGeneration
{
class GumPluginCodeGenerator : ElementComponentCodeGenerator
{
public override FlatRedBall.Glue.Plugins.Interfaces.CodeLocation CodeLocation
{
get
{
return FlatRedBall.Glue.Plugins.Interfaces.CodeLocation.BeforeStandardGenerated;
}
}
public override ICodeBlock GenerateFields(ICodeBlock codeBlock, IElement element)
{
bool isGlueScreen, hasGumScreen, hasForms;
bool needsGumIdb = NeedsGumIdb(element, out isGlueScreen, out hasGumScreen, out hasForms);
if (needsGumIdb)
{
// Create a generic Gum IDB to support in-code creation of Gum objects:
codeBlock.Line("FlatRedBall.Gum.GumIdb gumIdb;");
}
if (isGlueScreen && hasGumScreen && hasForms)
{
var rfs = GetGumScreenRfs(element);
var elementName = element.GetStrippedName();
var formsObjectType = FormsClassCodeGenerator.Self.GetFullRuntimeNamespaceFor(elementName, "Screens") +
"." + rfs.GetInstanceName() + "Forms";
codeBlock.Line($"{formsObjectType} Forms;");
}
return codeBlock;
}
private bool NeedsGumIdb(IElement element, out bool isGlueScreen, out bool hasGumScreen, out bool hasForms)
{
isGlueScreen = element is FlatRedBall.Glue.SaveClasses.ScreenSave;
hasGumScreen = GetIfContainsAnyGumScreenFiles(element);
// technically all FRB projects now have forms, so let's just default that to true
hasForms = true;
// if it's derived, then the base will take care of it.
var isDerivedScreen = !string.IsNullOrEmpty(element.BaseElement);
return isGlueScreen && !hasGumScreen && !isDerivedScreen && GetIfHasGumProject();
}
public override ICodeBlock GenerateInitialize(ICodeBlock codeBlock, IElement element)
{
var gumScreenRfs =
element.ReferencedFiles.FirstOrDefault(item => item.Name.EndsWith(".gusx"));
bool needsGumIdb = NeedsGumIdb(element, out bool isGlueScreen, out bool hasGumScreen, out bool hasForms);
if (needsGumIdb)
{
// Create a generic Gum IDB to support in-code creation of Gum objects:
codeBlock.Line("gumIdb = new FlatRedBall.Gum.GumIdb();");
}
if (isGlueScreen && hasGumScreen && hasForms)
{
var elementName = element.GetStrippedName();
//var screensOrComponents = element.Name.ToLowerInvariant().EndsWith(".gusx") ? "Screens" : "Components";
var rfs = GetGumScreenRfs(element);
var formsObjectType = FormsClassCodeGenerator.Self.GetFullRuntimeNamespaceFor(elementName, "Screens") +
"." + rfs.GetInstanceName() + "Forms";
var formsInstantiationLine =
$"Forms = new {formsObjectType}({rfs.GetInstanceName()});";
codeBlock.Line(formsInstantiationLine);
}
return codeBlock;
}
public override ICodeBlock GenerateAddToManagers(ICodeBlock codeBlock, IElement element)
{
var needsGumIdb = NeedsGumIdb(element, out bool _, out bool _, out bool _);
if (needsGumIdb)
{
// Create a generic Gum IDB to support in-code creation of Gum objects:
codeBlock.Line("FlatRedBall.SpriteManager.AddDrawableBatch(gumIdb);");
}
return codeBlock;
}
public override ICodeBlock GenerateDestroy(ICodeBlock codeBlock, IElement element)
{
var needsGumIdb = NeedsGumIdb(element, out bool _, out bool _, out bool _);
if (needsGumIdb)
{
codeBlock.Line("FlatRedBall.SpriteManager.RemoveDrawableBatch(gumIdb);");
}
return codeBlock;
}
public override ICodeBlock GenerateLoadStaticContent(ICodeBlock codeBlock, IElement element)
{
bool hasGumProject = GetIfHasGumProject();
// We used to only do this code if the screen had a component, but we will do it if the entire project
// has a gum file so that users don't have to manually do this
if (hasGumProject)
{
var gumProject =
GlueState.Self.CurrentGlueProject.GlobalFiles.FirstOrDefault(item => item.Name.EndsWith(".gumx"));
codeBlock.Line("// Set the content manager for Gum");
codeBlock.Line("var contentManagerWrapper = new FlatRedBall.Gum.ContentManagerWrapper();");
codeBlock.Line("contentManagerWrapper.ContentManagerName = contentManagerName;");
codeBlock.Line("RenderingLibrary.Content.LoaderManager.Self.ContentLoader = contentManagerWrapper;");
codeBlock.Line("// Access the GumProject just in case it's async loaded");
codeBlock.Line($"var throwaway = GlobalContent.{gumProject.GetInstanceName()};");
}
return codeBlock;
}
public override ICodeBlock GenerateAdditionalMethods(ICodeBlock codeBlock, IElement element)
{
bool isGlueScreen = element is FlatRedBall.Glue.SaveClasses.ScreenSave;
var gumScreenRfs = GetGumScreenRfs(element);
if(isGlueScreen && gumScreenRfs != null)
{
var method = codeBlock.Function("private void", "RefreshLayoutInternal", "object sender, EventArgs e");
var ati = gumScreenRfs.GetAssetTypeInfo();
// This could be null if the Gum screen has been deleted from the Gum project.
// dont' throw an exception if so...
//if(ati == null)
//{
// throw new Exception($"Could not find asset type info for {element.Name}");
//}
if(ati?.RuntimeTypeName == "GumIdb")
{
method.Line($"{gumScreenRfs.GetInstanceName()}.Element.UpdateLayout();");
}
else
{
method.Line($"{gumScreenRfs.GetInstanceName()}.UpdateLayout();");
}
}
return codeBlock;
}
private static bool GetIfHasGumProject()
{
return GlueState.Self.CurrentGlueProject.GlobalFiles.FirstOrDefault(item => item.Name.EndsWith(".gumx")) != null;
}
private bool GetIfContainsAnyGumFilesIn(IElement element)
{
foreach (var file in element.ReferencedFiles)
{
string extension = FileManager.GetExtension( file.Name);
if (file.LoadedAtRuntime &&
(extension == GumProjectSave.ComponentExtension ||
extension == GumProjectSave.ScreenExtension ||
extension == GumProjectSave.StandardExtension))
{
return true;
}
}
return false;
}
private ReferencedFileSave GetGumScreenRfs(IElement element)
{
foreach (var file in element.ReferencedFiles)
{
string extension = FileManager.GetExtension(file.Name);
if (file.LoadedAtRuntime && extension == GumProjectSave.ScreenExtension)
{
return file;
}
}
return null;
}
private bool GetIfContainsAnyGumScreenFiles(IElement element)
{
return GetGumScreenRfs(element) != null;
}
public override void GeneratePauseThisScreen(ICodeBlock codeBlock, IElement element)
{
if (element is FlatRedBall.Glue.SaveClasses.ScreenSave)
{
string line = "StateInterpolationPlugin.TweenerManager.Self.Pause();";
if (!codeBlock.HasLine(line))
{
codeBlock.Line(line);
}
}
}
public override void GenerateUnpauseThisScreen(ICodeBlock codeBlock, IElement element)
{
if (element is FlatRedBall.Glue.SaveClasses.ScreenSave)
{
string line = "StateInterpolationPlugin.TweenerManager.Self.Unpause();";
if (!codeBlock.HasLine(line))
{
codeBlock.Line(line);
}
}
}
public static bool IsGue(FlatRedBall.Glue.SaveClasses.NamedObjectSave item)
{
return item.SourceType == FlatRedBall.Glue.SaveClasses.SourceType.File &&
!string.IsNullOrEmpty(item.SourceFile) &&
!string.IsNullOrEmpty(item.SourceName) &&
(FileManager.GetExtension(item.SourceFile) == "gusx" || FileManager.GetExtension(item.SourceFile) == "gucx");
}
}
}
| 37.101167 | 125 | 0.584583 | [
"MIT"
] | coldacid/FlatRedBall | FRBDK/Glue/GumPlugin/GumPlugin/CodeGeneration/GumPluginCodeGenerator.cs | 9,537 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Luizalabs.Challenge.Core
{
public class Product : Entity
{
private IList<Review> _reviews;
public Product() : base()
{
_reviews = new List<Review>();
}
public string Title { get; set; }
public double Price { get; set; }
public string Image { get; set; }
public Brand Brand { get; set; }
public IEnumerable<Review> Reviews => _reviews;
public double ReviewScore { get; protected set; }
public void AddReview(Review review, Customer customer)
{
review.Customer = customer;
_reviews.Add(review);
}
}
}
| 23.677419 | 63 | 0.581744 | [
"Apache-2.0"
] | juloliveira/luizalabs | src/Luizalabs.Challenge/Luizalabs.Challenge.Core/Product.cs | 736 | C# |
#if DEBUG && !PROFILE_SVELTO
#define CHECK_ALL
#endif
using Svelto.DataStructures;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Svelto.ECS {
/// <summary>
/// Note: this check doesn't catch the case when an add and remove is done on the same entity before the nextI am
/// submission. Two operations on the same entity are not allowed between submissions.
/// </summary>
public partial class EnginesRoot
{
[Conditional("CHECK_ALL")]
void CheckRemoveEntityID(EGID egid, Type entityDescriptorType, string caller = "")
{
if (_multipleOperationOnSameEGIDChecker.ContainsKey(egid) == true)
throw new ECSException(
"Executing multiple structural changes in one submission on the same entity is not supported "
.FastConcat(" caller: ", caller, " ").FastConcat(egid.entityID).FastConcat(" groupid: ")
.FastConcat(egid.groupID.ToName()).FastConcat(" type: ")
.FastConcat(entityDescriptorType != null ? entityDescriptorType.Name : "not available")
.FastConcat(" operation was: ")
.FastConcat(_multipleOperationOnSameEGIDChecker[egid] == 1 ? "add" : "remove"));
if (_idChecker.TryGetValue(egid.groupID, out var hash))
if (hash.Contains(egid.entityID) == false)
throw new ECSException("Trying to remove an Entity never submitted in the database "
.FastConcat(" caller: ", caller, " ").FastConcat(egid.entityID)
.FastConcat(" groupid: ").FastConcat(egid.groupID.ToName())
.FastConcat(" type: ")
.FastConcat(entityDescriptorType != null
? entityDescriptorType.Name
: "not available"));
else
hash.Remove(egid.entityID);
_multipleOperationOnSameEGIDChecker.Add(egid, 0);
}
[Conditional("CHECK_ALL")]
void CheckAddEntityID(EGID egid, Type entityDescriptorType, string caller = "")
{
if (_multipleOperationOnSameEGIDChecker.ContainsKey(egid) == true)
throw new ECSException(
"Executing multiple structural changes in one submission on the same entity is not supported "
.FastConcat(" caller: ", caller, " ").FastConcat(egid.entityID).FastConcat(" groupid: ")
.FastConcat(egid.groupID.ToName()).FastConcat(" type: ")
.FastConcat(entityDescriptorType != null ? entityDescriptorType.Name : "not available")
.FastConcat(" operation was: ")
.FastConcat(_multipleOperationOnSameEGIDChecker[egid] == 1 ? "add" : "remove"));
var hash = _idChecker.GetOrCreate(egid.groupID, () => new HashSet<uint>());
if (hash.Contains(egid.entityID) == true)
throw new ECSException("Trying to add an Entity already submitted to the database "
.FastConcat(" caller: ", caller, " ").FastConcat(egid.entityID)
.FastConcat(" groupid: ").FastConcat(egid.groupID.ToName()).FastConcat(" type: ")
.FastConcat(entityDescriptorType != null
? entityDescriptorType.Name
: "not available"));
hash.Add(egid.entityID);
_multipleOperationOnSameEGIDChecker.Add(egid, 1);
}
[Conditional("CHECK_ALL")]
void RemoveGroupID(ExclusiveGroupStruct groupID) { _idChecker.Remove(groupID); }
[Conditional("CHECK_ALL")]
void ClearChecks() { _multipleOperationOnSameEGIDChecker.FastClear(); }
readonly FasterDictionary<EGID, uint> _multipleOperationOnSameEGIDChecker = new FasterDictionary<EGID, uint>();
readonly FasterDictionary<uint, HashSet<uint>> _idChecker = new FasterDictionary<uint, HashSet<uint>>();
}
} | 56.38961 | 121 | 0.562414 | [
"MIT"
] | The-Paladin-Forge-Studio/Svelto-ECS-Filters | Svelto.ECS/Svelto.ECS/CheckEntityUtilities.cs | 4,344 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
namespace _016_Power_Digit_Sum
{
class Program
{
static void Main(string[] args)
{
//2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
//What is the sum of the digits of the number 2^1000?
BigInteger sum = 0;
BigInteger number;
const int exponent = 1000;
number = 2;
for (int i = 1; i < exponent; i++)
{
number = number * 2;
}
BigInteger temp = number;
while (temp > 0)
{
sum += temp % 10;
temp = temp / 10;
}
Console.WriteLine("2^{0} = {1}", exponent, number);
Console.WriteLine("the digits of 2^{0} sum to {1}", exponent, sum);
Console.Read();
}
}
}
| 24.146341 | 79 | 0.486869 | [
"MIT"
] | HunterCarlson/ProjectEuler | Problems/016 Power Digit Sum/Program.cs | 992 | C# |
using System.Collections.Generic;
using System.Drawing;
using System.Net.Http;
using System.Web.Http.Routing;
namespace Kontur.ImageTransformer.Constraints
{
/// <inheritdoc />
/// <summary>
/// Constrains a route parameter to represent only Transform values: rotate-cw, rotate-ccw, flip-v, flip-h
/// </summary>
public class TransformConstraint : IHttpRouteConstraint
{
/// <inheritdoc />
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
if (!values.TryGetValue(parameterName, out var value) || value == null)
{
return false;
}
var stringValue = value as string;
switch (stringValue)
{
case null:
return false;
case "rotate-cw":
values[parameterName] = RotateFlipType.Rotate90FlipNone;
return true;
case "rotate-ccw":
values[parameterName] = RotateFlipType.Rotate270FlipNone;
return true;
case "flip-h":
values[parameterName] = RotateFlipType.RotateNoneFlipX;
return true;
case "flip-v":
values[parameterName] = RotateFlipType.RotateNoneFlipY;
return true;
}
return false;
}
}
} | 34.177778 | 111 | 0.551365 | [
"MIT"
] | alldevic/qwe | Kontur.ImageTransformer/Constraints/TransformConstraint.cs | 1,540 | C# |
/*
* Ory Kratos
*
* Welcome to the ORY Kratos HTTP API documentation!
*
* The version of the OpenAPI document: v0.5.4-alpha.1
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Ory.Kratos.Client.Client.OpenAPIDateConverter;
namespace Ory.Kratos.Client.Model
{
/// <summary>
/// KratosRecoveryFlowMethodConfig
/// </summary>
[DataContract]
public partial class KratosRecoveryFlowMethodConfig : IEquatable<KratosRecoveryFlowMethodConfig>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="KratosRecoveryFlowMethodConfig" /> class.
/// </summary>
[JsonConstructorAttribute]
protected KratosRecoveryFlowMethodConfig() { }
/// <summary>
/// Initializes a new instance of the <see cref="KratosRecoveryFlowMethodConfig" /> class.
/// </summary>
/// <param name="action">Action should be used as the form action URL `<form action=\"{{ .Action }}\" method=\"post\">`. (required).</param>
/// <param name="fields">Fields contains multiple fields (required).</param>
/// <param name="messages">messages.</param>
/// <param name="method">Method is the form method (e.g. POST) (required).</param>
public KratosRecoveryFlowMethodConfig(string action = default(string), List<KratosFormField> fields = default(List<KratosFormField>), List<KratosMessage> messages = default(List<KratosMessage>), string method = default(string))
{
// to ensure "action" is required (not null)
this.Action = action ?? throw new ArgumentNullException("action is a required property for KratosRecoveryFlowMethodConfig and cannot be null");
// to ensure "fields" is required (not null)
this.Fields = fields ?? throw new ArgumentNullException("fields is a required property for KratosRecoveryFlowMethodConfig and cannot be null");
// to ensure "method" is required (not null)
this.Method = method ?? throw new ArgumentNullException("method is a required property for KratosRecoveryFlowMethodConfig and cannot be null");
this.Messages = messages;
}
/// <summary>
/// Action should be used as the form action URL `<form action=\"{{ .Action }}\" method=\"post\">`.
/// </summary>
/// <value>Action should be used as the form action URL `<form action=\"{{ .Action }}\" method=\"post\">`.</value>
[DataMember(Name="action", EmitDefaultValue=false)]
public string Action { get; set; }
/// <summary>
/// Fields contains multiple fields
/// </summary>
/// <value>Fields contains multiple fields</value>
[DataMember(Name="fields", EmitDefaultValue=false)]
public List<KratosFormField> Fields { get; set; }
/// <summary>
/// Gets or Sets Messages
/// </summary>
[DataMember(Name="messages", EmitDefaultValue=false)]
public List<KratosMessage> Messages { get; set; }
/// <summary>
/// Method is the form method (e.g. POST)
/// </summary>
/// <value>Method is the form method (e.g. POST)</value>
[DataMember(Name="method", EmitDefaultValue=false)]
public string Method { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class KratosRecoveryFlowMethodConfig {\n");
sb.Append(" Action: ").Append(Action).Append("\n");
sb.Append(" Fields: ").Append(Fields).Append("\n");
sb.Append(" Messages: ").Append(Messages).Append("\n");
sb.Append(" Method: ").Append(Method).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as KratosRecoveryFlowMethodConfig);
}
/// <summary>
/// Returns true if KratosRecoveryFlowMethodConfig instances are equal
/// </summary>
/// <param name="input">Instance of KratosRecoveryFlowMethodConfig to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(KratosRecoveryFlowMethodConfig input)
{
if (input == null)
return false;
return
(
this.Action == input.Action ||
(this.Action != null &&
this.Action.Equals(input.Action))
) &&
(
this.Fields == input.Fields ||
this.Fields != null &&
input.Fields != null &&
this.Fields.SequenceEqual(input.Fields)
) &&
(
this.Messages == input.Messages ||
this.Messages != null &&
input.Messages != null &&
this.Messages.SequenceEqual(input.Messages)
) &&
(
this.Method == input.Method ||
(this.Method != null &&
this.Method.Equals(input.Method))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Action != null)
hashCode = hashCode * 59 + this.Action.GetHashCode();
if (this.Fields != null)
hashCode = hashCode * 59 + this.Fields.GetHashCode();
if (this.Messages != null)
hashCode = hashCode * 59 + this.Messages.GetHashCode();
if (this.Method != null)
hashCode = hashCode * 59 + this.Method.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 40.951872 | 235 | 0.577305 | [
"Apache-2.0"
] | UkonnRa/sdk | clients/kratos/dotnet/src/Ory.Kratos.Client/Model/KratosRecoveryFlowMethodConfig.cs | 7,658 | C# |
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Antlr.Runtime.Misc;
using Microsoft.Ajax.Utilities;
namespace WS.FrontEnd.WebApi.Infrastucture.Extensions
{
public static class ActionVerbConfigService
{
private static string VerbsDisabledSetting { get; } = "VerbsDisabled";
private static string Message { get; } = "That action is currently disabled";
public static T WrapAction<T>(Func<T> action)
{
if (VerbsDisabled())
{
ThrowDisabledVerb();
}
return action();
}
public static void ThrowDisabledVerb()
{
throw new HttpResponseException(new HttpResponseMessage
{
StatusCode = HttpStatusCode.NotImplemented,
Content = new StringContent(Message)
});
}
public static bool VerbsDisabled()
{
var setting = ConfigurationManager.AppSettings[VerbsDisabledSetting];
if (setting.IsNullOrWhiteSpace())
{
return false;
}
return setting.ToLower() == "true";
}
}
} | 26.434783 | 85 | 0.580592 | [
"MIT"
] | emir01/Web-Shop | Source/Solution/WS/FrontEnd/WS.FrontEnd.WebApi/Infrastucture/Extensions/ActionVerbConfigService.cs | 1,218 | C# |
using System.IO;
using Xunit;
namespace SkiaSharp.Extended.Tests
{
public class SKBlurHashTest
{
public const string Image1 = "LLHV6nae2ek8lAo0aeR*%fkCMxn%";
public const string Image1_8x6 = "qLHV6nae2ek8w^xbjYR*lAo0aeR*-6s:NeWB%fkCMxn%xuS2NHs.ShRj$%xaI;R%n$a$W?oeoJR+W:aes:xaofaxj[bHoLo0R*WW";
public const string Image2 = "LGFFaXYk^6#M@-5c,1Ex@@or[j6o";
public const string Image2_8x6 = "qHFFaXYk^6#M9vF~W@j=@-5b,1J5PBV=R:s;@[or[k6oO[TLtJrq};Fxi^OZE3NgM}spjMFxS#OtcXnzRjxZj]OYNeWGJCs9xunh";
public const string Image3 = "L6Pj0^nh.AyE?vt7t7R**0o#DgR4";
public const string Image4 = "LKO2?V%2Tw=^]~RBVZRi};RPxuwH";
public const string Image6 = "LlM~Oi00%#MwS|WDWEIoR*X8R*bH";
public const string Image6_cs = "LlMF%n00%#MwS|WCWEM{R*bbWBbH";
public const string Image7 = "LjIY5?00?bIUofWBWBM{WBofWBj[";
[Fact]
public void CanEncodeAndDecode()
{
using var img = SKBitmap.Decode(Path.Combine("images", "img1.jpg"));
var encoded = SKBlurHash.Serialize(img, 4, 3);
Assert.NotNull(encoded);
Assert.True(encoded.Length > 6);
var decoded = SKBlurHash.DeserializeBitmap(encoded, 12, 10);
Assert.NotNull(decoded);
}
}
}
| 34.205882 | 138 | 0.72055 | [
"MIT"
] | 8529447889/SkiaSharp.Extended | tests/SkiaSharp.Extended.Tests/BlurHash/SKBlurHashTest.cs | 1,165 | 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 workspaces-2015-04-08.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.WorkSpaces.Model
{
/// <summary>
/// Container for the parameters to the DeleteIpGroup operation.
/// Deletes the specified IP access control group.
///
///
/// <para>
/// You cannot delete an IP access control group that is associated with a directory.
/// </para>
/// </summary>
public partial class DeleteIpGroupRequest : AmazonWorkSpacesRequest
{
private string _groupId;
/// <summary>
/// Gets and sets the property GroupId.
/// <para>
/// The ID of the IP access control group.
/// </para>
/// </summary>
public string GroupId
{
get { return this._groupId; }
set { this._groupId = value; }
}
// Check to see if GroupId property is set
internal bool IsSetGroupId()
{
return this._groupId != null;
}
}
} | 29.080645 | 108 | 0.645591 | [
"Apache-2.0"
] | GitGaby/aws-sdk-net | sdk/src/Services/WorkSpaces/Generated/Model/DeleteIpGroupRequest.cs | 1,803 | C# |
// <copyright file="HistoryNotificationsController.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// </copyright>
namespace Microsoft.Teams.Apps.CompanyCommunicator.Controllers
{
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web;
using Microsoft.Teams.Apps.CompanyCommunicator.Authentication;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Repositories.NotificationData;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Services.MicrosoftGraph;
using Microsoft.Teams.Apps.CompanyCommunicator.Models;
/// <summary>
/// Controller for the notifications history data.
/// </summary>
[Route("api/history")]
[Authorize(PolicyNames.MustBeValidUpnPolicy)]
public class HistoryNotificationsController : ControllerBase
{
private readonly INotificationDataRepository notificationDataRepository;
private readonly IGroupsService groupsService;
/// <summary>
/// Initializes a new instance of the <see cref="HistoryNotificationsController"/> class.
/// </summary>
/// <param name="notificationDataRepository">Notification data repository instance.</param>
/// <param name="groupsService">group service.</param>
public HistoryNotificationsController(
INotificationDataRepository notificationDataRepository,
IGroupsService groupsService)
{
this.notificationDataRepository = notificationDataRepository ?? throw new ArgumentNullException(nameof(notificationDataRepository));
this.groupsService = groupsService ?? throw new ArgumentNullException(nameof(groupsService));
}
/// <summary>
/// Get user notifications history by user Id.
/// </summary>
/// <returns>It returns the notification history for specified user.</returns>
[HttpGet]
public async Task<ActionResult<DraftNotification>> GetUserNotificationsHistoryByIdAsync()
{
var claim = this.User?.Claims?.FirstOrDefault(p => p.Type == ClaimConstants.ObjectId);
var userAadId = claim?.Value;
var userGroupsRes = await this.groupsService.GetUserGroups(userAadId);
var groupIds = userGroupsRes.ToList().Select(x => x.Id);
var result = await this.notificationDataRepository.GetSentNotificationsToUser(groupIds);
return this.Ok(result);
}
}
}
| 44.033898 | 144 | 0.705928 | [
"MIT"
] | engagesquared/microsoft-teams-apps-company-communicator | Source/CompanyCommunicator/Controllers/HistoryNotificationsController.cs | 2,600 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V6.Enums;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V6.Services
{
/// <summary>Settings for <see cref="InvoiceServiceClient"/> instances.</summary>
public sealed partial class InvoiceServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="InvoiceServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="InvoiceServiceSettings"/>.</returns>
public static InvoiceServiceSettings GetDefault() => new InvoiceServiceSettings();
/// <summary>Constructs a new <see cref="InvoiceServiceSettings"/> object with default settings.</summary>
public InvoiceServiceSettings()
{
}
private InvoiceServiceSettings(InvoiceServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListInvoicesSettings = existing.ListInvoicesSettings;
OnCopy(existing);
}
partial void OnCopy(InvoiceServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>InvoiceServiceClient.ListInvoices</c> and <c>InvoiceServiceClient.ListInvoicesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListInvoicesSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="InvoiceServiceSettings"/> object.</returns>
public InvoiceServiceSettings Clone() => new InvoiceServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="InvoiceServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
internal sealed partial class InvoiceServiceClientBuilder : gaxgrpc::ClientBuilderBase<InvoiceServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public InvoiceServiceSettings Settings { get; set; }
partial void InterceptBuild(ref InvoiceServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<InvoiceServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override InvoiceServiceClient Build()
{
InvoiceServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<InvoiceServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<InvoiceServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private InvoiceServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return InvoiceServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<InvoiceServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return InvoiceServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => InvoiceServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => InvoiceServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => InvoiceServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>InvoiceService client wrapper, for convenient use.</summary>
/// <remarks>
/// A service to fetch invoices issued for a billing setup during a given month.
/// </remarks>
public abstract partial class InvoiceServiceClient
{
/// <summary>
/// The default endpoint for the InvoiceService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default InvoiceService scopes.</summary>
/// <remarks>
/// The default InvoiceService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes);
/// <summary>
/// Asynchronously creates a <see cref="InvoiceServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="InvoiceServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="InvoiceServiceClient"/>.</returns>
public static stt::Task<InvoiceServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new InvoiceServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="InvoiceServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="InvoiceServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="InvoiceServiceClient"/>.</returns>
public static InvoiceServiceClient Create() => new InvoiceServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="InvoiceServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="InvoiceServiceSettings"/>.</param>
/// <returns>The created <see cref="InvoiceServiceClient"/>.</returns>
internal static InvoiceServiceClient Create(grpccore::CallInvoker callInvoker, InvoiceServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
InvoiceService.InvoiceServiceClient grpcClient = new InvoiceService.InvoiceServiceClient(callInvoker);
return new InvoiceServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC InvoiceService client</summary>
public virtual InvoiceService.InvoiceServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns all invoices associated with a billing setup, for a given month.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ListInvoicesResponse ListInvoices(ListInvoicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns all invoices associated with a billing setup, for a given month.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListInvoicesResponse> ListInvoicesAsync(ListInvoicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns all invoices associated with a billing setup, for a given month.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListInvoicesResponse> ListInvoicesAsync(ListInvoicesRequest request, st::CancellationToken cancellationToken) =>
ListInvoicesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns all invoices associated with a billing setup, for a given month.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer to fetch invoices for.
/// </param>
/// <param name="billingSetup">
/// Required. The billing setup resource name of the requested invoices.
///
/// `customers/{customer_id}/billingSetups/{billing_setup_id}`
/// </param>
/// <param name="issueYear">
/// Required. The issue year to retrieve invoices, in yyyy format. Only
/// invoices issued in 2019 or later can be retrieved.
/// </param>
/// <param name="issueMonth">
/// Required. The issue month to retrieve invoices.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ListInvoicesResponse ListInvoices(string customerId, string billingSetup, string issueYear, gagve::MonthOfYearEnum.Types.MonthOfYear issueMonth, gaxgrpc::CallSettings callSettings = null) =>
ListInvoices(new ListInvoicesRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
BillingSetup = gax::GaxPreconditions.CheckNotNullOrEmpty(billingSetup, nameof(billingSetup)),
IssueYear = gax::GaxPreconditions.CheckNotNullOrEmpty(issueYear, nameof(issueYear)),
IssueMonth = issueMonth,
}, callSettings);
/// <summary>
/// Returns all invoices associated with a billing setup, for a given month.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer to fetch invoices for.
/// </param>
/// <param name="billingSetup">
/// Required. The billing setup resource name of the requested invoices.
///
/// `customers/{customer_id}/billingSetups/{billing_setup_id}`
/// </param>
/// <param name="issueYear">
/// Required. The issue year to retrieve invoices, in yyyy format. Only
/// invoices issued in 2019 or later can be retrieved.
/// </param>
/// <param name="issueMonth">
/// Required. The issue month to retrieve invoices.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListInvoicesResponse> ListInvoicesAsync(string customerId, string billingSetup, string issueYear, gagve::MonthOfYearEnum.Types.MonthOfYear issueMonth, gaxgrpc::CallSettings callSettings = null) =>
ListInvoicesAsync(new ListInvoicesRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
BillingSetup = gax::GaxPreconditions.CheckNotNullOrEmpty(billingSetup, nameof(billingSetup)),
IssueYear = gax::GaxPreconditions.CheckNotNullOrEmpty(issueYear, nameof(issueYear)),
IssueMonth = issueMonth,
}, callSettings);
/// <summary>
/// Returns all invoices associated with a billing setup, for a given month.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer to fetch invoices for.
/// </param>
/// <param name="billingSetup">
/// Required. The billing setup resource name of the requested invoices.
///
/// `customers/{customer_id}/billingSetups/{billing_setup_id}`
/// </param>
/// <param name="issueYear">
/// Required. The issue year to retrieve invoices, in yyyy format. Only
/// invoices issued in 2019 or later can be retrieved.
/// </param>
/// <param name="issueMonth">
/// Required. The issue month to retrieve invoices.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListInvoicesResponse> ListInvoicesAsync(string customerId, string billingSetup, string issueYear, gagve::MonthOfYearEnum.Types.MonthOfYear issueMonth, st::CancellationToken cancellationToken) =>
ListInvoicesAsync(customerId, billingSetup, issueYear, issueMonth, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>InvoiceService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A service to fetch invoices issued for a billing setup during a given month.
/// </remarks>
public sealed partial class InvoiceServiceClientImpl : InvoiceServiceClient
{
private readonly gaxgrpc::ApiCall<ListInvoicesRequest, ListInvoicesResponse> _callListInvoices;
/// <summary>
/// Constructs a client wrapper for the InvoiceService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="InvoiceServiceSettings"/> used within this client.</param>
public InvoiceServiceClientImpl(InvoiceService.InvoiceServiceClient grpcClient, InvoiceServiceSettings settings)
{
GrpcClient = grpcClient;
InvoiceServiceSettings effectiveSettings = settings ?? InvoiceServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callListInvoices = clientHelper.BuildApiCall<ListInvoicesRequest, ListInvoicesResponse>(grpcClient.ListInvoicesAsync, grpcClient.ListInvoices, effectiveSettings.ListInvoicesSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callListInvoices);
Modify_ListInvoicesApiCall(ref _callListInvoices);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListInvoicesApiCall(ref gaxgrpc::ApiCall<ListInvoicesRequest, ListInvoicesResponse> call);
partial void OnConstruction(InvoiceService.InvoiceServiceClient grpcClient, InvoiceServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC InvoiceService client</summary>
public override InvoiceService.InvoiceServiceClient GrpcClient { get; }
partial void Modify_ListInvoicesRequest(ref ListInvoicesRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns all invoices associated with a billing setup, for a given month.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ListInvoicesResponse ListInvoices(ListInvoicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListInvoicesRequest(ref request, ref callSettings);
return _callListInvoices.Sync(request, callSettings);
}
/// <summary>
/// Returns all invoices associated with a billing setup, for a given month.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ListInvoicesResponse> ListInvoicesAsync(ListInvoicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListInvoicesRequest(ref request, ref callSettings);
return _callListInvoices.Async(request, callSettings);
}
}
}
| 55.862434 | 556 | 0.678253 | [
"Apache-2.0"
] | GraphikaPS/google-ads-dotnet | src/V6/Services/InvoiceServiceClient.g.cs | 21,116 | C# |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2019 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
// Review: Under construction - StL/14-10-05
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using PikaPDF.Core.Drawing;
using PikaPDF.Core.Pdf.Actions;
using PikaPDF.Core.Pdf.Advanced;
using PikaPDF.Core.Pdf.enums;
using PikaPDF.Core.Pdf.Internal;
using PikaPDF.Core.Pdf.IO;
namespace PikaPDF.Core.Pdf
{
/// <summary>
/// Represents an outline item in the outlines tree. An 'outline' is also known as a 'bookmark'.
/// </summary>
public sealed class PdfOutline : PdfDictionary
{
// Reference: 8.2.2 Document Outline / Page 584
/// <summary>
/// Initializes a new instance of the <see cref="PdfOutline"/> class.
/// </summary>
public PdfOutline()
{
// Create _outlines on demand.
//_outlines = new PdfOutlineCollection(this);
}
/// <summary>
/// Initializes a new instance of the <see cref="PdfOutline"/> class.
/// </summary>
/// <param name="document">The document.</param>
internal PdfOutline(PdfDocument document)
: base(document)
{
// Create _outlines on demand.
//_outlines = new PdfOutlineCollection(this);
}
/// <summary>
/// Initializes a new instance from an existing dictionary. Used for object type transformation.
/// </summary>
public PdfOutline(PdfDictionary dict)
: base(dict)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="PdfOutline"/> class.
/// </summary>
/// <param name="title">The outline text.</param>
/// <param name="destinationPage">The destination page.</param>
/// <param name="opened">Specifies whether the node is displayed expanded (opened) or collapsed.</param>
/// <param name="style">The font style used to draw the outline text.</param>
/// <param name="textColor">The color used to draw the outline text.</param>
public PdfOutline(string title, PdfPage destinationPage, bool opened, PdfOutlineStyle style, XColor textColor)
{
Title = title;
DestinationPage = destinationPage;
Opened = opened;
Style = style;
TextColor = textColor;
}
/// <summary>
/// Initializes a new instance of the <see cref="PdfOutline"/> class.
/// </summary>
/// <param name="title">The outline text.</param>
/// <param name="destinationPage">The destination page.</param>
/// <param name="opened">Specifies whether the node is displayed expanded (opened) or collapsed.</param>
/// <param name="style">The font style used to draw the outline text.</param>
public PdfOutline(string title, PdfPage destinationPage, bool opened, PdfOutlineStyle style)
{
Title = title;
DestinationPage = destinationPage;
Opened = opened;
Style = style;
}
/// <summary>
/// Initializes a new instance of the <see cref="PdfOutline"/> class.
/// </summary>
/// <param name="title">The outline text.</param>
/// <param name="destinationPage">The destination page.</param>
/// <param name="opened">Specifies whether the node is displayed expanded (opened) or collapsed.</param>
public PdfOutline(string title, PdfPage destinationPage, bool opened)
{
Title = title;
DestinationPage = destinationPage;
Opened = opened;
}
/// <summary>
/// Initializes a new instance of the <see cref="PdfOutline"/> class.
/// </summary>
/// <param name="title">The outline text.</param>
/// <param name="destinationPage">The destination page.</param>
public PdfOutline(string title, PdfPage destinationPage)
{
Title = title;
DestinationPage = destinationPage;
}
internal int Count
{
get { return _count; }
set { _count = value; }
}
int _count;
/// <summary>
/// The total number of open descendants at all lower levels.
/// </summary>
internal int OpenCount;
/// <summary>
/// Counts the open outline items. Not yet used.
/// </summary>
internal int CountOpen()
{
int count = _opened ? 1 : 0;
if (_outlines != null)
count += _outlines.CountOpen();
return count;
}
/// <summary>
/// Gets the parent of this outline item. The root item has no parent and returns null.
/// </summary>
public PdfOutline Parent
{
get { return _parent; }
internal set { _parent = value; }
}
PdfOutline _parent;
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title
{
get { return Elements.GetString(Keys.Title); }
set
{
PdfString s = new PdfString(value, PdfStringEncoding.Unicode);
Elements.SetValue(Keys.Title, s);
}
}
/// <summary>
/// Gets or sets the destination page.
/// </summary>
public PdfPage DestinationPage
{
get { return _destinationPage; }
set { _destinationPage = value; }
}
PdfPage _destinationPage;
/// <summary>
/// Gets or sets the left position of the page positioned at the left side of the window.
/// Applies only if PageDestinationType is Xyz, FitV, FitR, or FitBV.
/// </summary>
public double? Left
{
get { return _left; }
set { _left = value; }
}
double? _left = null;
/// <summary>
/// Gets or sets the top position of the page positioned at the top side of the window.
/// Applies only if PageDestinationType is Xyz, FitH, FitR, ob FitBH.
/// </summary>
public double? Top
{
get { return _top; }
set { _top = value; }
}
double? _top = null;
/// <summary>
/// Gets or sets the right position of the page positioned at the right side of the window.
/// Applies only if PageDestinationType is FitR.
/// </summary>
public double Right // Cannot be null in a valid PDF.
{
get { return _right; }
set { _right = value; }
}
double _right = double.NaN;
/// <summary>
/// Gets or sets the bottom position of the page positioned at the bottom side of the window.
/// Applies only if PageDestinationType is FitR.
/// </summary>
public double Bottom // Cannot be null in a valid PDF.
{
get { return _bottom; }
set { _bottom = value; }
}
double _bottom = double.NaN;
/// <summary>
/// Gets or sets the zoom faction of the page.
/// Applies only if PageDestinationType is Xyz.
/// </summary>
public double? Zoom
{
get { return _zoom; }
set
{
if (value.HasValue && value.Value == 0)
_zoom = null;
else
_zoom = value;
}
}
double? _zoom; // PDF treats 0 and null equally.
/// <summary>
/// Gets or sets whether the outline item is opened (or expanded).
/// </summary>
public bool Opened
{
get { return _opened; }
#if true
set { _opened = value; }
#else
// TODO: adjust openCount of ascendant...
set
{
if (_opened != value)
{
_opened = value;
int sign = value ? 1 : -1;
PdfOutline parent = _parent;
if (_opened)
{
while (parent != null)
parent.openCount += 1 + _openCount;
}
else
{
}
}
}
#endif
}
bool _opened;
/// <summary>
/// Gets or sets the style of the outline text.
/// </summary>
public PdfOutlineStyle Style
{
get { return (PdfOutlineStyle)Elements.GetInteger(Keys.F); }
set { Elements.SetInteger(Keys.F, (int)value); }
}
/// <summary>
/// Gets or sets the type of the page destination.
/// </summary>
public PdfPageDestinationType PageDestinationType
{
get { return _pageDestinationType; }
set { _pageDestinationType = value; }
}
PdfPageDestinationType _pageDestinationType = PdfPageDestinationType.Xyz;
/// <summary>
/// Gets or sets the color of the text.
/// </summary>
/// <value>The color of the text.</value>
public XColor TextColor
{
get { return _textColor; }
set { _textColor = value; }
}
XColor _textColor;
/// <summary>
/// Gets a value indicating whether this outline object has child items.
/// </summary>
public bool HasChildren
{
get { return _outlines != null && _outlines.Count > 0; }
}
/// <summary>
/// Gets the outline collection of this node.
/// </summary>
public PdfOutlineCollection Outlines
{
get { return _outlines ?? (_outlines = new PdfOutlineCollection(Owner, this)); }
}
PdfOutlineCollection _outlines;
/// <summary>
/// Initializes this instance from an existing PDF document.
/// </summary>
void Initialize()
{
string title;
if (Elements.TryGetString(Keys.Title, out title))
Title = title;
PdfReference parentRef = Elements.GetReference(Keys.Parent);
if (parentRef != null)
{
PdfOutline parent = parentRef.Value as PdfOutline;
if (parent != null)
Parent = parent;
}
Count = Elements.GetInteger(Keys.Count);
PdfArray colors = Elements.GetArray(Keys.C);
if (colors != null && colors.Elements.Count == 3)
{
double r = colors.Elements.GetReal(0);
double g = colors.Elements.GetReal(1);
double b = colors.Elements.GetReal(2);
TextColor = XColor.FromArgb((int)(r * 255), (int)(g * 255), (int)(b * 255));
}
// Style directly works on dictionary element.
PdfItem dest = Elements.GetValue(Keys.Dest);
PdfItem a = Elements.GetValue(Keys.A);
Debug.Assert(dest == null || a == null, "Either destination or goto action.");
PdfArray destArray = null;
if (dest != null)
{
destArray = dest as PdfArray;
if (destArray != null)
{
SplitDestinationPage(destArray);
}
else
{
Debug.Assert(false, "See what to do when this happened.");
}
}
else if (a != null)
{
// The dictionary should be a GoTo action.
PdfDictionary action = a as PdfDictionary;
if (action != null && action.Elements.GetName(PdfAction.Keys.S) == "/GoTo")
{
dest = action.Elements[PdfGoToAction.Keys.D];
destArray = dest as PdfArray;
if (destArray != null)
{
// Replace Action with /Dest entry.
Elements.Remove(Keys.A);
Elements.Add(Keys.Dest, destArray);
SplitDestinationPage(destArray);
}
else
{
throw new Exception("Destination Array expected.");
}
}
else
{
Debug.Assert(false, "See what to do when this happened.");
}
}
else
{
// Neither destination page nor GoTo action.
}
InitializeChildren();
}
void SplitDestinationPage(PdfArray destination) // Reference: 8.2 Destination syntax / Page 582
{
// ReSharper disable HeuristicUnreachableCode
#pragma warning disable 162
// The destination page may not yet have been transformed to PdfPage.
PdfDictionary destPage = (PdfDictionary)((PdfReference)destination.Elements[0]).Value;
PdfPage page = destPage as PdfPage;
if (page == null)
page = new PdfPage(destPage);
DestinationPage = page;
PdfName type = destination.Elements[1] as PdfName;
if (type != null)
{
PageDestinationType = (PdfPageDestinationType)Enum.Parse(typeof(PdfPageDestinationType), type.Value.Substring(1), true);
switch (PageDestinationType)
{
// [page /XYZ left top zoom] -- left, top, and zoom can be null.
case PdfPageDestinationType.Xyz:
Left = destination.Elements.GetNullableReal(2);
Top = destination.Elements.GetNullableReal(3);
Zoom = destination.Elements.GetNullableReal(4); // For this parameter, null and 0 have the same meaning.
break;
// [page /Fit]
case PdfPageDestinationType.Fit:
// /Fit has no parameters.
break;
// [page /FitH top] -- top can be null.
case PdfPageDestinationType.FitH:
Top = destination.Elements.GetNullableReal(2);
break;
// [page /FitV left] -- left can be null.
case PdfPageDestinationType.FitV:
Left = destination.Elements.GetNullableReal(2);
break;
// [page /FitR left bottom right top] -- left, bottom, right, and top must not be null.
// TODO An exception in GetReal leads to an inconsistent document. Deal with that - e.g. by registering the corruption and preventing the user from saving the corrupted document.
case PdfPageDestinationType.FitR:
Left = destination.Elements.GetReal(2);
Bottom = destination.Elements.GetReal(3);
Right = destination.Elements.GetReal(4);
Top = destination.Elements.GetReal(5);
break;
// [page /FitB]
case PdfPageDestinationType.FitB:
// /Fit has no parameters.
break;
// [page /FitBH top] -- top can be null.
case PdfPageDestinationType.FitBH:
Top = destination.Elements.GetReal(2);
break;
// [page /FitBV left] -- left can be null.
case PdfPageDestinationType.FitBV:
Left = destination.Elements.GetReal(2);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
#pragma warning restore 162
// ReSharper restore HeuristicUnreachableCode
}
void InitializeChildren()
{
PdfReference firstRef = Elements.GetReference(Keys.First);
PdfReference lastRef = Elements.GetReference(Keys.Last);
PdfReference current = firstRef;
while (current != null)
{
// Create item and add it to outline items dictionary.
PdfOutline item = new PdfOutline((PdfDictionary)current.Value);
Outlines.Add(item);
current = item.Elements.GetReference(Keys.Next);
#if DEBUG_
if (current == null)
{
if (item.Reference != lastRef)
{
// Word produces PDFs that come to this case.
GetType();
}
}
#endif
}
}
/// <summary>
/// Creates key/values pairs according to the object structure.
/// </summary>
internal override void PrepareForSave()
{
bool hasKids = HasChildren;
// Is something to do at all?
if (_parent != null || hasKids)
{
if (_parent == null)
{
// Case: This is the outline dictionary (the root).
// Reference: TABLE 8.3 Entries in the outline dictionary / Page 585
Debug.Assert(_outlines != null && _outlines.Count > 0 && _outlines[0] != null);
Elements[Keys.First] = _outlines[0].Reference;
Elements[Keys.Last] = _outlines[_outlines.Count - 1].Reference;
// TODO: /Count - the meaning is not completely clear to me.
// Get PDFs created with Acrobat and analyze what to implement.
if (OpenCount > 0)
Elements[Keys.Count] = new PdfInteger(OpenCount);
}
else
{
// Case: This is an outline item dictionary.
// Reference: TABLE 8.4 Entries in the outline item dictionary / Page 585
Elements[Keys.Parent] = _parent.Reference;
int count = _parent._outlines.Count;
int index = _parent._outlines.IndexOf(this);
Debug.Assert(index != -1);
// Has destination?
if (DestinationPage != null)
Elements[Keys.Dest] = CreateDestArray();
// Not the first element?
if (index > 0)
Elements[Keys.Prev] = _parent._outlines[index - 1].Reference;
// Not the last element?
if (index < count - 1)
Elements[Keys.Next] = _parent._outlines[index + 1].Reference;
if (hasKids)
{
Elements[Keys.First] = _outlines[0].Reference;
Elements[Keys.Last] = _outlines[_outlines.Count - 1].Reference;
}
// TODO: /Count - the meaning is not completely clear to me
if (OpenCount > 0)
Elements[Keys.Count] = new PdfInteger((_opened ? 1 : -1) * OpenCount);
if (_textColor != XColor.Empty && Owner.HasVersion("1.4"))
Elements[Keys.C] = new PdfLiteral("[{0}]", PdfEncoders.ToString(_textColor, PdfColorMode.Rgb));
// if (Style != PdfOutlineStyle.Regular && Document.HasVersion("1.4"))
// //pdf.AppendFormat("/F {0}\n", (int)_style);
// Elements[Keys.F] = new PdfInteger((int)_style);
}
// Prepare child elements.
if (hasKids)
{
foreach (PdfOutline outline in _outlines)
outline.PrepareForSave();
}
}
}
PdfArray CreateDestArray()
{
PdfArray dest = null;
switch (PageDestinationType)
{
// [page /XYZ left top zoom]
case PdfPageDestinationType.Xyz:
dest = new PdfArray(Owner,
DestinationPage.Reference, new PdfLiteral(String.Format("/XYZ {0} {1} {2}", Fd(Left), Fd(Top), Fd(Zoom))));
break;
// [page /Fit]
case PdfPageDestinationType.Fit:
dest = new PdfArray(Owner,
DestinationPage.Reference, new PdfLiteral("/Fit"));
break;
// [page /FitH top]
case PdfPageDestinationType.FitH:
dest = new PdfArray(Owner,
DestinationPage.Reference, new PdfLiteral(String.Format("/FitH {0}", Fd(Top))));
break;
// [page /FitV left]
case PdfPageDestinationType.FitV:
dest = new PdfArray(Owner,
DestinationPage.Reference, new PdfLiteral(String.Format("/FitV {0}", Fd(Left))));
break;
// [page /FitR left bottom right top]
case PdfPageDestinationType.FitR:
dest = new PdfArray(Owner,
DestinationPage.Reference, new PdfLiteral(String.Format("/FitR {0} {1} {2} {3}", Fd(Left), Fd(Bottom), Fd(Right), Fd(Top))));
break;
// [page /FitB]
case PdfPageDestinationType.FitB:
dest = new PdfArray(Owner,
DestinationPage.Reference, new PdfLiteral("/FitB"));
break;
// [page /FitBH top]
case PdfPageDestinationType.FitBH:
dest = new PdfArray(Owner,
DestinationPage.Reference, new PdfLiteral(String.Format("/FitBH {0}", Fd(Top))));
break;
// [page /FitBV left]
case PdfPageDestinationType.FitBV:
dest = new PdfArray(Owner,
DestinationPage.Reference, new PdfLiteral(String.Format("/FitBV {0}", Fd(Left))));
break;
default:
throw new ArgumentOutOfRangeException();
}
return dest;
}
/// <summary>
/// Format double.
/// </summary>
string Fd(double value)
{
if (Double.IsNaN(value))
throw new InvalidOperationException("Value is not a valid Double.");
return value.ToString("#.##", CultureInfo.InvariantCulture);
//return Double.IsNaN(value) ? "null" : value.ToString("#.##", CultureInfo.InvariantCulture);
}
/// <summary>
/// Format nullable double.
/// </summary>
string Fd(double? value)
{
return value.HasValue ? value.Value.ToString("#.##", CultureInfo.InvariantCulture) : "null";
}
internal override void WriteObject(PdfWriter writer)
{
#if DEBUG
writer.WriteRaw("% Title = " + FilterUnicode(Title) + "\n");
#endif
// TODO: Proof that there is nothing to do here.
bool hasKids = HasChildren;
if (_parent != null || hasKids)
{
////// Everything done in PrepareForSave
////if (_parent == null)
////{
//// // This is the outline dictionary (the root)
////}
////else
////{
//// // This is an outline item dictionary
////}
base.WriteObject(writer);
}
}
#if DEBUG
private string FilterUnicode(string text)
{
StringBuilder result = new StringBuilder();
foreach (char ch in text)
result.Append((uint)ch < 256 ? (ch != '\r' && ch != '\n' ? ch : ' ') : '?');
return result.ToString();
}
#endif
/// <summary>
/// Predefined keys of this dictionary.
/// </summary>
internal sealed class Keys : KeysBase
{
// ReSharper disable InconsistentNaming
/// <summary>
/// (Optional) The type of PDF object that this dictionary describes; if present,
/// must be Outlines for an outline dictionary.
/// </summary>
[KeyInfo(KeyType.Name | KeyType.Optional, FixedValue = "Outlines")]
public const string Type = "/Type";
// Outline and outline item are combined
///// <summary>
///// (Required if there are any open or closed outline entries; must be an indirect reference)
///// An outline item dictionary representing the first top-level item in the outline.
///// </summary>
//[KeyInfo(KeyType.Dictionary)]
//public const string First = "/First";
//
///// <summary>
///// (Required if there are any open or closed outline entries; must be an indirect reference)
///// An outline item dictionary representing the last top-level item in the outline.
///// </summary>
//[KeyInfo(KeyType.Dictionary)]
//public const string Last = "/Last";
//
///// <summary>
///// (Required if the document has any open outline entries) The total number of open items at all
///// levels of the outline. This entry should be omitted if there are no open outline items.
///// </summary>
//[KeyInfo(KeyType.Integer)]
//public const string Count = "/Count";
/// <summary>
/// (Required) The text to be displayed on the screen for this item.
/// </summary>
[KeyInfo(KeyType.String | KeyType.Required)]
public const string Title = "/Title";
/// <summary>
/// (Required; must be an indirect reference) The parent of this item in the outline hierarchy.
/// The parent of a top-level item is the outline dictionary itself.
/// </summary>
[KeyInfo(KeyType.Dictionary | KeyType.Required)]
public const string Parent = "/Parent";
/// <summary>
/// (Required for all but the first item at each level; must be an indirect reference)
/// The previous item at this outline level.
/// </summary>
[KeyInfo(KeyType.Dictionary | KeyType.Required)]
public const string Prev = "/Prev";
/// <summary>
/// (Required for all but the last item at each level; must be an indirect reference)
/// The next item at this outline level.
/// </summary>
[KeyInfo(KeyType.Dictionary | KeyType.Required)]
public const string Next = "/Next";
/// <summary>
/// (Required if the item has any descendants; must be an indirect reference)
/// The first of this item’s immediate children in the outline hierarchy.
/// </summary>
[KeyInfo(KeyType.Dictionary | KeyType.Required)]
public const string First = "/First";
/// <summary>
/// (Required if the item has any descendants; must be an indirect reference)
/// The last of this item’s immediate children in the outline hierarchy.
/// </summary>
[KeyInfo(KeyType.Dictionary | KeyType.Required)]
public const string Last = "/Last";
/// <summary>
/// (Required if the item has any descendants) If the item is open, the total number of its
/// open descendants at all lower levels of the outline hierarchy. If the item is closed, a
/// negative integer whose absolute value specifies how many descendants would appear if the
/// item were reopened.
/// </summary>
[KeyInfo(KeyType.Integer | KeyType.Required)]
public const string Count = "/Count";
/// <summary>
/// (Optional; not permitted if an A entry is present) The destination to be displayed when this
/// item is activated.
/// </summary>
[KeyInfo(KeyType.ArrayOrNameOrString | KeyType.Optional)]
public const string Dest = "/Dest";
/// <summary>
/// (Optional; not permitted if a Dest entry is present) The action to be performed when
/// this item is activated.
/// </summary>
[KeyInfo(KeyType.Dictionary | KeyType.Optional)]
public const string A = "/A";
/// <summary>
/// (Optional; PDF 1.3; must be an indirect reference) The structure element to which the item
/// refers.
/// Note: The ability to associate an outline item with a structure element (such as the beginning
/// of a chapter) is a PDF 1.3 feature. For backward compatibility with earlier PDF versions, such
/// an item should also specify a destination (Dest) corresponding to an area of a page where the
/// contents of the designated structure element are displayed.
/// </summary>
[KeyInfo(KeyType.Dictionary | KeyType.Optional)]
public const string SE = "/SE";
/// <summary>
/// (Optional; PDF 1.4) An array of three numbers in the range 0.0 to 1.0, representing the
/// components in the DeviceRGB color space of the color to be used for the outline entry’s text.
/// Default value: [0.0 0.0 0.0].
/// </summary>
[KeyInfo(KeyType.Array | KeyType.Optional)]
public const string C = "/C";
/// <summary>
/// (Optional; PDF 1.4) A set of flags specifying style characteristics for displaying the outline
/// item’s text. Default value: 0.
/// </summary>
[KeyInfo(KeyType.Integer | KeyType.Optional)]
public const string F = "/F";
/// <summary>
/// Gets the KeysMeta for these keys.
/// </summary>
public static DictionaryMeta Meta
{
get { return _meta ?? (_meta = CreateMeta(typeof(Keys))); }
}
static DictionaryMeta _meta;
// ReSharper restore InconsistentNaming
}
/// <summary>
/// Gets the KeysMeta of this dictionary type.
/// </summary>
internal override DictionaryMeta Meta
{
get { return Keys.Meta; }
}
}
}
| 38.642005 | 198 | 0.518498 | [
"MIT"
] | marcindawidziuk/PikaPDF | src/PikaPDF.Core/Pdf/PdfOutline.cs | 32,392 | C# |
/***
Copyright (C) 2018-2019. dc-koromo. All Rights Reserved.
Author: Koromo Copy Developer
***/
using Etier.IconHelper;
using Koromo_Copy.Component.Hitomi;
using Koromo_Copy.Controls;
using Koromo_Copy.Fs;
using Koromo_Copy.Fs.FileIcon;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Koromo_Copy.Utility
{
public partial class HitomiExplorer : Form
{
ImageList smallImageList = new ImageList();
ImageList largeImageList = new ImageList();
IconListManager iconListManager;
FileIndexor indexor;
public HitomiExplorer()
{
InitializeComponent();
smallImageList.ColorDepth = ColorDepth.Depth32Bit;
largeImageList.ColorDepth = ColorDepth.Depth32Bit;
smallImageList.ImageSize = new System.Drawing.Size(16, 16);
largeImageList.ImageSize = new System.Drawing.Size(32, 32);
smallImageList.Images.Add(FolderIcon.GetFolderIcon(
FolderIcon.IconSize.Small,
FolderIcon.FolderType.Closed));
iconListManager = new IconListManager(smallImageList, largeImageList);
PathTree.ImageList = smallImageList;
}
private void HitomiExplorer_Load(object sender, EventArgs e)
{
ColumnSorter.InitListView(AvailableList);
ColumnSorter.InitListView(listView1);
string[] splits = Settings.Instance.Hitomi.Path.Split('\\');
string path = "";
for (int i = 0; i < splits.Length; i++)
{
if (!(splits[i].Contains("{") && splits[i].Contains("}")))
path += splits[i] + "\\";
else
break;
}
tbPath.Text = path;
}
#region 파일 시스템 리스팅
private async void bOpen_ClickAsync(object sender, EventArgs e)
{
indexor = null;
indexor = new FileIndexor();
PathTree.Nodes.Clear();
AvailableList.Items.Clear();
Monitor.Instance.Push($"[Hitomi Explorer] Open directory '{tbPath.Text}'");
await indexor.ListingDirectoryAsync(tbPath.Text);
Monitor.Instance.Push($"[Hitomi Explorer] Complete open! DirCount={indexor.Count}");
listing(indexor);
}
private void listing(FileIndexor fi)
{
FileIndexorNode node = fi.GetRootNode();
foreach (FileIndexorNode n in node.Nodes)
{
make_node(PathTree.Nodes, Path.GetFileName(n.Path.Remove(n.Path.Length - 1)));
make_tree(n, PathTree.Nodes[PathTree.Nodes.Count - 1]);
}
foreach (FileInfo f in new DirectoryInfo(node.Path).GetFiles())
make_node(PathTree.Nodes, f.Name);
}
private void make_tree(FileIndexorNode fn, TreeNode tn)
{
foreach (FileIndexorNode n in fn.Nodes)
{
make_node(tn.Nodes, Path.GetFileName(n.Path.Remove(n.Path.Length - 1)));
make_tree(n, tn.Nodes[tn.Nodes.Count - 1]);
}
foreach (FileInfo f in new DirectoryInfo(fn.Path).GetFiles())
make_node(tn.Nodes, f.Name);
}
private void make_node(TreeNodeCollection tnc, string path)
{
TreeNode tn = new TreeNode(path);
tnc.Add(tn);
string fullpath = Path.Combine(tbPath.Text, tn.FullPath);
if (File.Exists(fullpath))
{
int index = iconListManager.AddFileIcon(fullpath);
tn.ImageIndex = index;
tn.SelectedImageIndex = index;
}
else
{
tn.ImageIndex = 0;
}
}
#endregion
#region 규칙 적용 및 추출
List<Tuple<string, string, HitomiIndexMetadata?>> metadatas = new List<Tuple<string, string, HitomiIndexMetadata?>>();
List<KeyValuePair<string, int>> artist_rank;
Dictionary<string, int> artist_rank_dic;
int visit_count = 0;
int available_count = 0;
bool show_unavailables = true;
bool deal_group_with_artist = false;
bool search_subfiles_whenever = false;
bool deal_artists_with_parent_folder = true;
private void bApply_Click(object sender, EventArgs e)
{
var regexs = tbRule.Text.Split(',').ToList().Select(x => new Regex(x.Trim())).ToList();
metadatas.Clear();
visit_count = 0;
available_count = 0;
foreach (var node in PathTree.Nodes.OfType<TreeNode>())
RecursiveVisit(node, regexs);
Monitor.Instance.Push($"[Hitomi Explorer] Apply! visit_count={visit_count}, available_count={available_count}");
List<ListViewItem> lvil = new List<ListViewItem>();
for (int i = 0; i < metadatas.Count; i++)
{
if (show_unavailables == false && !metadatas[i].Item3.HasValue) continue;
lvil.Add(new ListViewItem(new string[]
{
(i+1).ToString(),
metadatas[i].Item1,
metadatas[i].Item2,
metadatas[i].Item3.HasValue.ToString()
}));
}
AvailableList.Items.Clear();
AvailableList.Items.AddRange(lvil.ToArray());
//////////////////////////////////////////////////
Dictionary<string, int> artist_count = new Dictionary<string, int>();
foreach (var md in metadatas)
{
if (!deal_artists_with_parent_folder)
{
if (md.Item3.HasValue && md.Item3.Value.Artists != null)
foreach (var _artist in md.Item3.Value.Artists)
{
var artist = HitomiIndex.Instance.index.Artists[_artist];
if (artist_count.ContainsKey(artist))
artist_count[artist] += 1;
else
artist_count.Add(artist, 1);
}
if (deal_group_with_artist && md.Item3.HasValue && md.Item3.Value.Groups != null)
foreach (var _group in md.Item3.Value.Groups)
{
var group = HitomiIndex.Instance.index.Artists[_group];
string tmp = "group:" + group;
if (artist_count.ContainsKey(tmp))
artist_count[tmp] += 1;
else
artist_count.Add(tmp, 1);
}
}
else
{
var split = md.Item1.Split('\\');
string parent_folder = split.Length >= 2 ? split[split.Length - 2] : "";
if (artist_count.ContainsKey(parent_folder))
artist_count[parent_folder] += 1;
else
artist_count.Add(parent_folder, 1);
}
}
artist_rank = artist_count.ToList();
artist_rank.Sort((a, b) => b.Value.CompareTo(a.Value));
artist_rank_dic = new Dictionary<string, int>();
lvil.Clear();
for (int i = 0; i < artist_rank.Count; i++)
{
lvil.Add(new ListViewItem(new string[]
{
(i+1).ToString(),
artist_rank[i].Key,
artist_rank[i].Value.ToString()
}));
artist_rank_dic.Add(artist_rank[i].Key, i);
}
lvArtistPriority.Items.Clear();
lvArtistPriority.Items.AddRange(lvil.ToArray());
}
private void RecursiveVisit(TreeNode node, List<Regex> regex)
{
string match = "";
if (regex.Any(x => {
if (!x.Match(Path.GetFileNameWithoutExtension(node.Text)).Success) return false;
match = x.Match(Path.GetFileNameWithoutExtension(node.Text)).Groups[1].Value;
return true;
}))
{
metadatas.Add(new Tuple<string, string, HitomiIndexMetadata?>(node.FullPath, match, HitomiDataAnalysis.GetMetadataFromMagic(match)));
available_count += 1;
if (!search_subfiles_whenever)
return;
}
visit_count += 1;
foreach (var cnode in node.Nodes.OfType<TreeNode>())
RecursiveVisit(cnode, regex);
}
#endregion
#region 재배치 도구
private string MakeDownloadDirectory(string source, string artists, HitomiIndexMetadata metadata, string extension)
{
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
string title = metadata.Name ?? "";
string type = metadata.Type < 0 ? "" : HitomiIndex.Instance.index.Types[metadata.Type];
string series = "";
//if (HitomiSetting.Instance.GetModel().ReplaceArtistsWithTitle)
//{
// TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
// artists = textInfo.ToTitleCase(artists);
//}
if (metadata.Parodies != null) series = HitomiIndex.Instance.index.Series[metadata.Parodies[0]];
if (title != null)
foreach (char c in invalid) title = title.Replace(c.ToString(), "");
if (artists != null)
foreach (char c in invalid) artists = artists.Replace(c.ToString(), "");
if (series != null)
foreach (char c in invalid) series = series.Replace(c.ToString(), "");
if (artists.StartsWith("group:"))
artists = artists.Substring("group:".Length);
string path = source;
path = Regex.Replace(path, "{Title}", title, RegexOptions.IgnoreCase);
path = Regex.Replace(path, "{Artists}", artists, RegexOptions.IgnoreCase);
path = Regex.Replace(path, "{Id}", metadata.ID.ToString(), RegexOptions.IgnoreCase);
path = Regex.Replace(path, "{Type}", type, RegexOptions.IgnoreCase);
path = Regex.Replace(path, "{Date}", DateTime.Now.ToString(), RegexOptions.IgnoreCase);
path = Regex.Replace(path, "{Series}", series, RegexOptions.IgnoreCase);
path += extension;
return path;
}
private List<Tuple<string, string>> GetResult(string source, bool rename = false)
{
List<Tuple<string, string>> result = new List<Tuple<string, string>>();
foreach (var md in metadatas)
{
if (!md.Item3.HasValue) continue;
string extension = Path.GetExtension(md.Item1);
string dir = rename ? Path.GetDirectoryName(md.Item1) + '\\' : "";
if (md.Item3.Value.Artists == null && md.Item3.Value.Groups == null)
{
result.Add(new Tuple<string, string>(md.Item1, dir + MakeDownloadDirectory(source, "", md.Item3.Value, extension)));
continue;
}
List<string> artist_group = new List<string>();
if (md.Item3.Value.Artists != null)
foreach (var artist in md.Item3.Value.Artists)
artist_group.Add(HitomiIndex.Instance.index.Artists[artist]);
else if (md.Item3.Value.Groups != null)
foreach (var group in md.Item3.Value.Groups)
artist_group.Add(HitomiIndex.Instance.index.Groups[group]);
//if (tgAEG.Checked == true && md.Item3.Value.Groups != null)
// foreach (var group in md.Item3.Value.Groups)
// artist_group.Add("group:" + group);
int top_rank = 0;
//if (md.Item3.Value.Artists != null)
//{
// for (int i = 1; i < artist_group.Count; i++)
// {
// if (artist_rank_dic[artist_group[top_rank]] > artist_rank_dic[artist_group[i]])
// top_rank = i;
// }
//}
result.Add(new Tuple<string, string>(md.Item1, dir + MakeDownloadDirectory(source, artist_group[top_rank], md.Item3.Value, extension)));
}
return result;
}
private void bReplaceTest_Click(object sender, EventArgs e)
{
var result = GetResult(tbDownloadPath.Text);
List<ListViewItem> lvil = new List<ListViewItem>();
HashSet<string> overlapping_check = new HashSet<string>();
for (int i = 0; i < result.Count; i++)
{
bool err = false;
string err_msg = "Already exists";
if (File.Exists(result[i].Item2)) err = true;
else if (Directory.Exists(result[i].Item2)) err = true;
if (overlapping_check.Contains(result[i].Item2)) { err = true; err_msg = "Overlapping"; }
else overlapping_check.Add(result[i].Item2);
lvil.Add(new ListViewItem(new string[]
{
(i+1).ToString(),
result[i].Item1,
result[i].Item2,
(err ? err_msg : "")
}));
if (err)
{
lvil[i].BackColor = Color.Orange;
lvil[i].ForeColor = Color.White;
}
}
lvReplacerTestResult.Items.Clear();
lvReplacerTestResult.Items.AddRange(lvil.ToArray());
}
private void bMove_Click(object sender, EventArgs e)
{
if (MessageBox.Show("이 과정은 되돌릴 수 없습니다. 계속하시겠습니까?", "Hitomi Copy Article Replacer", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
return;
var result = GetResult(tbDownloadPath.Text);
for (int i = 0; i < result.Count; i++)
{
try
{
string src = Path.Combine(indexor.RootDirectory, result[i].Item1);
string dest = result[i].Item2;
string dir = Path.GetDirectoryName(result[i].Item2);
Directory.CreateDirectory(dir);
if (File.Exists(src))
File.Move(src, dest);
else
Directory.Move(src, dest);
Monitor.Instance.Push($"[Replacer] Move '{src}' => '{dest}'");
}
catch (Exception ex)
{
Monitor.Instance.Push($"[Replacer] Error occurred! {Path.Combine(indexor.RootDirectory, result[i].Item1)} => {result[i].Item2}");
Monitor.Instance.Push(ex);
}
}
}
#endregion
#region 이름 바꾸기 도구
private void bRenameTest_Click(object sender, EventArgs e)
{
var result = GetResult(tbRenameRule.Text, true);
List<ListViewItem> lvil = new List<ListViewItem>();
HashSet<string> overlapping_check = new HashSet<string>();
for (int i = 0; i < result.Count; i++)
{
bool err = false;
string err_msg = "Alread exists";
string dest = Path.Combine(indexor.RootDirectory, result[i].Item2);
if (File.Exists(dest)) err = true;
else if (Directory.Exists(dest)) err = true;
if (overlapping_check.Contains(dest)) { err = true; err_msg = "Overlapping"; }
else overlapping_check.Add(dest);
lvil.Add(new ListViewItem(new string[]
{
(i+1).ToString(),
result[i].Item1,
result[i].Item2,
(err ? err_msg : "")
}));
if (err)
{
lvil[i].BackColor = Color.Orange;
lvil[i].ForeColor = Color.White;
}
}
lvRenamerTestResult.Items.Clear();
lvRenamerTestResult.Items.AddRange(lvil.ToArray());
}
private void bRename_Click(object sender, EventArgs e)
{
if (MessageBox.Show("이 과정은 되돌릴 수 없습니다. 계속하시겠습니까?", "Hitomi Copy Article Renamer", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
return;
var result = GetResult(tbRenameRule.Text, true);
for (int i = 0; i < result.Count; i++)
{
try
{
string src = Path.Combine(indexor.RootDirectory, result[i].Item1);
string dest = Path.Combine(indexor.RootDirectory, result[i].Item2);
string dir = Path.GetDirectoryName(result[i].Item2);
Directory.CreateDirectory(dir);
if (File.Exists(src))
File.Move(src, dest);
else
Directory.Move(src, dest);
Monitor.Instance.Push($"[Renamer] Move '{src}' => '{dest}'");
}
catch (Exception ex)
{
Monitor.Instance.Push($"[Renamer] Error occurred! {Path.Combine(indexor.RootDirectory, result[i].Item1)} => {result[i].Item2}");
Monitor.Instance.Push(ex);
}
}
}
#endregion
#region 로그 매칭 도구
private void bExtract_Click(object sender, EventArgs e)
{
Dictionary<int, HitomiIndexMetadata?> map = new Dictionary<int, HitomiIndexMetadata?>();
foreach (var tuple in metadatas)
{
int key = Convert.ToInt32(tuple.Item2);
if (!map.ContainsKey(key))
map.Add(key, tuple.Item3);
else
{
}
}
List<ListViewItem> lvil = new List<ListViewItem>();
int i = 0;
foreach (var h in HitomiLog.Instance.DownloadTable)
{
if (!map.ContainsKey(h))
{
var md = HitomiDataAnalysis.GetMetadataFromMagic(h.ToString());
List<string> artists = new List<string>();
if (md.HasValue)
{
if (md.Value.Artists != null)
md.Value.Artists.ToList().ForEach(x => artists.Add(HitomiIndex.Instance.index.Artists[x]));
}
lvil.Add(new ListViewItem(new string[]
{
(i+1).ToString(),
h.ToString(),
string.Join(",", artists)
}));
i++;
}
}
listView1.Items.Clear();
listView1.Items.AddRange(lvil.ToArray());
}
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
string artist = listView1.SelectedItems[0].SubItems[2].Text.Split(',')[0].Trim();
if (!string.IsNullOrEmpty(artist))
Global.ShowArtistView(artist);
}
}
#endregion
}
}
| 39.695825 | 163 | 0.507938 | [
"MIT"
] | Terkiss/Koromo-Copy | Koromo Copy/Utility/HitomiExplorer.cs | 20,115 | C# |
using System;
using System.Collections.Generic;
namespace ObjectMapper.Tests.TestClasses
{
public class PersonModel
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? LastUpdatedOn { get; set; }
public bool Active { get; set; }
public Guid RowGuid { get; set; }
public PersonData Data { get; set; }
public double NonMatching { get; set; }
public List<int> List { get; set; }
public PersonAddress Address { get; set; }
public Guid PersonGuid { get; set; }
public decimal? AmountPaid { get; set; }
public DateTime BirthDate { get; set; }
}
} | 31.652174 | 52 | 0.603022 | [
"MIT"
] | JonHaywood/ObjectMapper | source/ObjectMapper.Tests/TestClasses/PersonModel.cs | 730 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Nest
{
internal class AggregateJsonConverter : JsonConverter
{
private static readonly Regex _numeric = new Regex(@"^[\d.]+(\.[\d.]+)?$");
static AggregateJsonConverter()
{
AllReservedAggregationNames = typeof(Parser)
.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)
.Where(f => f.IsLiteral && !f.IsInitOnly)
.Select(f => (string)f.GetValue(null))
.ToArray();
var allKeys = string.Join(", ", AllReservedAggregationNames);
UsingReservedAggNameFormat =
"'{0}' is one of the reserved aggregation keywords"
+ " we use a heuristics based response parser and using these reserved keywords"
+ " could throw its heuristics off course. We are working on a solution in elasticsearch itself to make"
+ " the response parseable. For now these are all the reserved keywords: "
+ allKeys;
}
public static string[] AllReservedAggregationNames { get; }
public override bool CanWrite => false;
public static string UsingReservedAggNameFormat { get; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer
) => ReadAggregate(reader, serializer);
public override bool CanConvert(Type objectType) => objectType == typeof(IAggregate);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) =>
throw new NotSupportedException();
private IAggregate ReadAggregate(JsonReader reader, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.StartObject)
return null;
reader.Read();
if (reader.TokenType != JsonToken.PropertyName)
return null;
IAggregate aggregate = null;
var propertyName = (string)reader.Value;
if (_numeric.IsMatch(propertyName))
aggregate = GetPercentilesAggregate(reader, serializer, true);
var meta = propertyName == Parser.Meta
? GetMetadata(serializer, reader)
: null;
if (aggregate != null)
{
aggregate.Meta = meta;
return aggregate;
}
propertyName = (string)reader.Value;
switch (propertyName)
{
case Parser.Values:
reader.Read();
reader.Read();
aggregate = GetPercentilesAggregate(reader, serializer);
break;
case Parser.Value:
aggregate = GetValueAggregate(reader, serializer);
break;
case Parser.AfterKey:
reader.Read();
var afterKeys = serializer.Deserialize<Dictionary<string, object>>(reader);
reader.Read();
var bucketAggregate = reader.Value.ToString() == Parser.Buckets
? GetMultiBucketAggregate(reader, serializer) as BucketAggregate ?? new BucketAggregate()
: new BucketAggregate();
bucketAggregate.AfterKey = afterKeys;
aggregate = bucketAggregate;
break;
case Parser.Buckets:
case Parser.DocCountErrorUpperBound:
aggregate = GetMultiBucketAggregate(reader, serializer);
break;
case Parser.Count:
aggregate = GetStatsAggregate(reader, serializer);
break;
case Parser.DocCount:
aggregate = GetSingleBucketAggregate(reader, serializer);
break;
case Parser.Bounds:
aggregate = GetGeoBoundsAggregate(reader, serializer);
break;
case Parser.Hits:
aggregate = GetTopHitsAggregate(reader, serializer);
break;
case Parser.Location:
aggregate = GetGeoCentroidAggregate(reader, serializer);
break;
case Parser.Fields:
aggregate = GetMatrixStatsAggregate(reader, serializer);
break;
default:
return null;
}
aggregate.Meta = meta;
return aggregate;
}
private IBucket ReadBucket(JsonReader reader, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.StartObject)
return null;
reader.Read();
if (reader.TokenType != JsonToken.PropertyName)
return null;
IBucket item;
var property = (string)reader.Value;
switch (property)
{
case Parser.Key:
item = GetKeyedBucket(reader, serializer);
break;
case Parser.From:
case Parser.To:
item = GetRangeBucket(reader, serializer);
break;
case Parser.KeyAsString:
item = GetDateHistogramBucket(reader, serializer);
break;
case Parser.DocCount:
item = GetFiltersBucket(reader, serializer);
break;
default:
return null;
}
return item;
}
private Dictionary<string, object> GetMetadata(JsonSerializer serializer, JsonReader reader)
{
// read past "meta" property name to start of object
reader.Read();
var meta = serializer.Deserialize<Dictionary<string, object>>(reader);
// read past the closing end object of "meta" object
reader.Read();
return meta;
}
private IAggregate GetMatrixStatsAggregate(JsonReader reader, JsonSerializer serializer, long? docCount = null)
{
reader.Read();
var matrixStats = new MatrixStatsAggregate { DocCount = docCount };
var array = JArray.Load(reader);
matrixStats.Fields = array.ToObject<List<MatrixStatsField>>();
return matrixStats;
}
private IAggregate GetTopHitsAggregate(JsonReader reader, JsonSerializer serializer)
{
reader.Read();
var o = JObject.Load(reader);
if (o == null)
return null;
var total = o[Parser.Total].ToObject<long>();
var maxScore = o[Parser.MaxScore].ToObject<double?>();
var hits = o[Parser.Hits].Children().OfType<JObject>();
reader.Read();
//using request/response serializer here because doc is wrapped in NEST's Hit<T>
var s = serializer.GetConnectionSettings().RequestResponseSerializer;
var lazyHits = hits.Select(h => new LazyDocument(h, s)).ToList();
return new TopHitsAggregate(lazyHits)
{
Total = total,
MaxScore = maxScore
};
}
private IAggregate GetGeoCentroidAggregate(JsonReader reader, JsonSerializer serializer)
{
reader.Read();
var geoCentroid = new GeoCentroidAggregate { Location = serializer.Deserialize<GeoLocation>(reader) };
reader.Read();
if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == Parser.Count)
{
reader.Read();
geoCentroid.Count = (long)reader.Value;
reader.Read();
}
return geoCentroid;
}
private IAggregate GetGeoBoundsAggregate(JsonReader reader, JsonSerializer serializer)
{
reader.Read();
var o = JObject.Load(reader);
if (o == null)
return null;
var geoBoundsMetric = new GeoBoundsAggregate();
if (o.TryGetValue(Parser.TopLeft, out var topLeftToken) && topLeftToken != null)
{
var topLeft = topLeftToken.ToObject<LatLon>();
if (topLeft != null)
geoBoundsMetric.Bounds.TopLeft = topLeft;
}
if (o.TryGetValue(Parser.BottomRight, out var bottomRightToken) && bottomRightToken != null)
{
var bottomRight = bottomRightToken.ToObject<LatLon>();
if (bottomRight != null)
geoBoundsMetric.Bounds.BottomRight = bottomRight;
}
reader.Read();
return geoBoundsMetric;
}
private IAggregate GetPercentilesAggregate(JsonReader reader, JsonSerializer serializer, bool oldFormat = false)
{
var metric = new PercentilesAggregate();
var percentileItems = new List<PercentileItem>();
if (reader.TokenType == JsonToken.StartObject)
reader.Read();
while (reader.TokenType != JsonToken.EndObject)
{
var propertyName = (string)reader.Value;
if (propertyName.Contains(Parser.AsStringSuffix))
{
reader.Read();
reader.Read();
}
if (reader.TokenType != JsonToken.EndObject)
{
var percentileValue = (string)reader.Value;
var percentile = double.Parse(percentileValue, CultureInfo.InvariantCulture);
reader.Read();
var value = reader.Value as double?;
percentileItems.Add(new PercentileItem()
{
Percentile = percentile,
Value = value.GetValueOrDefault(0)
});
reader.Read();
}
}
metric.Items = percentileItems;
if (!oldFormat) reader.Read();
return metric;
}
private IAggregate GetSingleBucketAggregate(JsonReader reader, JsonSerializer serializer)
{
reader.Read();
var docCount = (reader.Value as long?).GetValueOrDefault(0);
reader.Read();
long bgCount = 0;
if ((string)reader.Value == Parser.BgCount)
{
reader.Read();
bgCount = (reader.Value as long?).GetValueOrDefault(0);
reader.Read();
}
if ((string)reader.Value == Parser.Fields)
return GetMatrixStatsAggregate(reader, serializer, docCount);
if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == Parser.Buckets)
{
var b = GetMultiBucketAggregate(reader, serializer) as BucketAggregate;
return new BucketAggregate
{
BgCount = bgCount,
DocCount = docCount,
Items = b?.Items ?? EmptyReadOnly<IBucket>.Collection
};
}
var nestedAggregations = GetSubAggregates(reader, serializer);
var bucket = new SingleBucketAggregate(nestedAggregations)
{
DocCount = docCount
};
return bucket;
}
private IAggregate GetStatsAggregate(JsonReader reader, JsonSerializer serializer)
{
reader.Read();
var count = (reader.Value as long?).GetValueOrDefault(0);
reader.Read();
if (reader.TokenType == JsonToken.EndObject) return new GeoCentroidAggregate { Count = count };
reader.Read();
var min = reader.Value as double?;
reader.Read();
reader.Read();
var max = reader.Value as double?;
reader.Read();
reader.Read();
var average = reader.Value as double?;
reader.Read();
reader.Read();
var sum = reader.Value as double?;
var statsMetric = new StatsAggregate()
{
Average = average,
Count = count,
Max = max,
Min = min,
Sum = sum
};
reader.Read();
if (reader.TokenType == JsonToken.EndObject)
return statsMetric;
var propertyName = (string)reader.Value;
while (reader.TokenType != JsonToken.EndObject && propertyName.Contains(Parser.AsStringSuffix))
{
reader.Read();
reader.Read();
}
if (reader.TokenType == JsonToken.EndObject)
return statsMetric;
return GetExtendedStatsAggregate(statsMetric, reader);
}
private IAggregate GetExtendedStatsAggregate(StatsAggregate statsMetric, JsonReader reader)
{
var extendedStatsMetric = new ExtendedStatsAggregate()
{
Average = statsMetric.Average,
Count = statsMetric.Count,
Max = statsMetric.Max,
Min = statsMetric.Min,
Sum = statsMetric.Sum
};
reader.Read();
extendedStatsMetric.SumOfSquares = reader.Value as double?;
reader.Read();
reader.Read();
extendedStatsMetric.Variance = reader.Value as double?;
reader.Read();
reader.Read();
extendedStatsMetric.StdDeviation = reader.Value as double?;
reader.Read();
string propertyName;
if (reader.TokenType != JsonToken.EndObject)
{
var bounds = new StandardDeviationBounds();
reader.Read();
reader.Read();
propertyName = (string)reader.Value;
if (propertyName == Parser.Upper)
{
reader.Read();
bounds.Upper = reader.Value as double?;
}
reader.Read();
propertyName = (string)reader.Value;
if (propertyName == Parser.Lower)
{
reader.Read();
bounds.Lower = reader.Value as double?;
}
extendedStatsMetric.StdDeviationBounds = bounds;
reader.Read();
reader.Read();
}
propertyName = (string)reader.Value;
while (reader.TokenType != JsonToken.EndObject && propertyName.Contains(Parser.AsStringSuffix))
{
// std_deviation_bounds is an object, so we need to skip its properties
if (propertyName.Equals(Parser.StdDeviationBoundsAsString))
{
reader.Read();
reader.Read();
reader.Read();
reader.Read();
}
reader.Read();
reader.Read();
}
return extendedStatsMetric;
}
private Dictionary<string, IAggregate> GetSubAggregates(JsonReader reader, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.PropertyName)
return null;
var nestedAggs = new Dictionary<string, IAggregate>();
var currentDepth = reader.Depth;
do
{
var fieldName = (string)reader.Value;
reader.Read();
var agg = ReadAggregate(reader, serializer);
nestedAggs.Add(fieldName, agg);
reader.Read();
if (reader.Depth == currentDepth && reader.TokenType == JsonToken.EndObject || reader.Depth < currentDepth)
break;
} while (true);
return nestedAggs;
}
private IAggregate GetMultiBucketAggregate(JsonReader reader, JsonSerializer serializer)
{
var bucket = new BucketAggregate();
var propertyName = (string)reader.Value;
if (propertyName == Parser.DocCountErrorUpperBound)
{
reader.Read();
bucket.DocCountErrorUpperBound = reader.Value as long?;
reader.Read();
}
propertyName = (string)reader.Value;
if (propertyName == Parser.SumOtherDocCount)
{
reader.Read();
bucket.SumOtherDocCount = reader.Value as long?;
reader.Read();
}
var items = new List<IBucket>();
reader.Read();
if (reader.TokenType == JsonToken.StartObject)
{
reader.Read();
var aggs = new Dictionary<string, IAggregate>();
while (reader.TokenType != JsonToken.EndObject)
{
var name = reader.Value.ToString();
reader.Read();
var innerAgg = ReadAggregate(reader, serializer);
aggs.Add(name, innerAgg);
reader.Read();
}
reader.Read();
return new FiltersAggregate(aggs);
}
if (reader.TokenType != JsonToken.StartArray)
return null;
reader.Read(); //move from start array to start object
if (reader.TokenType == JsonToken.EndArray)
{
reader.Read();
bucket.Items = EmptyReadOnly<IBucket>.Collection;
return bucket;
}
do
{
var item = ReadBucket(reader, serializer);
items.Add(item);
reader.Read();
} while (reader.TokenType != JsonToken.EndArray);
bucket.Items = items;
reader.Read();
if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == Parser.Interval)
{
var interval = reader.ReadAsString();
bucket.Interval = new Time(interval);
}
return bucket;
}
private IAggregate GetValueAggregate(JsonReader reader, JsonSerializer serializer)
{
reader.Read();
var valueMetric = new ValueAggregate
{
Value = reader.Value as double?
};
if (valueMetric.Value == null && reader.ValueType == typeof(long))
valueMetric.Value = reader.Value as long?;
// https://github.com/elastic/elasticsearch-net/issues/3311
// above code just checks for long through reader.ValueType, this is not always the case
if (valueMetric.Value != null || reader.TokenType == JsonToken.Null)
{
reader.Read();
if (reader.TokenType != JsonToken.EndObject)
{
if (reader.TokenType == JsonToken.PropertyName)
{
var propertyName = (string)reader.Value;
if (propertyName == Parser.ValueAsString)
{
valueMetric.ValueAsString = reader.ReadAsString();
reader.Read();
}
if (reader.TokenType == JsonToken.PropertyName)
{
propertyName = (string)reader.Value;
if (propertyName == Parser.Keys)
{
var keyedValueMetric = new KeyedValueAggregate
{
Value = valueMetric.Value
};
var keys = new List<string>();
reader.Read();
reader.Read();
while (reader.TokenType != JsonToken.EndArray)
{
keys.Add(reader.Value.ToString());
reader.Read();
}
reader.Read();
keyedValueMetric.Keys = keys;
return keyedValueMetric;
}
}
}
else
{
reader.Read();
reader.Read();
}
}
return valueMetric;
}
var scriptedMetric = reader.ReadTokenWithDateParseHandlingNone();
reader.Read();
if (scriptedMetric != null)
{
var s = serializer.GetConnectionSettings().SourceSerializer;
return new ScriptedMetricAggregate(new LazyDocument(scriptedMetric, s));
}
return valueMetric;
}
public IBucket GetRangeBucket(JsonReader reader, JsonSerializer serializer, string key = null)
{
string fromAsString = null, toAsString = null;
long? docCount = null;
double? toDouble = null, fromDouble = null;
var readExpectedProperty = true;
while (readExpectedProperty)
{
switch (reader.Value as string)
{
case Parser.From:
reader.Read();
if (reader.ValueType == typeof(double))
fromDouble = (double)reader.Value;
reader.Read();
break;
case Parser.To:
reader.Read();
if (reader.ValueType == typeof(double))
toDouble = (double)reader.Value;
reader.Read();
break;
case Parser.Key:
key = reader.ReadAsString();
reader.Read();
break;
case Parser.FromAsString:
fromAsString = reader.ReadAsString();
reader.Read();
break;
case Parser.ToAsString:
toAsString = reader.ReadAsString();
reader.Read();
break;
case Parser.DocCount:
reader.Read();
docCount = (reader.Value as long?).GetValueOrDefault(0);
reader.Read();
break;
default:
readExpectedProperty = false;
break;
}
}
var nestedAggregations = GetSubAggregates(reader, serializer);
var bucket = new RangeBucket(nestedAggregations)
{
Key = key,
From = fromDouble,
To = toDouble,
DocCount = docCount.GetValueOrDefault(),
FromAsString = fromAsString,
ToAsString = toAsString,
};
return bucket;
}
private IBucket GetDateHistogramBucket(JsonReader reader, JsonSerializer serializer)
{
var keyAsString = reader.ReadAsString();
reader.Read();
reader.Read();
var key = (reader.Value as long?).GetValueOrDefault(0);
reader.Read();
reader.Read();
var docCount = (reader.Value as long?).GetValueOrDefault(0);
reader.Read();
var nestedAggregations = GetSubAggregates(reader, serializer);
var dateHistogram = new DateHistogramBucket(nestedAggregations)
{
Key = key,
KeyAsString = keyAsString,
DocCount = docCount,
};
return dateHistogram;
}
private IBucket GetKeyedBucket(JsonReader reader, JsonSerializer serializer)
{
reader.Read();
if (reader.TokenType == JsonToken.StartObject)
return GetCompositeBucket(reader, serializer);
var key = reader.Value;
reader.Read();
var propertyName = (string)reader.Value;
if (propertyName == Parser.From || propertyName == Parser.To)
return GetRangeBucket(reader, serializer, key as string);
string keyAsString = null;
if (propertyName == Parser.KeyAsString)
{
keyAsString = reader.ReadAsString();
reader.Read();
}
reader.Read(); //doc_count;
var docCount = reader.Value as long?;
reader.Read();
var nextProperty = (string)reader.Value;
if (nextProperty == Parser.Score)
return GetSignificantTermsBucket(reader, serializer, key, keyAsString, docCount);
long? docCountErrorUpperBound = null;
if (nextProperty == Parser.DocCountErrorUpperBound)
{
reader.Read();
docCountErrorUpperBound = reader.Value as long?;
reader.Read();
}
var nestedAggregates = GetSubAggregates(reader, serializer);
var bucket = new KeyedBucket<object>(nestedAggregates)
{
Key = key,
KeyAsString = keyAsString,
DocCount = docCount.GetValueOrDefault(0),
DocCountErrorUpperBound = docCountErrorUpperBound
};
return bucket;
}
private IBucket GetCompositeBucket(JsonReader reader, JsonSerializer serializer)
{
var key = new CompositeKey(serializer.Deserialize<IReadOnlyDictionary<string, object>>(reader));
reader.Read();
long? docCount = null;
if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == Parser.DocCount)
{
reader.Read();
docCount = reader.Value as long?;
reader.Read();
}
var nestedAggregates = GetSubAggregates(reader, serializer);
return new CompositeBucket(nestedAggregates, key) { DocCount = docCount };
}
private IBucket GetSignificantTermsBucket(JsonReader reader, JsonSerializer serializer, object key, string keyAsString, long? docCount)
{
reader.Read();
var score = reader.Value as double?;
reader.Read();
reader.Read();
var bgCount = reader.Value as long?;
reader.Read();
var nestedAggregations = GetSubAggregates(reader, serializer);
var significantTermItem = new SignificantTermsBucket(nestedAggregations)
{
Key = key as string,
DocCount = docCount.GetValueOrDefault(0),
BgCount = bgCount.GetValueOrDefault(0),
Score = score.GetValueOrDefault(0)
};
return significantTermItem;
}
private IBucket GetFiltersBucket(JsonReader reader, JsonSerializer serializer)
{
reader.Read();
var docCount = (reader.Value as long?).GetValueOrDefault(0);
reader.Read();
var nestedAggregations = GetSubAggregates(reader, serializer);
var filtersBucketItem = new FiltersBucketItem(nestedAggregations)
{
DocCount = docCount
};
return filtersBucketItem;
}
private static class Parser
{
public const string AfterKey = "after_key";
public const string AsStringSuffix = "_as_string";
public const string BgCount = "bg_count";
public const string BottomRight = "bottom_right";
public const string Bounds = "bounds";
public const string Buckets = "buckets";
public const string Count = "count";
public const string DocCount = "doc_count";
public const string DocCountErrorUpperBound = "doc_count_error_upper_bound";
public const string Fields = "fields";
public const string From = "from";
public const string Interval = "interval";
public const string FromAsString = "from_as_string";
public const string Hits = "hits";
public const string Key = "key";
public const string KeyAsString = "key_as_string";
public const string Keys = "keys";
public const string Location = "location";
public const string Lower = "lower";
public const string MaxScore = "max_score";
public const string Meta = "meta";
public const string Score = "score";
public const string StdDeviationBoundsAsString = "std_deviation_bounds_as_string";
public const string SumOtherDocCount = "sum_other_doc_count";
public const string To = "to";
public const string ToAsString = "to_as_string";
public const string TopLeft = "top_left";
public const string Total = "total";
public const string Upper = "upper";
public const string Value = "value";
public const string ValueAsString = "value_as_string";
public const string Values = "values";
}
}
}
| 28.590909 | 137 | 0.68336 | [
"Apache-2.0"
] | Henr1k80/elasticsearch-net | src/Nest/Aggregations/AggregateJsonConverter.cs | 22,646 | 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 mturk-requester-2017-01-17.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.MTurk.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MTurk.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpdateQualificationType Request Marshaller
/// </summary>
public class UpdateQualificationTypeRequestMarshaller : IMarshaller<IRequest, UpdateQualificationTypeRequest> , 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((UpdateQualificationTypeRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(UpdateQualificationTypeRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.MTurk");
string target = "MTurkRequesterServiceV20170117.UpdateQualificationType";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-01-17";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAnswerKey())
{
context.Writer.WritePropertyName("AnswerKey");
context.Writer.Write(publicRequest.AnswerKey);
}
if(publicRequest.IsSetAutoGranted())
{
context.Writer.WritePropertyName("AutoGranted");
context.Writer.Write(publicRequest.AutoGranted);
}
if(publicRequest.IsSetAutoGrantedValue())
{
context.Writer.WritePropertyName("AutoGrantedValue");
context.Writer.Write(publicRequest.AutoGrantedValue);
}
if(publicRequest.IsSetDescription())
{
context.Writer.WritePropertyName("Description");
context.Writer.Write(publicRequest.Description);
}
if(publicRequest.IsSetQualificationTypeId())
{
context.Writer.WritePropertyName("QualificationTypeId");
context.Writer.Write(publicRequest.QualificationTypeId);
}
if(publicRequest.IsSetQualificationTypeStatus())
{
context.Writer.WritePropertyName("QualificationTypeStatus");
context.Writer.Write(publicRequest.QualificationTypeStatus);
}
if(publicRequest.IsSetRetryDelayInSeconds())
{
context.Writer.WritePropertyName("RetryDelayInSeconds");
context.Writer.Write(publicRequest.RetryDelayInSeconds);
}
if(publicRequest.IsSetTest())
{
context.Writer.WritePropertyName("Test");
context.Writer.Write(publicRequest.Test);
}
if(publicRequest.IsSetTestDurationInSeconds())
{
context.Writer.WritePropertyName("TestDurationInSeconds");
context.Writer.Write(publicRequest.TestDurationInSeconds);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static UpdateQualificationTypeRequestMarshaller _instance = new UpdateQualificationTypeRequestMarshaller();
internal static UpdateQualificationTypeRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static UpdateQualificationTypeRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.256579 | 161 | 0.600918 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/MTurk/Generated/Model/Internal/MarshallTransformations/UpdateQualificationTypeRequestMarshaller.cs | 5,663 | C# |
namespace DotNetInterceptTester.My_System.Xml.XmlDocument
{
public class InsertBefore_System_Xml_XmlDocument_System_Xml_XmlNode_System_Xml_XmlNode
{
public static bool _InsertBefore_System_Xml_XmlDocument_System_Xml_XmlNode_System_Xml_XmlNode( )
{
//Parameters
System.Xml.XmlNode newChild = null;
System.Xml.XmlNode refChild = null;
//ReturnType/Value
System.Xml.XmlNode returnVal_Real = null;
System.Xml.XmlNode returnVal_Intercepted = null;
//Exception
Exception exception_Real = null;
Exception exception_Intercepted = null;
InterceptionMaintenance.disableInterception( );
try
{
returnValue_Real = System.Xml.XmlDocument.InsertBefore(newChild,refChild);
}
catch( Exception e )
{
exception_Real = e;
}
InterceptionMaintenance.enableInterception( );
try
{
returnValue_Intercepted = System.Xml.XmlDocument.InsertBefore(newChild,refChild);
}
catch( Exception e )
{
exception_Intercepted = e;
}
Return ( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
}
}
}
| 24.040816 | 127 | 0.712224 | [
"MIT"
] | SecurityInnovation/Holodeck | Test/Automation/DotNetInterceptTester/DotNetInterceptTester/System.Xml.XmlDocument.InsertBefore(XmlNode, XmlNode).cs | 1,178 | C# |
using System;
using System.IO;
using System.Collections.Generic;
namespace Prism.Modularity
{
/// <summary>
/// Loads modules from an arbitrary location on the filesystem. This typeloader is only called if
/// <see cref="ModuleInfo"/> classes have a Ref parameter that starts with "file://".
/// This class is only used on the Desktop version of the Prism Library.
/// </summary>
public class FileModuleTypeLoader : IModuleTypeLoader, IDisposable
{
private const string RefFilePrefix = "file://";
private readonly IAssemblyResolver assemblyResolver;
private HashSet<Uri> downloadedUris = new HashSet<Uri>();
/// <summary>
/// Initializes a new instance of the <see cref="FileModuleTypeLoader"/> class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is disposed of in the Dispose method.")]
public FileModuleTypeLoader()
: this(new AssemblyResolver())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileModuleTypeLoader"/> class.
/// </summary>
/// <param name="assemblyResolver">The assembly resolver.</param>
public FileModuleTypeLoader(IAssemblyResolver assemblyResolver)
{
this.assemblyResolver = assemblyResolver;
}
/// <summary>
/// Raised repeatedly to provide progress as modules are loaded in the background.
/// </summary>
public event EventHandler<ModuleDownloadProgressChangedEventArgs> ModuleDownloadProgressChanged;
private void RaiseModuleDownloadProgressChanged(ModuleInfo moduleInfo, long bytesReceived, long totalBytesToReceive)
{
this.RaiseModuleDownloadProgressChanged(new ModuleDownloadProgressChangedEventArgs(moduleInfo, bytesReceived, totalBytesToReceive));
}
private void RaiseModuleDownloadProgressChanged(ModuleDownloadProgressChangedEventArgs e)
{
if (this.ModuleDownloadProgressChanged != null)
{
this.ModuleDownloadProgressChanged(this, e);
}
}
/// <summary>
/// Raised when a module is loaded or fails to load.
/// </summary>
public event EventHandler<LoadModuleCompletedEventArgs> LoadModuleCompleted;
private void RaiseLoadModuleCompleted(ModuleInfo moduleInfo, Exception error)
{
this.RaiseLoadModuleCompleted(new LoadModuleCompletedEventArgs(moduleInfo, error));
}
private void RaiseLoadModuleCompleted(LoadModuleCompletedEventArgs e)
{
if (this.LoadModuleCompleted != null)
{
this.LoadModuleCompleted(this, e);
}
}
/// <summary>
/// Evaluates the <see cref="ModuleInfo.Ref"/> property to see if the current typeloader will be able to retrieve the <paramref name="moduleInfo"/>.
/// Returns true if the <see cref="ModuleInfo.Ref"/> property starts with "file://", because this indicates that the file
/// is a local file.
/// </summary>
/// <param name="moduleInfo">Module that should have it's type loaded.</param>
/// <returns>
/// <see langword="true"/> if the current typeloader is able to retrieve the module, otherwise <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">An <see cref="ArgumentNullException"/> is thrown if <paramref name="moduleInfo"/> is null.</exception>
public bool CanLoadModuleType(ModuleInfo moduleInfo)
{
if (moduleInfo == null)
{
throw new System.ArgumentNullException("moduleInfo");
}
return moduleInfo.Ref != null && moduleInfo.Ref.StartsWith(RefFilePrefix, StringComparison.Ordinal);
}
/// <summary>
/// Retrieves the <paramref name="moduleInfo"/>.
/// </summary>
/// <param name="moduleInfo">Module that should have it's type loaded.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is rethrown as part of a completion event")]
public void LoadModuleType(ModuleInfo moduleInfo)
{
if (moduleInfo == null)
{
throw new System.ArgumentNullException("moduleInfo");
}
try
{
Uri uri = new Uri(moduleInfo.Ref, UriKind.RelativeOrAbsolute);
// If this module has already been downloaded, I fire the completed event.
if (this.IsSuccessfullyDownloaded(uri))
{
this.RaiseLoadModuleCompleted(moduleInfo, null);
}
else
{
string path;
if (moduleInfo.Ref.StartsWith(RefFilePrefix + "/", StringComparison.Ordinal))
{
path = moduleInfo.Ref.Substring(RefFilePrefix.Length + 1);
}
else
{
path = moduleInfo.Ref.Substring(RefFilePrefix.Length);
}
long fileSize = -1L;
if (File.Exists(path))
{
FileInfo fileInfo = new FileInfo(path);
fileSize = fileInfo.Length;
}
// Although this isn't asynchronous, nor expected to take very long, I raise progress changed for consistency.
this.RaiseModuleDownloadProgressChanged(moduleInfo, 0, fileSize);
this.assemblyResolver.LoadAssemblyFrom(moduleInfo.Ref);
// Although this isn't asynchronous, nor expected to take very long, I raise progress changed for consistency.
this.RaiseModuleDownloadProgressChanged(moduleInfo, fileSize, fileSize);
// I remember the downloaded URI.
this.RecordDownloadSuccess(uri);
this.RaiseLoadModuleCompleted(moduleInfo, null);
}
}
catch (Exception ex)
{
this.RaiseLoadModuleCompleted(moduleInfo, ex);
}
}
private bool IsSuccessfullyDownloaded(Uri uri)
{
lock (this.downloadedUris)
{
return this.downloadedUris.Contains(uri);
}
}
private void RecordDownloadSuccess(Uri uri)
{
lock (this.downloadedUris)
{
this.downloadedUris.Add(uri);
}
}
#region Implementation of IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <remarks>Calls <see cref="Dispose(bool)"/></remarks>.
/// <filterpriority>2</filterpriority>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the associated <see cref="AssemblyResolver"/>.
/// </summary>
/// <param name="disposing">When <see langword="true"/>, it is being called from the Dispose method.</param>
protected virtual void Dispose(bool disposing)
{
IDisposable disposableResolver = this.assemblyResolver as IDisposable;
if (disposableResolver != null)
{
disposableResolver.Dispose();
}
}
#endregion
}
}
| 38.841584 | 190 | 0.588708 | [
"Apache-2.0"
] | WertherHu/Prism | Source/Wpf/Prism.Wpf/Modularity/FileModuleTypeLoader.Desktop.cs | 7,846 | C# |
using System;
using System.Collections.Generic;
using System.IO.Abstractions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Urunium.Stitch.ModuleTransformers
{
public class DefaultModuleTransformer : IModuleTransformer
{
IFileSystem _fileSystem;
public DefaultModuleTransformer(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
public IEnumerable<string> Extensions => new[] { "*" };
public Module Transform(Module module)
{
string fullModulePath = module.FullPath;
string moduleId = module.ModuleId;
string content = module.TransformedContent ?? ReadFileContent(fullModulePath);
module.OriginalContent = module.OriginalContent ?? content;
module.TransformedContent = content;
return module;
}
private string ReadFileContent(string fullModulePath)
{
string content;
var binaryExtensions = ApacheMimeTypes.Apache.MimeTypes.Where(x => x.Value.StartsWith("image/")
|| x.Value.StartsWith("video/")
|| x.Value.StartsWith("audio/")
|| x.Value.StartsWith("application/x-font")).Select(x => "." + x.Key);
if (binaryExtensions.Contains(_fileSystem.Path.GetExtension(fullModulePath).ToLower()))
{
content = _fileSystem.File.ReadAllText(fullModulePath, Encoding.Default);
}
else
{
content = _fileSystem.File.ReadAllText(fullModulePath);
}
return content;
}
}
}
| 34.962264 | 148 | 0.549379 | [
"MIT"
] | urunium/Urunium.Stitch | src/Urunium.Stitch/ModuleTransformers/DefaultModuleTransformer.cs | 1,855 | C# |
// -----------------------------------------------------------------------
// <copyright file="NotificationController.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using Microsoft.Graph;
using System;
namespace MicrosoftGraph_Security_API_Sample.Models.DomainModels
{
public class SecurityActionResponse : SecurityActionBase
{
public string Id { get; set; }
public DateTimeOffset? SubmittedDateTime { get; set; }
public DateTimeOffset? StatusUpdateDateTime { get; set; }
public Microsoft.Graph.SecurityVendorInformation SecurityVendorInformation { get; set; }
public OperationStatus Status { get; set; }
}
} | 34.833333 | 97 | 0.574163 | [
"MIT"
] | Lauragra/aspnet-security-api-sample | V3.0/MicrosoftGraph_Security_API_Sample/Models/Responses/SecurityActionResponse.cs | 838 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
namespace Tasks
{
public class A
{
public static void Main(string[] args)
{
var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
Console.SetOut(sw);
Solve();
Console.Out.Flush();
}
public static void Solve()
{
var A = Scanner.Scan<int>();
var B = Scanner.Scan<int>();
var C = Scanner.Scan<int>();
var S = Scanner.Scan<int>();
var sum = A + B + C;
var answer = sum <= S && S <= sum + 3;
Console.WriteLine(answer ? "Yes" : "No");
}
public static class Scanner
{
private static Queue<string> queue = new Queue<string>();
public static T Next<T>()
{
if (!queue.Any()) foreach (var item in Console.ReadLine().Trim().Split(" ")) queue.Enqueue(item);
return (T)Convert.ChangeType(queue.Dequeue(), typeof(T));
}
public static T Scan<T>() => Next<T>();
public static (T1, T2) Scan<T1, T2>() => (Next<T1>(), Next<T2>());
public static (T1, T2, T3) Scan<T1, T2, T3>() => (Next<T1>(), Next<T2>(), Next<T3>());
public static (T1, T2, T3, T4) Scan<T1, T2, T3, T4>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>());
public static (T1, T2, T3, T4, T5) Scan<T1, T2, T3, T4, T5>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>());
public static (T1, T2, T3, T4, T5, T6) Scan<T1, T2, T3, T4, T5, T6>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>(), Next<T6>());
public static IEnumerable<T> ScanEnumerable<T>() => Console.ReadLine().Trim().Split(" ").Select(x => (T)Convert.ChangeType(x, typeof(T)));
}
}
}
| 39.34 | 158 | 0.50788 | [
"CC0-1.0"
] | AconCavy/AtCoder.Tasks.CS | Other/CODE-FESTIVAL-2018-QUALA/Tasks/A.cs | 1,967 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace BeerApp.Areas.HelpPage.ModelDescriptions
{
public class ParameterDescription
{
public ParameterDescription()
{
Annotations = new Collection<ParameterAnnotation>();
}
public Collection<ParameterAnnotation> Annotations { get; private set; }
public string Documentation { get; set; }
public string Name { get; set; }
public ModelDescription TypeDescription { get; set; }
}
} | 25.619048 | 80 | 0.674721 | [
"Unlicense"
] | Saturnno/BeerAppApi | BeerApp/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs | 538 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityCollectionRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
/// <summary>
/// The type GraphServiceGroupSettingTemplatesCollectionRequestBuilder.
/// </summary>
public partial class GraphServiceGroupSettingTemplatesCollectionRequestBuilder : BaseRequestBuilder, IGraphServiceGroupSettingTemplatesCollectionRequestBuilder
{
/// <summary>
/// Constructs a new GraphServiceGroupSettingTemplatesCollectionRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public GraphServiceGroupSettingTemplatesCollectionRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public IGraphServiceGroupSettingTemplatesCollectionRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public IGraphServiceGroupSettingTemplatesCollectionRequest Request(IEnumerable<Option> options)
{
return new GraphServiceGroupSettingTemplatesCollectionRequest(this.RequestUrl, this.Client, options);
}
/// <summary>
/// Gets an <see cref="IGroupSettingTemplateRequestBuilder"/> for the specified GraphServiceGroupSettingTemplate.
/// </summary>
/// <param name="id">The ID for the GraphServiceGroupSettingTemplate.</param>
/// <returns>The <see cref="IGroupSettingTemplateRequestBuilder"/>.</returns>
public IGroupSettingTemplateRequestBuilder this[string id]
{
get
{
return new GroupSettingTemplateRequestBuilder(this.AppendSegmentToRequestUrl(id), this.Client);
}
}
}
}
| 40.409091 | 163 | 0.618298 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/GraphServiceGroupSettingTemplatesCollectionRequestBuilder.cs | 2,667 | C# |
#region
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinterLeaf.Engine;
using WinterLeaf.Engine.Classes;
using WinterLeaf.Engine.Containers;
using WinterLeaf.Engine.Enums;
using System.ComponentModel;
using System.Threading;
using WinterLeaf.Engine.Classes.Interopt;
using WinterLeaf.Engine.Classes.Decorations;
using WinterLeaf.Engine.Classes.Extensions;
using WinterLeaf.Engine.Classes.Helpers;
using Winterleaf.Demo.Full.Dedicated.Models.User.Extendable;
#endregion
namespace Winterleaf.Demo.Full.Dedicated.Models.Base
{
/// <summary>
///
/// </summary>
[TypeConverter(typeof(TypeConverterGeneric<GroundCover_Base>))]
public partial class GroundCover_Base: SceneObject
{
#region ProxyObjects Operator Overrides
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator ==(GroundCover_Base ts, string simobjectid)
{
return object.ReferenceEquals(ts, null) ? object.ReferenceEquals(simobjectid, null) : ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (this._ID ==(string)myReflections.ChangeType( obj,typeof(string)));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator !=(GroundCover_Base ts, string simobjectid)
{
if (object.ReferenceEquals(ts, null))
return !object.ReferenceEquals(simobjectid, null);
return !ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator string( GroundCover_Base ts)
{
if (object.ReferenceEquals(ts, null))
return "0";
return ts._ID;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator GroundCover_Base(string ts)
{
uint simobjectid = resolveobject(ts);
return (GroundCover_Base) Omni.self.getSimObject(simobjectid,typeof(GroundCover_Base));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator int( GroundCover_Base ts)
{
return (int)ts._iID;
}
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static implicit operator GroundCover_Base(int simobjectid)
{
return (GroundCover) Omni.self.getSimObject((uint)simobjectid,typeof(GroundCover_Base));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator uint( GroundCover_Base ts)
{
return ts._iID;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static implicit operator GroundCover_Base(uint simobjectid)
{
return (GroundCover_Base) Omni.self.getSimObject(simobjectid,typeof(GroundCover_Base));
}
#endregion
#region Init Persists
[MemberGroup("GroundCover General")]
public arrayObject<RectF> billboardUVs;
[MemberGroup("GroundCover General")]
public arrayObject<float> clumpExponent;
[MemberGroup("GroundCover General")]
public arrayObject<float> clumpRadius;
/// <summary>
/// This is less than or equal to radius and defines when fading of cover elements begins.
/// </summary>
[MemberGroup("GroundCover General")]
public float dissolveRadius
{
get
{
return Omni.self.GetVar(_ID + ".dissolveRadius").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".dissolveRadius", value.AsString());
}
}
/// <summary>
/// The number of cells per axis in the grid.
/// </summary>
[MemberGroup("GroundCover General")]
public int gridSize
{
get
{
return Omni.self.GetVar(_ID + ".gridSize").AsInt();
}
set
{
Omni.self.SetVar(_ID + ".gridSize", value.AsString());
}
}
[MemberGroup("GroundCover General")]
public arrayObject<bool> invertLayer;
[MemberGroup("GroundCover General")]
public arrayObject<TypeTerrainMaterialName> layer;
/// <summary>
/// Debug parameter for locking the culling frustum which will freeze the cover generation.
/// </summary>
[MemberGroup("GroundCover Debug")]
public bool lockFrustum
{
get
{
return Omni.self.GetVar(_ID + ".lockFrustum").AsBool();
}
set
{
Omni.self.SetVar(_ID + ".lockFrustum", value.AsString());
}
}
/// <summary>
/// Material used by all GroundCover segments.
/// </summary>
[MemberGroup("GroundCover General")]
public TypeMaterialName material
{
get
{
return Omni.self.GetVar(_ID + ".material").AsTypeMaterialName();
}
set
{
Omni.self.SetVar(_ID + ".material", value.AsString());
}
}
/// <summary>
/// The maximum amout of degrees the billboard will tilt down to match the camera.
/// </summary>
[MemberGroup("GroundCover General")]
public float maxBillboardTiltAngle
{
get
{
return Omni.self.GetVar(_ID + ".maxBillboardTiltAngle").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".maxBillboardTiltAngle", value.AsString());
}
}
[MemberGroup("GroundCover General")]
public arrayObject<int> maxClumpCount;
/// <summary>
/// The maximum amount of cover elements to include in the grid at any one time.
/// </summary>
[MemberGroup("GroundCover General")]
public int maxElements
{
get
{
return Omni.self.GetVar(_ID + ".maxElements").AsInt();
}
set
{
Omni.self.SetVar(_ID + ".maxElements", value.AsString());
}
}
[MemberGroup("GroundCover General")]
public arrayObject<float> maxElevation;
[MemberGroup("GroundCover General")]
public arrayObject<float> maxSlope;
[MemberGroup("GroundCover General")]
public arrayObject<int> minClumpCount;
[MemberGroup("GroundCover General")]
public arrayObject<float> minElevation;
/// <summary>
/// Debug parameter for turning off billboard rendering.
/// </summary>
[MemberGroup("GroundCover Debug")]
public bool noBillboards
{
get
{
return Omni.self.GetVar(_ID + ".noBillboards").AsBool();
}
set
{
Omni.self.SetVar(_ID + ".noBillboards", value.AsString());
}
}
/// <summary>
/// Debug parameter for turning off shape rendering.
/// </summary>
[MemberGroup("GroundCover Debug")]
public bool noShapes
{
get
{
return Omni.self.GetVar(_ID + ".noShapes").AsBool();
}
set
{
Omni.self.SetVar(_ID + ".noShapes", value.AsString());
}
}
[MemberGroup("GroundCover General")]
public arrayObject<float> probability;
/// <summary>
/// Outer generation radius from the current camera position.
/// </summary>
[MemberGroup("GroundCover General")]
public float radius
{
get
{
return Omni.self.GetVar(_ID + ".radius").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".radius", value.AsString());
}
}
/// <summary>
/// Scales the various culling radii when rendering a reflection. Typically for water.
/// </summary>
[MemberGroup("GroundCover General")]
public float reflectScale
{
get
{
return Omni.self.GetVar(_ID + ".reflectScale").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".reflectScale", value.AsString());
}
}
/// <summary>
/// Debug parameter for displaying the grid cells.
/// </summary>
[MemberGroup("GroundCover Debug")]
public bool renderCells
{
get
{
return Omni.self.GetVar(_ID + ".renderCells").AsBool();
}
set
{
Omni.self.SetVar(_ID + ".renderCells", value.AsString());
}
}
/// <summary>
/// This RNG seed is saved and sent to clients for generating the same cover.
/// </summary>
[MemberGroup("GroundCover General")]
public int seed
{
get
{
return Omni.self.GetVar(_ID + ".seed").AsInt();
}
set
{
Omni.self.SetVar(_ID + ".seed", value.AsString());
}
}
/// <summary>
/// This is the distance at which DTS elements are completely culled out.
/// </summary>
[MemberGroup("GroundCover General")]
public float shapeCullRadius
{
get
{
return Omni.self.GetVar(_ID + ".shapeCullRadius").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".shapeCullRadius", value.AsString());
}
}
[MemberGroup("GroundCover General")]
public arrayObject<String> shapeFilename;
/// <summary>
/// Whether DTS elements should cast shadows or not.
/// </summary>
[MemberGroup("GroundCover General")]
public bool shapesCastShadows
{
get
{
return Omni.self.GetVar(_ID + ".shapesCastShadows").AsBool();
}
set
{
Omni.self.SetVar(_ID + ".shapesCastShadows", value.AsString());
}
}
[MemberGroup("GroundCover General")]
public arrayObject<float> sizeExponent;
[MemberGroup("GroundCover General")]
public arrayObject<float> sizeMax;
[MemberGroup("GroundCover General")]
public arrayObject<float> sizeMin;
/// <summary>
/// The direction of the wind.
/// </summary>
[MemberGroup("GroundCover Wind")]
public Point2F windDirection
{
get
{
return Omni.self.GetVar(_ID + ".windDirection").AsPoint2F();
}
set
{
Omni.self.SetVar(_ID + ".windDirection", value.AsString());
}
}
/// <summary>
/// Controls how often the wind gust peaks per second.
/// </summary>
[MemberGroup("GroundCover Wind")]
public float windGustFrequency
{
get
{
return Omni.self.GetVar(_ID + ".windGustFrequency").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".windGustFrequency", value.AsString());
}
}
/// <summary>
/// The length in meters between peaks in the wind gust.
/// </summary>
[MemberGroup("GroundCover Wind")]
public float windGustLength
{
get
{
return Omni.self.GetVar(_ID + ".windGustLength").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".windGustLength", value.AsString());
}
}
/// <summary>
/// The maximum distance in meters that the peak wind gust will displace an element.
/// </summary>
[MemberGroup("GroundCover Wind")]
public float windGustStrength
{
get
{
return Omni.self.GetVar(_ID + ".windGustStrength").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".windGustStrength", value.AsString());
}
}
[MemberGroup("GroundCover General")]
public arrayObject<float> windScale;
/// <summary>
/// Controls the overall rapidity of the wind turbulence.
/// </summary>
[MemberGroup("GroundCover Wind")]
public float windTurbulenceFrequency
{
get
{
return Omni.self.GetVar(_ID + ".windTurbulenceFrequency").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".windTurbulenceFrequency", value.AsString());
}
}
/// <summary>
/// The maximum distance in meters that the turbulence can displace a ground cover element.
/// </summary>
[MemberGroup("GroundCover Wind")]
public float windTurbulenceStrength
{
get
{
return Omni.self.GetVar(_ID + ".windTurbulenceStrength").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".windTurbulenceStrength", value.AsString());
}
}
/// <summary>
/// Offset along the Z axis to render the ground cover.
/// </summary>
[MemberGroup("GroundCover General")]
public float zOffset
{
get
{
return Omni.self.GetVar(_ID + ".zOffset").AsFloat();
}
set
{
Omni.self.SetVar(_ID + ".zOffset", value.AsString());
}
}
#endregion
#region Member Functions
#endregion
#region T3D Callbacks
#endregion
public GroundCover_Base (){billboardUVs = new arrayObject<RectF>(8,"billboardUVs","TypeVariable",false,this);
clumpExponent = new arrayObject<float>(8,"clumpExponent","TypeVariable",false,this);
clumpRadius = new arrayObject<float>(8,"clumpRadius","TypeVariable",false,this);
invertLayer = new arrayObject<bool>(8,"invertLayer","TypeVariable",false,this);
layer = new arrayObject<TypeTerrainMaterialName>(8,"layer","TypeVariable",false,this);
maxClumpCount = new arrayObject<int>(8,"maxClumpCount","TypeVariable",false,this);
maxElevation = new arrayObject<float>(8,"maxElevation","TypeVariable",false,this);
maxSlope = new arrayObject<float>(8,"maxSlope","TypeVariable",false,this);
minClumpCount = new arrayObject<int>(8,"minClumpCount","TypeVariable",false,this);
minElevation = new arrayObject<float>(8,"minElevation","TypeVariable",false,this);
probability = new arrayObject<float>(8,"probability","TypeVariable",false,this);
shapeFilename = new arrayObject<String>(8,"shapeFilename","TypeVariable",false,this);
sizeExponent = new arrayObject<float>(8,"sizeExponent","TypeVariable",false,this);
sizeMax = new arrayObject<float>(8,"sizeMax","TypeVariable",false,this);
sizeMin = new arrayObject<float>(8,"sizeMin","TypeVariable",false,this);
windScale = new arrayObject<float>(8,"windScale","TypeVariable",false,this);
}
}}
| 29.947266 | 122 | 0.566295 | [
"MIT",
"Unlicense"
] | RichardRanft/OmniEngine.Net | Templates/C#-Full-Ded/WinterLeaf.Demo.Full.Dedicated/Models.Base/GroundCover_Base.cs | 14,822 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using HoloToolkit.Unity.InputModule;
public class ButtonAppearance : MonoBehaviour, IFocusable {
// Use this for initialization
public Sprite hoverSprite;
public Sprite defaultSprite;
public Sprite activeSprite;
public Sprite disabledSprite;
public bool oneButtonActiveInGroup = false;
public bool resetOnSecondClick = false;
public bool defaultActive = false;
private bool buttonDisabled = false;
private SpriteRenderer renderer;
private Image image;
private bool activeState;
private AudioSource hoverSound;
void Awake()
{
renderer = GetComponent<SpriteRenderer>();
if (renderer == null)
{
image = GetComponent<Image>();
if(image == null)
{
Debug.Log("no sprite renderer or Image on button where expected");
}
} else
{
if (defaultActive)
{
changeSprite(activeSprite);
}
else
{
ResetButton();
}
}
activeState = defaultActive;
hoverSound = GameObject.Find("menu_current").GetComponent<AudioSource>();
}
void OnDisable()
{
if(!defaultActive)
{
activeState = false;
changeSprite(defaultSprite);
} else
{
activeState = true;
changeSprite(activeSprite);
}
}
public void setActiveDefault(bool def)
{
defaultActive = def;
}
public void SetButtonHover()
{
if(!buttonDisabled)
{
changeSprite(hoverSprite);
}
}
public void SetButtonActive()
{
if(!buttonDisabled) {
//reset all other buttons in the group
if(oneButtonActiveInGroup)
{
foreach(Transform t in transform.parent)
{
if (t.gameObject.GetInstanceID() != gameObject.GetInstanceID())
{
ButtonAppearance b = t.GetComponent<ButtonAppearance>();
if(b != null)
{
b.ResetButton();
}
}
}
}
//"unpress" the button
if (activeState && resetOnSecondClick)
{
Debug.Log("resetting button: " + activeState + " " + resetOnSecondClick);
ResetButton();
}
else
{
Debug.Log("setting button Active");
changeSprite(activeSprite);
activeState = true;
}
}
}
public void SetButtonDisabled()
{
buttonDisabled = true;
changeSprite(disabledSprite);
}
public void SetButtonEnabled()
{
buttonDisabled = false;
changeSprite(defaultSprite);
}
public void ToggleButtonActive()
{
if(!buttonDisabled)
{
if (activeState == false)
{
SetButtonActive();
}
else
{
ResetButton();
}
}
}
public void ResetButton()
{
if(!buttonDisabled)
{
changeSprite(defaultSprite);
activeState = false;
}
}
public void OnFocusEnter()
{
if(!buttonDisabled)
{
if (activeState)
{
return;
}
hoverSound.Play();
SetButtonHover();
}
}
public void OnFocusExit()
{
if(!buttonDisabled)
{
if (activeState)
{
return;
}
ResetButton();
}
}
private void changeSprite(Sprite sprite)
{
if (renderer != null)
{
renderer.sprite = sprite;
}
else if (image != null)
{
image.sprite = sprite;
}
}
}
| 24.088398 | 90 | 0.460321 | [
"MIT"
] | UBCHiveLab/SpectatorBrain | UnityProject/Assets/Scripts/ButtonAppearance.cs | 4,362 | C# |
/*
* Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace Minio.DataModel
{
// Arn holds ARN information that will be sent to the web service,
// ARN desciption can be found in http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
public class Arn
{
private string Partition { get; }
private string Service { get; }
private string Region { get; }
private string AccountID { get; }
private string Resource { get; }
[XmlText]
private string arnString;
public Arn()
{
}
// Pass valid Arn string on aws to constructor
public Arn(string arnString)
{
string[] parts = arnString.Split(':');
if (parts.Length == 6)
{
this.Partition = parts[1];
this.Service = parts[2];
this.Region = parts[3];
this.AccountID = parts[4];
this.Resource = parts[5];
this.arnString = arnString;
}
}
// constructs new ARN based on the given partition, service, region, account id and resource
public Arn(string partition, string service, string region, string accountId, string resource)
{
this.Partition = partition;
this.Service = service;
this.Region = region;
this.AccountID = accountId;
this.Resource = resource;
this.arnString = "arn:" + this.Partition + ":" + this.Service + ":" + this.Region + ":" + this.AccountID + ":" + this.Resource;
}
public override string ToString()
{
return arnString;
}
}
} | 34.414286 | 139 | 0.60191 | [
"Apache-2.0"
] | MarcosBidtellect/minio-dotnet | Minio/DataModel/Notification/Arn.cs | 2,409 | 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 codedeploy-2014-10-06.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.CodeDeploy
{
/// <summary>
/// Configuration for accessing Amazon CodeDeploy service
/// </summary>
public partial class AmazonCodeDeployConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.101.76");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonCodeDeployConfig()
{
this.AuthenticationServiceName = "codedeploy";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "codedeploy";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2014-10-06";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.3 | 108 | 0.589829 | [
"Apache-2.0"
] | TallyUpTeam/aws-sdk-net | sdk/src/Services/CodeDeploy/Generated/AmazonCodeDeployConfig.cs | 2,104 | C# |
using System;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Linq;
using Orleans;
using TestGrainInterfaces;
using Xunit;
using Assert = Xunit.Assert;
using TestExtensions;
using Xunit.Abstractions;
using Orleans.Runtime;
using System.Collections.Generic;
using Xunit.Sdk;
namespace Tester.EventSourcingTests
{
[TestCaseOrderer("Tester.EventSourcingTests.SimplePriorityOrderer", "Tester")]
public partial class CountersGrainTests
{
// you can look at the time taken by each of the tests below
// to get a rough idea on how the synchronization choices, and the configuration parameters,
// and the consistency provider, affect throughput
// To run these perf tests from within visual studio, first type
// "CountersGrainTests.Perf" in the search box, and then "Run All"
// This will run the warmup and then all tests, in the same test cluster. Afterwards it reports
// approximate time taken for each. It's not really a test, just an
// illustration of how JournaledGrain performance can vary with the choices made.
// what you should see is:
// - the conservative approach (confirm each update, disallow reentrancy) is slow.
// - confirming at end only, instead of after each update, is fast.
// - allowing reentrancy, while still confirming after each update, is also fast.
private int iterations = 800;
[Fact, RunThisFirst, TestCategory("EventSourcing")]
public Task Perf_Warmup()
{
// call reset on each grain to ensure everything is loaded and primed
return Task.WhenAll(
GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_StateStore_NonReentrant").Reset(true),
GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_StateStore_Reentrant").Reset(true),
GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_LogStore_NonReentrant").Reset(true),
GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_LogStore_Reentrant").Reset(true)
);
}
[Fact, TestCategory("EventSourcing")]
public async Task Perf_ConfirmEachUpdate_MemoryStateStore_NonReentrant()
{
var grain = GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_StateStore_NonReentrant");
await ConcurrentIncrements(grain, iterations, true);
}
[Fact, TestCategory("EventSourcing")]
public async Task Perf_ConfirmAtEndOnly_MemoryStateStore_NonReentrant()
{
var grain = GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_StateStore_NonReentrant");
await ConcurrentIncrements(grain, iterations, false);
}
[Fact, TestCategory("EventSourcing")]
public async Task Perf_ConfirmEachUpdate_MemoryLogStore_NonReentrant()
{
var grain = GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_LogStore_NonReentrant");
await ConcurrentIncrements(grain, iterations, true);
}
[Fact, TestCategory("EventSourcing")]
public async Task Perf_ConfirmAtEndOnly_MemoryLogStore_NonReentrant()
{
var grain = GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_LogStore_NonReentrant");
await ConcurrentIncrements(grain, iterations, false);
}
[Fact, TestCategory("EventSourcing")]
public async Task Perf_ConfirmEachUpdate_MemoryStateStore_Reentrant()
{
var grain = GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_StateStore_Reentrant");
await ConcurrentIncrements(grain, iterations, true);
}
[Fact, TestCategory("EventSourcing")]
public async Task Perf_ConfirmAtEndOnly_MemoryStateStore_Reentrant()
{
var grain = GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_StateStore_Reentrant");
await ConcurrentIncrements(grain, iterations, false);
}
[Fact, TestCategory("EventSourcing")]
public async Task Perf_ConfirmEachUpdate_MemoryLogStore_Reentrant()
{
var grain = GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_LogStore_Reentrant");
await ConcurrentIncrements(grain, iterations, true);
}
[Fact, TestCategory("EventSourcing")]
public async Task Perf_ConfirmAtEndOnly_MemoryLogStore_Reentrant()
{
var grain = GrainClient.GrainFactory.GetGrain<ICountersGrain>(0, "TestGrains.CountersGrain_LogStore_Reentrant");
await ConcurrentIncrements(grain, iterations, false);
}
}
class RunThisFirstAttribute : Attribute
{
}
public class SimplePriorityOrderer : ITestCaseOrderer
{
private string attrname = typeof(RunThisFirstAttribute).AssemblyQualifiedName;
private bool HasRunThisFirstAttribute(ITestCase testcase)
{
return testcase.TestMethod.Method.GetCustomAttributes(attrname).Count() > 0;
}
public IEnumerable<TTestCase> OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases) where TTestCase : ITestCase
{
// return all tests with RunThisFirst attribute
foreach (var tc in testCases.Where(tc => HasRunThisFirstAttribute(tc)))
yield return tc;
// return all other tests
foreach (var tc in testCases.Where(tc => !HasRunThisFirstAttribute(tc)))
yield return tc;
}
}
} | 45.748031 | 133 | 0.695181 | [
"MIT"
] | OrleansContrib/Orleans.Indexing-1.5 | test/Tester/EventSourcingTests/CountersGrainPerfTests.cs | 5,812 | C# |
/* Copyright 2010-2016 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Reflection;
using MongoDB.Bson.Serialization.Serializers;
namespace MongoDB.Bson.Serialization
{
/// <summary>
/// Provides serializers for primitive types.
/// </summary>
public class PrimitiveSerializationProvider : BsonSerializationProviderBase
{
private static readonly Dictionary<Type, Type> __serializersTypes;
static PrimitiveSerializationProvider()
{
__serializersTypes = new Dictionary<Type, Type>
{
{ typeof(Boolean), typeof(BooleanSerializer) },
{ typeof(Byte), typeof(ByteSerializer) },
{ typeof(Byte[]), typeof(ByteArraySerializer) },
{ typeof(Char), typeof(CharSerializer) },
{ typeof(CultureInfo), typeof(CultureInfoSerializer) },
{ typeof(DateTime), typeof(DateTimeSerializer) },
{ typeof(DateTimeOffset), typeof(DateTimeOffsetSerializer) },
{ typeof(Decimal), typeof(DecimalSerializer) },
{ typeof(Double), typeof(DoubleSerializer) },
{ typeof(Guid), typeof(GuidSerializer) },
{ typeof(Int16), typeof(Int16Serializer) },
{ typeof(Int32), typeof(Int32Serializer) },
{ typeof(Int64), typeof(Int64Serializer) },
{ typeof(IPAddress), typeof(IPAddressSerializer) },
{ typeof(IPEndPoint), typeof(IPEndPointSerializer) },
{ typeof(KeyValuePair<,>), typeof(KeyValuePairSerializer<,>) },
{ typeof(Nullable<>), typeof(NullableSerializer<>) },
{ typeof(Object), typeof(ObjectSerializer) },
{ typeof(ObjectId), typeof(ObjectIdSerializer) },
{ typeof(SByte), typeof(SByteSerializer) },
{ typeof(Single), typeof(SingleSerializer) },
{ typeof(String), typeof(StringSerializer) },
{ typeof(TimeSpan), typeof(TimeSpanSerializer) },
{ typeof(Tuple<>), typeof(TupleSerializer<>) },
{ typeof(Tuple<,>), typeof(TupleSerializer<,>) },
{ typeof(Tuple<,,>), typeof(TupleSerializer<,,>) },
{ typeof(Tuple<,,,>), typeof(TupleSerializer<,,,>) },
{ typeof(Tuple<,,,,>), typeof(TupleSerializer<,,,,>) },
{ typeof(Tuple<,,,,,>), typeof(TupleSerializer<,,,,,>) },
{ typeof(Tuple<,,,,,,>), typeof(TupleSerializer<,,,,,,>) },
{ typeof(Tuple<,,,,,,,>), typeof(TupleSerializer<,,,,,,,>) },
{ typeof(UInt16), typeof(UInt16Serializer) },
{ typeof(UInt32), typeof(UInt32Serializer) },
{ typeof(UInt64), typeof(UInt64Serializer) },
{ typeof(Uri), typeof(UriSerializer) },
{ typeof(Version), typeof(VersionSerializer) }
};
}
/// <inheritdoc/>
public override IBsonSerializer GetSerializer(Type type, IBsonSerializerRegistry serializerRegistry)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericType && typeInfo.ContainsGenericParameters)
{
var message = string.Format("Generic type {0} has unassigned type parameters.", BsonUtils.GetFriendlyTypeName(type));
throw new ArgumentException(message, "type");
}
Type serializerType;
if (__serializersTypes.TryGetValue(type, out serializerType))
{
return CreateSerializer(serializerType, serializerRegistry);
}
if (typeInfo.IsGenericType && !typeInfo.ContainsGenericParameters)
{
Type serializerTypeDefinition;
if (__serializersTypes.TryGetValue(type.GetGenericTypeDefinition(), out serializerTypeDefinition))
{
return CreateGenericSerializer(serializerTypeDefinition, type.GetTypeInfo().GetGenericArguments(), serializerRegistry);
}
}
if (typeInfo.IsEnum)
{
return CreateGenericSerializer(typeof(EnumSerializer<>), new[] { type }, serializerRegistry);
}
return null;
}
}
} | 45.017857 | 139 | 0.590639 | [
"Apache-2.0"
] | joeenzminger/mongo-csharp-driver | src/MongoDB.Bson/Serialization/PrimitiveSerializationProvider.cs | 5,044 | C# |
/*****************************************************************************
* Copyright 2016 Aurora Solutions
*
* http://www.aurorasolutions.io
*
* Aurora Solutions is an innovative services and product company at
* the forefront of the software industry, with processes and practices
* involving Domain Driven Design(DDD), Agile methodologies to build
* scalable, secure, reliable and high performance products.
*
* TradeSharp is a C# based data feed and broker neutral Algorithmic
* Trading Platform that lets trading firms or individuals automate
* any rules based trading strategies in stocks, forex and ETFs.
* TradeSharp allows users to connect to providers like Tradier Brokerage,
* IQFeed, FXCM, Blackwood, Forexware, Integral, HotSpot, Currenex,
* Interactive Brokers and more.
* Key features: Place and Manage Orders, Risk Management,
* Generate Customized Reports etc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace TradeHub.TradeManager.Server.WindowsService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new TradeManagerService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
| 36.152542 | 79 | 0.658228 | [
"Apache-2.0"
] | TradeNexus/tradesharp-core | Backend/TradeManager/TradeHub.TradeManager.Server.WindowsService/Program.cs | 2,135 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ToolsApp.Web
{
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>();
});
}
}
| 23.851852 | 66 | 0.694099 | [
"MIT"
] | t4d-classes/blazor-server_08022021 | ToolsApp/ToolsApp.Web/Program.cs | 644 | 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 storagegateway-2013-06-30.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.StorageGateway.Model
{
/// <summary>
/// JoinDomainOutput
/// </summary>
public partial class JoinDomainResponse : AmazonWebServiceResponse
{
private ActiveDirectoryStatus _activeDirectoryStatus;
private string _gatewayARN;
/// <summary>
/// Gets and sets the property ActiveDirectoryStatus.
/// <para>
/// Indicates the status of the gateway as a member of the Active Directory domain.
/// </para>
/// <ul> <li>
/// <para>
/// <code>ACCESS_DENIED</code>: Indicates that the <code>JoinDomain</code> operation
/// failed due to an authentication error.
/// </para>
/// </li> <li>
/// <para>
/// <code>DETACHED</code>: Indicates that gateway is not joined to a domain.
/// </para>
/// </li> <li>
/// <para>
/// <code>JOINED</code>: Indicates that the gateway has successfully joined a domain.
/// </para>
/// </li> <li>
/// <para>
/// <code>JOINING</code>: Indicates that a <code>JoinDomain</code> operation is in progress.
/// </para>
/// </li> <li>
/// <para>
/// <code>NETWORK_ERROR</code>: Indicates that <code>JoinDomain</code> operation failed
/// due to a network or connectivity error.
/// </para>
/// </li> <li>
/// <para>
/// <code>TIMEOUT</code>: Indicates that the <code>JoinDomain</code> operation failed
/// because the operation didn't complete within the allotted time.
/// </para>
/// </li> <li>
/// <para>
/// <code>UNKNOWN_ERROR</code>: Indicates that the <code>JoinDomain</code> operation
/// failed due to another type of error.
/// </para>
/// </li> </ul>
/// </summary>
public ActiveDirectoryStatus ActiveDirectoryStatus
{
get { return this._activeDirectoryStatus; }
set { this._activeDirectoryStatus = value; }
}
// Check to see if ActiveDirectoryStatus property is set
internal bool IsSetActiveDirectoryStatus()
{
return this._activeDirectoryStatus != null;
}
/// <summary>
/// Gets and sets the property GatewayARN.
/// <para>
/// The unique Amazon Resource Name (ARN) of the gateway that joined the domain.
/// </para>
/// </summary>
[AWSProperty(Min=50, Max=500)]
public string GatewayARN
{
get { return this._gatewayARN; }
set { this._gatewayARN = value; }
}
// Check to see if GatewayARN property is set
internal bool IsSetGatewayARN()
{
return this._gatewayARN != null;
}
}
} | 33.909091 | 112 | 0.590617 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/StorageGateway/Generated/Model/JoinDomainResponse.cs | 3,730 | C# |
using System;
using Moq;
namespace Sample.CSharp
{
public class Class1
{
public void Test()
{
var mock = Mock.Of<CalculatorBase, ICustomFormatter, IDisposable>();
mock.Setup(m => m.Memory.Recall()).Returns(1);
var foo = Mock.Of<IFoo>();
var bar = Mock.Of<IBar>();
var value = "foo";
foo.Id
.Callback(() => value = "before")
.Returns(() => value)
.Callback(() => value = "after")
.Returns(() => value);
Console.WriteLine(foo.Id);
Console.WriteLine(foo.Id);
}
public void Test1()
{
var fake = Mock.Of<ICalculator>();
fake.Memory.Recall().Returns(5);
}
public void Test2()
{
var fake = Mock.Of<ICalculator>();
fake.Memory.Recall().Returns(5);
}
}
}
public interface IBar
{
void DoBar();
}
public interface IFoo
{
void Do(bool donow);
string Id { get; }
string Title { get; set; }
} | 19.642857 | 80 | 0.475455 | [
"MIT"
] | AzureMentor/moq | src/Samples/Moq.CSharp/Class1.cs | 1,102 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Avdm.Config;
using Avdm.Core;
using Quartz;
namespace Avdm.Scheduler.Core
{
public class NodeScheduler : INodeScheduler
{
private static readonly IScheduler g_scheduler;
static NodeScheduler()
{
var properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = ConfigManager.AppSettings["Scheduler.InstanceName"];
properties["quartz.scheduler.instanceId"] = Environment.MachineName + DateTime.UtcNow.Ticks;
properties["quartz.jobStore.type"] = "Quartz.Impl.MongoDB.JobStore, Quartz.Impl.MongoDB";
//TODO Quartz.Impl.MongoDB.JobStore.DefaultConnectionString = ConfigManager.AppSettings["Scheduler.ConnectionString"];
g_scheduler = new Quartz.Impl.StdSchedulerFactory( properties ).GetScheduler();
g_scheduler.Start();
}
public void AddOrReplaceCommandMessageJob(
string jobId,
string description,
string jobToRun,
string runOnMachineName,
MissedTriggerAction missedTriggerAction,
PreviousJobRunningAction previousJobRunningAction,
DateTime startTime,
IEnumerable<INodeTrigger> triggers )
{
Preconditions.CheckNotBlank( jobId, "jobId" );
Preconditions.CheckNotBlank( description, "description" );
Preconditions.CheckNotBlank( jobToRun, "jobToRun" );
Preconditions.CheckNotBlank( runOnMachineName, "runOnMachineName" );
Preconditions.CheckNotNull( triggers, "triggers" );
Preconditions.CheckNotBlank( jobId, "jobId" );
Preconditions.CheckNotBlank( jobId, "jobId" );
Preconditions.CheckNotBlank( jobId, "jobId" );
var job = JobBuilder.Create<NodeScheduledCommandSender>()
.WithIdentity( "job_" + jobId, "defaultGroup" )
.UsingJobData( "#missedTriggerAction", missedTriggerAction.ToString() )
.UsingJobData( "#previousJobRunningAction", previousJobRunningAction.ToString() )
.UsingJobData( "#jobToRun", jobToRun ?? "" )
.UsingJobData( "#runOnMachineName", runOnMachineName ?? "" )
.Build();
var quartzTriggers = new List<ITrigger>();
foreach( var trigger in triggers )
{
quartzTriggers.Add( TriggerBuilder.Create()
.WithIdentity( "trigger_" + quartzTriggers.Count + "_" + trigger.Description + "_for_" + jobId, "group1" )
.ForJob( job )
.StartAt( startTime )
.WithCronSchedule( trigger.Cron )
.WithDescription( description )
.Build() );
}
if( quartzTriggers.Count == 0 )
{
throw new ArgumentException( "No triggers defined", "triggers" );
}
g_scheduler.ScheduleJob( job, new Quartz.Collection.HashSet<ITrigger>( quartzTriggers ), true );
}
}
} | 46.648649 | 146 | 0.561414 | [
"MIT"
] | andrevdm/NodeScheduler | Source/Avdm.NodeScheduler/Core/NodeScheduler.cs | 3,454 | 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("Ch24_Examples")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Ch24_Examples")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[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("ade8c4f0-cd38-46fc-984d-2373ebdce3b2")]
// 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")]
| 39.27027 | 85 | 0.730213 | [
"MIT"
] | jdm7dv/financial | windows/CsForFinancialMarkets/CsForFinancialMarkets/BookExamples/Ch24/MultiThreadOnSwap/Properties/AssemblyInfo.cs | 1,456 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Outputs
{
[OutputType]
public sealed class WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString
{
[OutputConstructor]
private WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString()
{
}
}
}
| 32.454545 | 143 | 0.778711 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Outputs/WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString.cs | 714 | C# |
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MVC5_Template.Web.DependencyInjectionConfig), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(MVC5_Template.Web.DependencyInjectionConfig), "Stop")]
namespace MVC5_Template.Web
{
using System;
using System.Data.Entity;
using System.Web;
using Auth.ApplicationManagers;
using Auth.Models;
using AutoMapper;
using Core.Contracts;
using Infrastructure.Attributes;
using Infrastructure.Filters;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Extensions.Conventions;
using Ninject.Web.Common;
using Ninject.Web.Mvc.FilterBindingSyntax;
using Persistence.Data;
using Persistence.Data.Repositories;
using Persistence.Data.UnitOfWork;
using Services.Data.Contracts;
public static class DependencyInjectionConfig
{
private static readonly Bootstrapper Bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
Bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
Bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind(x =>
{
x.FromThisAssembly()
.SelectAllClasses()
.BindDefaultInterface();
});
kernel.Bind(x =>
{
x.FromAssemblyContaining(typeof(IDataService))
.SelectAllClasses()
.BindDefaultInterface();
});
kernel
.Bind(typeof(DbContext), typeof(MsSqlDbContext))
.To<MsSqlDbContext>()
.InRequestScope();
// Configure the db context, user manager and signin manager to use a single instance per request
kernel.Bind<ApplicationUserManager>().ToSelf().InRequestScope();
kernel.Bind<ApplicationSignInManager>().ToSelf().InRequestScope();
kernel.Bind<IUserStore<User>>().To<UserStore<User>>().InRequestScope();
kernel.Bind<IAuthenticationManager>()
.ToMethod(c => HttpContext.Current.GetOwinContext().Authentication).InRequestScope();
kernel.Bind<IdentityFactoryOptions<ApplicationUserManager>>().ToSelf().InRequestScope();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind(typeof(IRepository<,>)).To(typeof(EfRepository<,>)).InRequestScope();
kernel.Bind<IMapper>().ToMethod(ctx => Mapper.Instance).InSingletonScope();
kernel.BindFilter<SaveChangesFilter>(System.Web.Mvc.FilterScope.Controller, 0)
.WhenActionMethodHas<SaveChangesAttribute>();
}
}
}
| 34.303279 | 122 | 0.608124 | [
"MIT"
] | SimeonGerginov/ASP.NET-MVC-5-Project-Template | Source/Web/MVC5-Template.Web/App_Start/DependencyInjectionConfig.cs | 4,185 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Devices.V20170119.Inputs
{
/// <summary>
/// The properties related to service bus queue endpoint types.
/// </summary>
public sealed class RoutingServiceBusQueueEndpointPropertiesArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The connection string of the service bus queue endpoint.
/// </summary>
[Input("connectionString", required: true)]
public Input<string> ConnectionString { get; set; } = null!;
/// <summary>
/// The name of the service bus queue endpoint. The name can only include alphanumeric characters, periods, underscores, hyphens and has a maximum length of 64 characters. The following names are reserved; events, operationsMonitoringEvents, fileNotifications, $default. Endpoint names must be unique across endpoint types. The name need not be the same as the actual queue name.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// The name of the resource group of the service bus queue endpoint.
/// </summary>
[Input("resourceGroup")]
public Input<string>? ResourceGroup { get; set; }
/// <summary>
/// The subscription identifier of the service bus queue endpoint.
/// </summary>
[Input("subscriptionId")]
public Input<string>? SubscriptionId { get; set; }
public RoutingServiceBusQueueEndpointPropertiesArgs()
{
}
}
}
| 39.255319 | 388 | 0.661789 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Devices/V20170119/Inputs/RoutingServiceBusQueueEndpointPropertiesArgs.cs | 1,845 | C# |
namespace SystemDot.Bootstrapping
{
using System;
using System.Collections.Generic;
public interface IApplication
{
IEnumerable<Type> GetAllTypes();
}
} | 18.1 | 40 | 0.685083 | [
"MIT"
] | SystemDot/Bootstrapping | IApplication.cs | 181 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace Domain.Model.Data.Migrations
{
public partial class initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.EnsureSchema(
name: "model");
migrationBuilder.CreateTable(
name: "Topics",
schema: "model",
columns: table => new
{
HashTag = table.Column<string>(type: "varchar(128)", nullable: false),
CreateCommandId = table.Column<Guid>(nullable: false),
CreatedOn = table.Column<DateTimeOffset>(nullable: false),
Description = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 128, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Topics", x => x.HashTag)
.Annotation("SqlServer:Clustered", true);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Topics",
schema: "model");
}
}
}
| 33.9 | 90 | 0.532448 | [
"MIT"
] | mitsbits/NoBorg | src/projects/playground/compose/Domain/Model/Data/Migrations/20171222162950_initial.cs | 1,358 | C# |
/*
* tranche.NET - a DSL for modeling structured finance products.
* Copyright (C) 2012 Timothy Goric
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
namespace SemanticAnalysis
{
public class TypeBoolean : InternalType
{
public override Type CilType { get { return typeof(bool); } }
public override string ToString() { return "boolean"; }
}
}
| 33.464286 | 76 | 0.690502 | [
"Unlicense"
] | goric/tranche-net | SemanticAnalysis/TypeBoolean.cs | 939 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.IO;
using System.Reflection;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.ComponentModel.Design.Tests
{
public static class DesigntimeLicenseContextSerializerTests
{
private const string enableBinaryFormatterInTypeConverter =
"System.ComponentModel.TypeConverter.EnableUnsafeBinaryFormatterInDesigntimeLicenseContextSerialization";
private const string enableBinaryFormatter =
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization";
public static bool AreBinaryFormatterAndRemoteExecutorSupportedOnThisPlatform =>
PlatformDetection.IsBinaryFormatterSupported && RemoteExecutor.IsSupported;
private static void VerifyStreamFormatting(Stream stream)
{
AppContext.TryGetSwitch(
enableBinaryFormatterInTypeConverter,
out bool binaryFormatterUsageInTypeConverterIsEnabled
);
long position = stream.Position;
int firstByte = stream.ReadByte();
if (binaryFormatterUsageInTypeConverterIsEnabled)
{
Assert.Equal(0, firstByte);
}
else
{
Assert.Equal(255, firstByte);
}
stream.Seek(position, SeekOrigin.Begin);
}
[ConditionalTheory(nameof(AreBinaryFormatterAndRemoteExecutorSupportedOnThisPlatform))]
[InlineData(false, "key")]
[InlineData(true, "key")]
[InlineData(false, "")]
[InlineData(true, "")]
public static void SerializeAndDeserialize(bool useBinaryFormatter, string key)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
if (useBinaryFormatter)
{
options.RuntimeConfigurationOptions.Add(
enableBinaryFormatterInTypeConverter,
bool.TrueString
);
}
RemoteExecutor
.Invoke(
(key) =>
{
var context = new DesigntimeLicenseContext();
context.SetSavedLicenseKey(typeof(int), key);
var assembly = typeof(DesigntimeLicenseContextSerializer).Assembly;
Type runtimeLicenseContextType = assembly.GetType(
"System.ComponentModel.Design.RuntimeLicenseContext"
);
Assert.NotNull(runtimeLicenseContextType);
object runtimeLicenseContext = Activator.CreateInstance(
runtimeLicenseContextType
);
FieldInfo _savedLicenseKeys = runtimeLicenseContextType.GetField(
"_savedLicenseKeys",
BindingFlags.NonPublic | BindingFlags.Instance
);
Assert.NotNull(_savedLicenseKeys);
_savedLicenseKeys.SetValue(runtimeLicenseContext, new Hashtable());
Assert.NotNull(runtimeLicenseContext);
Type designtimeLicenseContextSerializer = assembly.GetType(
"System.ComponentModel.Design.DesigntimeLicenseContextSerializer"
);
Assert.NotNull(designtimeLicenseContextSerializer);
MethodInfo deserializeMethod = designtimeLicenseContextSerializer.GetMethod(
"Deserialize",
BindingFlags.NonPublic | BindingFlags.Static
);
using (MemoryStream stream = new MemoryStream())
{
long position = stream.Position;
DesigntimeLicenseContextSerializer.Serialize(stream, key, context);
stream.Seek(position, SeekOrigin.Begin);
VerifyStreamFormatting(stream);
deserializeMethod.Invoke(
null,
new object[] { stream, key, runtimeLicenseContext }
);
Hashtable savedLicenseKeys =
runtimeLicenseContext
.GetType()
.GetField(
"_savedLicenseKeys",
BindingFlags.NonPublic | BindingFlags.Instance
)
.GetValue(runtimeLicenseContext) as Hashtable;
Assert.NotNull(savedLicenseKeys);
var value = savedLicenseKeys[typeof(int).AssemblyQualifiedName];
Assert.True(value is string);
Assert.Equal(key, value);
}
},
key,
options
)
.Dispose();
}
[ConditionalTheory(nameof(AreBinaryFormatterAndRemoteExecutorSupportedOnThisPlatform))]
[InlineData("key")]
[InlineData("")]
public static void SerializeWithBinaryFormatter_DeserializeWithBinaryWriter(string key)
{
AppContext.SetSwitch(enableBinaryFormatter, true);
AppContext.SetSwitch(enableBinaryFormatterInTypeConverter, true);
var context = new DesigntimeLicenseContext();
context.SetSavedLicenseKey(typeof(int), key);
string tempPath = Path.GetTempPath();
try
{
using (MemoryStream stream = new MemoryStream())
{
long position = stream.Position;
DesigntimeLicenseContextSerializer.Serialize(stream, key, context);
stream.Seek(position, SeekOrigin.Begin);
VerifyStreamFormatting(stream);
using (
FileStream outStream = File.Create(
Path.Combine(
tempPath,
"_temp_SerializeWithBinaryFormatter_DeserializeWithBinaryWriter"
)
)
)
{
stream.Seek(position, SeekOrigin.Begin);
stream.CopyTo(outStream);
}
}
RemoteInvokeHandle handle = RemoteExecutor.Invoke(
(key) =>
{
var assembly = typeof(DesigntimeLicenseContextSerializer).Assembly;
Type runtimeLicenseContextType = assembly.GetType(
"System.ComponentModel.Design.RuntimeLicenseContext"
);
Assert.NotNull(runtimeLicenseContextType);
object runtimeLicenseContext = Activator.CreateInstance(
runtimeLicenseContextType
);
Assert.NotNull(runtimeLicenseContext);
FieldInfo _savedLicenseKeys = runtimeLicenseContextType.GetField(
"_savedLicenseKeys",
BindingFlags.NonPublic | BindingFlags.Instance
);
Assert.NotNull(_savedLicenseKeys);
_savedLicenseKeys.SetValue(runtimeLicenseContext, new Hashtable());
Type designtimeLicenseContextSerializer = assembly.GetType(
"System.ComponentModel.Design.DesigntimeLicenseContextSerializer"
);
Assert.NotNull(designtimeLicenseContextSerializer);
MethodInfo deserializeMethod = designtimeLicenseContextSerializer.GetMethod(
"Deserialize",
BindingFlags.NonPublic | BindingFlags.Static
);
Assert.NotNull(deserializeMethod);
string tempPath = Path.GetTempPath();
using (
FileStream stream = File.Open(
Path.Combine(
tempPath,
"_temp_SerializeWithBinaryFormatter_DeserializeWithBinaryWriter"
),
FileMode.Open
)
)
{
TargetInvocationException exception =
Assert.Throws<TargetInvocationException>(
() =>
deserializeMethod.Invoke(
null,
new object[] { stream, key, runtimeLicenseContext }
)
);
Assert.IsType<NotSupportedException>(exception.InnerException);
}
},
key
);
handle.Process.WaitForExit();
handle.Dispose();
}
finally
{
File.Delete(
Path.Combine(
tempPath,
"_temp_SerializeWithBinaryFormatter_DeserializeWithBinaryWriter"
)
);
}
}
}
}
| 45.812785 | 117 | 0.491179 | [
"MIT"
] | belav/runtime | src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesigntimeLicenseContextSerializerTests.cs | 10,035 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Yandex.Outputs
{
[OutputType]
public sealed class GetAlbBackendGroupHttpBackendHealthcheckHttpHealthcheckResult
{
/// <summary>
/// Optional "Host" HTTP header value.
/// </summary>
public readonly string Host;
/// <summary>
/// If set, health checks will use HTTP2.
/// </summary>
public readonly bool Http2;
/// <summary>
/// HTTP path.
/// </summary>
public readonly string Path;
[OutputConstructor]
private GetAlbBackendGroupHttpBackendHealthcheckHttpHealthcheckResult(
string host,
bool http2,
string path)
{
Host = host;
Http2 = http2;
Path = path;
}
}
}
| 25.883721 | 88 | 0.601977 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-yandex | sdk/dotnet/Outputs/GetAlbBackendGroupHttpBackendHealthcheckHttpHealthcheckResult.cs | 1,113 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using CommandLine;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace UniGet
{
internal static class PackTool
{
internal class Options
{
[Value(0, Required = true, HelpText = "Project File")]
public string ProjectFile { get; set; }
[Option('o', "output", HelpText = "Specifies the directory for the created unity package file. If not specified, uses the current directory.")]
public string OutputDirectory { get; set; }
[Option('l', "local", HelpText = "Specifies the directory for the local repository.")]
public string LocalRepositoryDirectory { get; set; }
}
public static int Run(params string[] args)
{
var parser = new Parser(config => config.HelpWriter = Console.Out);
if (args.Length == 0)
{
parser.ParseArguments<Options>(new[] { "--help" });
return 1;
}
Options options = null;
var result = parser.ParseArguments<Options>(args)
.WithParsed(r => { options = r; });
// Run process !
if (options != null)
return Process(options);
else
return 1;
}
internal static int Process(Options options)
{
var p = Project.Load(options.ProjectFile);
var projectDir = Path.GetDirectoryName(options.ProjectFile);
var outputDir = options.OutputDirectory ?? projectDir;
if (string.IsNullOrEmpty(p.Id))
throw new InvalidDataException("Cannot find id from project.");
if (string.IsNullOrEmpty(p.Version))
throw new InvalidDataException("Cannot find version from project.");
p.Version = new SemVer.Version(p.Version).ToString();
if (p.Files == null || p.Files.Any() == false)
throw new InvalidDataException("Cannot find files from project.");
var homeBaseDir = "Assets/UnityPackages";
var homeDir = homeBaseDir + "/" + p.Id;
var tempDir = Extracter.CreateTemporaryDirectory();
var files = new List<Project.FileItem>();
var packagePath = Path.Combine(outputDir, $"{p.Id}.{p.Version}.unitypackage");
using (var packer = new Packer(packagePath))
{
foreach (var fileValue in p.Files)
{
if (fileValue is JObject)
{
var fileItem = fileValue.ToObject<Project.FileItem>();
var filePath = Path.Combine(projectDir, fileItem.Source);
var targetResolved = fileItem.Target.Replace("$id$", p.Id)
.Replace("$home$", homeDir)
.Replace("$homebase$", homeBaseDir);
AddFiles(packer, files, filePath, targetResolved, fileItem.Extra);
}
else if (fileValue.ToString().StartsWith("$"))
{
var keyword = fileValue.ToString().ToLower();
if (keyword != "$dependencies$")
{
throw new InvalidDataException("Wrong keyword: " + keyword);
}
var mergedProjectMap = RestoreTool.Process(new RestoreTool.Options
{
ProjectFile = options.ProjectFile,
OutputDirectory = tempDir,
LocalRepositoryDirectory = options.LocalRepositoryDirectory
}).Result;
p.MergedDependencies = mergedProjectMap.ToDictionary(
i => i.Key,
i => new Project.Dependency { Version = i.Value.ToString() });
foreach (var file in Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories))
{
if (Path.GetExtension(file).ToLower() == ".meta")
{
var assetFile = file.Substring(0, file.Length - 5);
var targetFile = assetFile.Substring(tempDir.Length + 1).Replace("\\", "/");
// NOTE:
// if Extra field of file in merged dependencies,
// read *.unitypackage.json and use data from them.
if (File.Exists(assetFile))
{
files.Add(new Project.FileItem
{
Source = assetFile,
Target = targetFile,
Merged = true
});
}
packer.Add(assetFile, targetFile);
}
}
}
else
{
var filePath = Path.Combine(projectDir, fileValue.ToString());
AddFiles(packer, files, filePath, homeDir + "/", false);
}
}
if (files.Any() == false)
throw new InvalidDataException("Nothing to add for files.");
// make files
var jsonSettings = new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore,
};
p.Files = files.Select(
f => (f.Extra || f.Merged)
? JToken.FromObject(new Project.FileItem { Target = f.Target, Extra = f.Extra, Merged = f.Merged }, JsonSerializer.Create(jsonSettings))
: JToken.FromObject(f.Target)).ToList();
// add project.json
var projectPath = Path.Combine(tempDir, p.Id + ".unitypackage.json");
File.WriteAllText(projectPath, JsonConvert.SerializeObject(p, Formatting.Indented, jsonSettings));
packer.AddWithMetaGenerated(projectPath, homeBaseDir + "/" + p.Id + ".unitypackage.json");
packer.AddDirectoriesWithMetaGenerated(homeBaseDir);
}
if (string.IsNullOrEmpty(tempDir) == false)
Directory.Delete(tempDir, true);
return 0;
}
internal static void AddFiles(Packer packer, List<Project.FileItem> files, string source, string target, bool extra)
{
var dirs = new HashSet<string>();
foreach (var f in FileUtility.GetFiles(source, target))
{
var srcFile = f.Item1;
var dstFile = f.Item2.Replace("\\", "/");
if (Path.GetExtension(srcFile).ToLower() == ".meta")
continue;
// add file
files.Add(new Project.FileItem
{
Source = srcFile,
Target = dstFile,
Extra = extra,
});
if (File.Exists(srcFile + ".meta"))
packer.Add(srcFile, dstFile);
else
packer.AddWithMetaGenerated(srcFile, dstFile);
dirs.Add(Path.GetDirectoryName(dstFile).Replace("\\", "/"));
// if dll, add *.mdb. if not exist, generate one from pdb
if (Path.GetExtension(srcFile).ToLower() == ".dll")
{
var mdbFilePath = srcFile + ".mdb";
if (File.Exists(mdbFilePath) == false ||
File.GetLastWriteTime(srcFile) > File.GetLastWriteTime(mdbFilePath))
{
MdbTool.ConvertPdbToMdb(srcFile);
}
if (File.Exists(mdbFilePath))
{
files.Add(new Project.FileItem
{
Source = mdbFilePath,
Target = dstFile + ".mdb",
Extra = extra,
});
packer.AddWithMetaGenerated(mdbFilePath, dstFile + ".mdb");
}
}
}
foreach (var dir in dirs)
{
packer.AddDirectoriesWithMetaGenerated(dir);
}
}
}
}
| 39.905405 | 160 | 0.462129 | [
"MIT"
] | SaladLab/UniGet | src/UniGet/PackTool.cs | 8,861 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Transactions ;
using NUnit.Framework ;
using NW = alby.northwind.codegen ;
namespace alby.northwind.codegen.test.table
{
[TestFixture]
public class TestTable3 : NW.test.TransactionScopeTestBase
{
public TestTable3()
{
_connectionString = Settings.ConnectionString();
}
[Test]
public void TestDeleteAllAndComputedColumnsInsertUpdate()
{
NW.table.TestTable3Factory factory = new NW.table.TestTable3Factory();
// load all test
List<NW.table.TestTable3> list = factory.Loadˡ(_connection);
int count = factory.GetRowCountˡ(_connection) ;
Console.WriteLine( "count = {0}", count ) ;
Assert.AreEqual( count, list.Count ) ;
int max = int.Parse( factory.GetMaxValueˡ( _connection, NW.table.TestTable3.column٠ID ) ) ;
Assert.AreEqual( count, max ) ;
// delete all test
factory.DeleteAllˡ(_connection);
int count2 = factory.GetRowCountˡ(_connection) ;
Assert.AreEqual(count2, 0);
Assert.IsNull( factory.GetMaxValueˡ(_connection, NW.table.TestTable3.column٠ID ) ) ;
// insert 1 row
NW.table.TestTable3 obj = new NW.table.TestTable3() ;
string id = factory.GetMaxValueˡ( _connection, NW.table.TestTable3.column٠ID ) ;
if ( id == null ) id = "0" ;
obj.ID = int.Parse( id ) + 1 ;
obj.update_date = DateTime.Now ;
obj.A = 100 ;
obj.B = 200 ;
//obj.C ;
//obj.TheProduct ;
//obj.TheSum ;
// assert unset fields
Assert.IsNull(obj.C);
Assert.IsNull(obj.TheProduct);
Assert.IsNull(obj.TheSum);
// dump object
foreach (string key in obj.Dictionaryˡ.Keys)
Console.WriteLine("obj [{0}] [{1}]", key, obj.Dictionaryˡ[key]);
// save it
NW.table.TestTable3 obj1 = factory.Saveˡ( _connection, obj ) ;
Assert.IsNotNull(obj1);
Assert.AreNotSame(obj, obj1);
// dump object
foreach (string key in obj1.Dictionaryˡ.Keys)
Console.WriteLine("obj1 [{0}] [{1}]", key, obj1.Dictionaryˡ[key]);
//assert computed fields
Assert.AreEqual(obj1.ID, 1);
Assert.AreEqual(obj1.TheSum, 100 + 200 );
Assert.AreEqual(obj1.TheProduct, 100 * 200);
Assert.IsNull( obj1.C ) ;
// do update
obj1.A = 101 ;
obj1.C = -1234 ;
NW.table.TestTable3 obj2 = factory.Saveˡ( _connection, obj1 );
Assert.IsNotNull(obj2);
Assert.AreNotSame(obj1, obj2);
// dump object
foreach (string key in obj2.Dictionaryˡ.Keys)
Console.WriteLine("obj2 [{0}] [{1}]", key, obj2.Dictionaryˡ[key]);
//assert computed fields
Assert.AreEqual(obj2.ID, 1);
Assert.AreEqual(obj2.TheSum, 101 + 200);
Assert.AreEqual(obj2.TheProduct, 101 * 200);
// test only 1 row in table
list = factory.Loadˡ(_connection);
count = factory.GetRowCountˡ(_connection);
Console.WriteLine("count = {0}", count);
Assert.AreEqual(count, 1);
Assert.AreEqual(count, list.Count);
max = int.Parse( factory.GetMaxValueˡ(_connection, NW.table.TestTable3.column٠ID ));
Assert.AreEqual(max, count);
// read it back
NW.table.TestTable3 obj3 = factory.LoadByPrimaryKeyˡ( _connection, obj1.ID );
Assert.IsNotNull( obj3 ) ;
Assert.AreEqual( obj3.ID, obj1.ID ) ;
Assert.AreEqual( obj3.ID, 1 ) ;
Assert.AreEqual( obj3.A, obj1.A);
// dump object
foreach (string key in obj3.Dictionaryˡ.Keys)
Console.WriteLine("obj3 [{0}] [{1}]", key, obj3.Dictionaryˡ[key]);
}
[Test]
public void TestInsertAndUpdate()
{
NW.table.TestTable3Factory factory = new NW.table.TestTable3Factory();
int count1 = factory.GetRowCountˡ(_connection);
// insert row
NW.table.TestTable3 obj1 = new NW.table.TestTable3();
obj1.ID = int.Parse( factory.GetMaxValueˡ(_connection, NW.table.TestTable3.column٠ID )) + 1 ;
obj1.update_date = DateTime.Now ;
obj1.A = obj1.ID ;
obj1.B = obj1.ID;
NW.table.TestTable3 obj2 = factory.Saveˡ( _connection, obj1 );
Assert.IsNotNull(obj2);
Assert.AreNotEqual(obj1, obj2);
Assert.AreEqual(obj1.ID, obj2.ID);
Assert.AreEqual(obj2.TheProduct, obj1.A * obj1.B);
int count2 = factory.GetRowCountˡ(_connection);
Assert.AreEqual(count2, count1 + 1);
// dump object
foreach (string key in obj2.Dictionaryˡ.Keys)
Console.WriteLine("obj2 [{0}] [{1}]", key, obj2.Dictionaryˡ[key]);
foreach (string key in obj2.PrimaryKeyDictionaryˡ.Keys)
Console.WriteLine("obj2 pk [{0}] [{1}]", key, obj2.PrimaryKeyDictionaryˡ[key]);
// test normal update
obj2.A = 100 ;
obj2.B = 100;
obj2.update_date = DateTime.Now;
NW.table.TestTable3 obj3 = factory.Saveˡ( _connection, obj2 );
Assert.IsNotNull(obj3);
Assert.AreNotEqual(obj2, obj3);
Assert.AreEqual(obj3.ID, obj2.ID);
Assert.AreEqual(obj3.TheProduct, 100*100);
int count3 = factory.GetRowCountˡ(_connection);
Assert.AreEqual(count3, count2);
// dump object
foreach (string key in obj3.Dictionaryˡ.Keys)
Console.WriteLine("obj3 [{0}] [{1}]", key, obj3.Dictionaryˡ[key]);
foreach (string key in obj3.PrimaryKeyDictionaryˡ.Keys)
Console.WriteLine("obj3 pk [{0}] [{1}]", key, obj3.PrimaryKeyDictionaryˡ[key]);
// update primary key
obj3.ID = obj2.ID * 2 ;
obj3.update_date = DateTime.Now;
NW.table.TestTable3 obj4 = factory.Saveˡ( _connection, obj3 );
Assert.IsNotNull(obj4);
Assert.AreNotEqual(obj3, obj4);
Assert.AreEqual(obj4.ID, obj3.ID);
Assert.AreEqual(obj4.ID, obj2.ID*2);
Assert.AreEqual(obj4.TheProduct, 100 * 100);
// dump object
foreach (string key in obj4.Dictionaryˡ.Keys)
Console.WriteLine("obj4 [{0}] [{1}]", key, obj4.Dictionaryˡ[key]);
foreach (string key in obj4.PrimaryKeyDictionaryˡ.Keys)
Console.WriteLine("obj4 pk [{0}] [{1}]", key, obj4.PrimaryKeyDictionaryˡ[key]);
// check that original ID is now not found
NW.table.TestTable3 obj5 = factory.LoadByPrimaryKeyˡ( _connection, obj1.ID ) ;
Assert.IsNull(obj5);
int count4 = factory.GetRowCountˡ(_connection);
Assert.AreEqual(count4, count2);
}
}
} | 32.57513 | 98 | 0.65882 | [
"MIT"
] | casaletto/alby.northwind.2015 | alby.northwind.codegen.test/table/TestTable3.cs | 6,334 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was automatically generated.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FoxKit.Modules.DataSet.Fox.Sdx
{
using System;
using System.Collections.Generic;
using FoxKit.Modules.DataSet.Fox.FoxCore;
using FoxKit.Modules.Lua;
using FoxLib;
using static KopiLua.Lua;
using OdinSerializer;
using UnityEngine;
using DataSetFile2 = DataSetFile2;
using TppGameKit = FoxKit.Modules.DataSet.Fox.TppGameKit;
[SerializableAttribute, ExposeClassToLuaAttribute]
public partial class SoundSourceBody : TransformDataBody
{
public override short ClassId => 0;
public override ushort Version => 0;
public override string Category => "";
[ExposeMethodToLua(MethodStaticity.Instance)]
partial void PostEvent(lua_State lua);
[ExposeMethodToLua(MethodStaticity.Instance)]
partial void StopEvent(lua_State lua);
[ExposeMethodToLua(MethodStaticity.Instance)]
partial void SetSwitch(lua_State lua);
[ExposeMethodToLua(MethodStaticity.Instance)]
partial void SetRTPC(lua_State lua);
[ExposeMethodToLua(MethodStaticity.Instance)]
partial void ResetRTPC(lua_State lua);
[ExposeMethodToLua(MethodStaticity.Instance)]
partial void IsPlaying(lua_State lua);
}
}
| 33.5 | 81 | 0.608955 | [
"MIT"
] | Joey35233/FoxKit | FoxKit/Assets/FoxKit/Modules/DataSet/Fox/Sdx/SoundSourceBody.Generated.cs | 1,675 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JCSoft.WX.Framework.Models.ApiResponses;
using JCSoft.Core.Net.Http;
namespace JCSoft.WX.Framework.Models.ApiRequests
{
public class CustomserviceKfaccountAddRequest : ApiRequest<DefaultResponse>
{
/// <summary>
/// 完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符。如果没有公众号微信号,请前往微信公众平台设置。
/// </summary>
[JsonProperty("kf_account")]
public string Account { get; set; }
/// <summary>
/// 客服昵称,最长6个汉字或12个英文字符
/// </summary>
[JsonProperty("nickname")]
public string Nickname { get; set; }
/// <summary>
/// 客服账号登录密码,格式为密码明文的32位加密MD5值
/// </summary>
[JsonProperty("password")]
public string Password { get; set; }
internal override HttpRequestActionType Method
{
get { return HttpRequestActionType.Content; }
}
protected override string UrlFormat
{
get { return "/customservice/kfaccount/add?access_token={0}"; }
}
internal override string GetUrl()
{
return String.Format(UrlFormat, AccessToken);
}
protected override bool NeedToken
{
get { return true; }
}
internal override string GetPostContent()
{
return JsonConvert.SerializeObject(this);
}
}
}
| 25.964912 | 82 | 0.6 | [
"MIT"
] | JamesYing/JCWXCore | src/JCSoft.WX.Framework/Models/ApiRequests/customservice/CustomserviceKfaccountAddRequest.cs | 1,690 | C# |
namespace BizHawk.Client.EmuHawk
{
partial class AutofireConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Ok = new System.Windows.Forms.Button();
this.Cancel = new System.Windows.Forms.Button();
this.OnNumeric = new System.Windows.Forms.NumericUpDown();
this.OffNumeric = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.LagFrameCheck = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.OnNumeric)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.OffNumeric)).BeginInit();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// Ok
//
this.Ok.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.Ok.Location = new System.Drawing.Point(108, 140);
this.Ok.Name = "Ok";
this.Ok.Size = new System.Drawing.Size(75, 23);
this.Ok.TabIndex = 5;
this.Ok.Text = "&OK";
this.Ok.UseVisualStyleBackColor = true;
this.Ok.Click += new System.EventHandler(this.Ok_Click);
//
// Cancel
//
this.Cancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Cancel.Location = new System.Drawing.Point(189, 140);
this.Cancel.Name = "Cancel";
this.Cancel.Size = new System.Drawing.Size(75, 23);
this.Cancel.TabIndex = 7;
this.Cancel.Text = "&Cancel";
this.Cancel.UseVisualStyleBackColor = true;
this.Cancel.Click += new System.EventHandler(this.Cancel_Click);
//
// OnNumeric
//
this.OnNumeric.Location = new System.Drawing.Point(10, 32);
this.OnNumeric.Maximum = new decimal(new int[] {
512,
0,
0,
0});
this.OnNumeric.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.OnNumeric.Name = "OnNumeric";
this.OnNumeric.Size = new System.Drawing.Size(74, 20);
this.OnNumeric.TabIndex = 2;
this.OnNumeric.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// OffNumeric
//
this.OffNumeric.Location = new System.Drawing.Point(101, 32);
this.OffNumeric.Maximum = new decimal(new int[] {
512,
0,
0,
0});
this.OffNumeric.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.OffNumeric.Name = "OffNumeric";
this.OffNumeric.Size = new System.Drawing.Size(74, 20);
this.OffNumeric.TabIndex = 3;
this.OffNumeric.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(10, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(21, 13);
this.label1.TabIndex = 4;
this.label1.Text = "On";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(101, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(21, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Off";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.OnNumeric);
this.groupBox1.Controls.Add(this.OffNumeric);
this.groupBox1.Location = new System.Drawing.Point(13, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(184, 70);
this.groupBox1.TabIndex = 6;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Autofire Pattern";
//
// LagFrameCheck
//
this.LagFrameCheck.AutoSize = true;
this.LagFrameCheck.Location = new System.Drawing.Point(13, 100);
this.LagFrameCheck.Name = "LagFrameCheck";
this.LagFrameCheck.Size = new System.Drawing.Size(164, 17);
this.LagFrameCheck.TabIndex = 8;
this.LagFrameCheck.Text = "Take lag frames into account";
this.LagFrameCheck.UseVisualStyleBackColor = true;
//
// AutofireConfig
//
this.AcceptButton = this.Ok;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.Cancel;
this.ClientSize = new System.Drawing.Size(276, 175);
this.Controls.Add(this.LagFrameCheck);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.Cancel);
this.Controls.Add(this.Ok);
this.Icon = global::BizHawk.Client.EmuHawk.Properties.Resources.Lightning_MultiSize;
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(512, 512);
this.MinimumSize = new System.Drawing.Size(218, 179);
this.Name = "AutofireConfig";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Autofire Configuration";
this.Load += new System.EventHandler(this.AutofireConfig_Load);
((System.ComponentModel.ISupportInitialize)(this.OnNumeric)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.OffNumeric)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button Ok;
private System.Windows.Forms.Button Cancel;
private System.Windows.Forms.NumericUpDown OffNumeric;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.GroupBox groupBox1;
public System.Windows.Forms.NumericUpDown OnNumeric;
private System.Windows.Forms.CheckBox LagFrameCheck;
}
} | 35.560209 | 149 | 0.652385 | [
"MIT"
] | Diefool/BizHawk | BizHawk.Client.EmuHawk/config/AutofireConfig.Designer.cs | 6,794 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hradla.Asm
{
class Hadani : Assembler
{
public Hadani()
{
Jmp("code");
LData("secret", 83);
LData("low", 0);
LData("hi", 100);
LData("testsPtr", "tests");
LData("result", -1);
Label("code");
Ld(AR, "hi");
SubLd(AR, "low");
Jnz("code1");
Ld(AR, "low");
St("result", AR);
Mov(AR, 1);
St(255, AR);
Label("code1");
Shr(AR, 1);
AddLd(AR, "low");
Ld(BR, "testsPtr");
St(BR, AR);
Add(BR, 1);
St("testsPtr", BR);
Mov(BR, AR);
SubLd(AR, "secret");
Jl("greater");
St("hi", BR);
Jmp("code");
Label("greater");
Add(BR, 1);
St("low", BR);
Jmp("code");
Label("tests");
}
}
}
| 21.792453 | 40 | 0.366234 | [
"MIT"
] | HonzaMD/TunnaHead-483-processor | Asm/Hadani.cs | 1,157 | C# |
namespace JDP {
partial class frmSettings {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.txtDownloadFolder = new System.Windows.Forms.TextBox();
this.lblDownloadFolder = new System.Windows.Forms.Label();
this.btnBrowse = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.chkCustomUserAgent = new System.Windows.Forms.CheckBox();
this.txtCustomUserAgent = new System.Windows.Forms.TextBox();
this.chkRelativePath = new System.Windows.Forms.CheckBox();
this.lblSettingsLocation = new System.Windows.Forms.Label();
this.rbSettingsInAppDataFolder = new System.Windows.Forms.RadioButton();
this.rbSettingsInExeFolder = new System.Windows.Forms.RadioButton();
this.chkUseOriginalFileNames = new System.Windows.Forms.CheckBox();
this.chkVerifyImageHashes = new System.Windows.Forms.CheckBox();
this.chkSaveThumbnails = new System.Windows.Forms.CheckBox();
this.chkRenameDownloadFolderWithDescription = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// txtDownloadFolder
//
this.txtDownloadFolder.Location = new System.Drawing.Point(108, 8);
this.txtDownloadFolder.Name = "txtDownloadFolder";
this.txtDownloadFolder.Size = new System.Drawing.Size(412, 20);
this.txtDownloadFolder.TabIndex = 1;
//
// lblDownloadFolder
//
this.lblDownloadFolder.AutoSize = true;
this.lblDownloadFolder.Location = new System.Drawing.Point(8, 12);
this.lblDownloadFolder.Name = "lblDownloadFolder";
this.lblDownloadFolder.Size = new System.Drawing.Size(87, 13);
this.lblDownloadFolder.TabIndex = 0;
this.lblDownloadFolder.Text = "Download folder:";
//
// btnBrowse
//
this.btnBrowse.Location = new System.Drawing.Point(528, 8);
this.btnBrowse.Name = "btnBrowse";
this.btnBrowse.Size = new System.Drawing.Size(80, 23);
this.btnBrowse.TabIndex = 2;
this.btnBrowse.Text = "Browse...";
this.btnBrowse.UseVisualStyleBackColor = true;
this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
//
// btnOK
//
this.btnOK.Location = new System.Drawing.Point(568, 168);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(60, 23);
this.btnOK.TabIndex = 13;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(636, 168);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(68, 23);
this.btnCancel.TabIndex = 14;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// chkCustomUserAgent
//
this.chkCustomUserAgent.AutoSize = true;
this.chkCustomUserAgent.Location = new System.Drawing.Point(10, 42);
this.chkCustomUserAgent.Name = "chkCustomUserAgent";
this.chkCustomUserAgent.Size = new System.Drawing.Size(117, 17);
this.chkCustomUserAgent.TabIndex = 4;
this.chkCustomUserAgent.Text = "Custom user agent:";
this.chkCustomUserAgent.UseVisualStyleBackColor = true;
this.chkCustomUserAgent.CheckedChanged += new System.EventHandler(this.chkCustomUserAgent_CheckedChanged);
//
// txtCustomUserAgent
//
this.txtCustomUserAgent.Enabled = false;
this.txtCustomUserAgent.Location = new System.Drawing.Point(140, 40);
this.txtCustomUserAgent.Name = "txtCustomUserAgent";
this.txtCustomUserAgent.Size = new System.Drawing.Size(564, 20);
this.txtCustomUserAgent.TabIndex = 5;
//
// chkRelativePath
//
this.chkRelativePath.AutoSize = true;
this.chkRelativePath.Location = new System.Drawing.Point(616, 12);
this.chkRelativePath.Name = "chkRelativePath";
this.chkRelativePath.Size = new System.Drawing.Size(89, 17);
this.chkRelativePath.TabIndex = 3;
this.chkRelativePath.Text = "Relative path";
this.chkRelativePath.UseVisualStyleBackColor = true;
this.chkRelativePath.CheckedChanged += new System.EventHandler(this.chkRelativePath_CheckedChanged);
//
// lblSettingsLocation
//
this.lblSettingsLocation.AutoSize = true;
this.lblSettingsLocation.Location = new System.Drawing.Point(8, 176);
this.lblSettingsLocation.Name = "lblSettingsLocation";
this.lblSettingsLocation.Size = new System.Drawing.Size(85, 13);
this.lblSettingsLocation.TabIndex = 10;
this.lblSettingsLocation.Text = "Save settings in:";
//
// rbSettingsInAppDataFolder
//
this.rbSettingsInAppDataFolder.AutoSize = true;
this.rbSettingsInAppDataFolder.Location = new System.Drawing.Point(108, 174);
this.rbSettingsInAppDataFolder.Name = "rbSettingsInAppDataFolder";
this.rbSettingsInAppDataFolder.Size = new System.Drawing.Size(130, 17);
this.rbSettingsInAppDataFolder.TabIndex = 11;
this.rbSettingsInAppDataFolder.TabStop = true;
this.rbSettingsInAppDataFolder.Text = "Application data folder";
this.rbSettingsInAppDataFolder.UseVisualStyleBackColor = true;
//
// rbSettingsInExeFolder
//
this.rbSettingsInExeFolder.AutoSize = true;
this.rbSettingsInExeFolder.Location = new System.Drawing.Point(252, 174);
this.rbSettingsInExeFolder.Name = "rbSettingsInExeFolder";
this.rbSettingsInExeFolder.Size = new System.Drawing.Size(107, 17);
this.rbSettingsInExeFolder.TabIndex = 12;
this.rbSettingsInExeFolder.TabStop = true;
this.rbSettingsInExeFolder.Text = "Executable folder";
this.rbSettingsInExeFolder.UseVisualStyleBackColor = true;
//
// chkUseOriginalFileNames
//
this.chkUseOriginalFileNames.AutoSize = true;
this.chkUseOriginalFileNames.Location = new System.Drawing.Point(10, 120);
this.chkUseOriginalFileNames.Name = "chkUseOriginalFileNames";
this.chkUseOriginalFileNames.Size = new System.Drawing.Size(273, 17);
this.chkUseOriginalFileNames.TabIndex = 8;
this.chkUseOriginalFileNames.Text = "Use original filenames (only supported for some sites)";
this.chkUseOriginalFileNames.UseVisualStyleBackColor = true;
//
// chkVerifyImageHashes
//
this.chkVerifyImageHashes.AutoSize = true;
this.chkVerifyImageHashes.Location = new System.Drawing.Point(10, 144);
this.chkVerifyImageHashes.Name = "chkVerifyImageHashes";
this.chkVerifyImageHashes.Size = new System.Drawing.Size(265, 17);
this.chkVerifyImageHashes.TabIndex = 9;
this.chkVerifyImageHashes.Text = "Verify image hashes (only supported for some sites)";
this.chkVerifyImageHashes.UseVisualStyleBackColor = true;
//
// chkSaveThumbnails
//
this.chkSaveThumbnails.AutoSize = true;
this.chkSaveThumbnails.Location = new System.Drawing.Point(10, 72);
this.chkSaveThumbnails.Name = "chkSaveThumbnails";
this.chkSaveThumbnails.Size = new System.Drawing.Size(221, 17);
this.chkSaveThumbnails.TabIndex = 6;
this.chkSaveThumbnails.Text = "Save thumbnails and post-process HTML";
this.chkSaveThumbnails.UseVisualStyleBackColor = true;
//
// chkRenameDownloadFolderWithDescription
//
this.chkRenameDownloadFolderWithDescription.AutoSize = true;
this.chkRenameDownloadFolderWithDescription.Location = new System.Drawing.Point(10, 96);
this.chkRenameDownloadFolderWithDescription.Name = "chkRenameDownloadFolderWithDescription";
this.chkRenameDownloadFolderWithDescription.Size = new System.Drawing.Size(253, 17);
this.chkRenameDownloadFolderWithDescription.TabIndex = 7;
this.chkRenameDownloadFolderWithDescription.Text = "Use description as thread download folder name";
this.chkRenameDownloadFolderWithDescription.UseVisualStyleBackColor = true;
//
// frmSettings
//
this.AcceptButton = this.btnOK;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(714, 201);
this.Controls.Add(this.chkRenameDownloadFolderWithDescription);
this.Controls.Add(this.chkSaveThumbnails);
this.Controls.Add(this.chkVerifyImageHashes);
this.Controls.Add(this.chkUseOriginalFileNames);
this.Controls.Add(this.rbSettingsInExeFolder);
this.Controls.Add(this.rbSettingsInAppDataFolder);
this.Controls.Add(this.lblSettingsLocation);
this.Controls.Add(this.chkRelativePath);
this.Controls.Add(this.txtCustomUserAgent);
this.Controls.Add(this.chkCustomUserAgent);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnBrowse);
this.Controls.Add(this.lblDownloadFolder);
this.Controls.Add(this.txtDownloadFolder);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmSettings";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Settings";
this.Load += new System.EventHandler(this.frmSettings_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtDownloadFolder;
private System.Windows.Forms.Label lblDownloadFolder;
private System.Windows.Forms.Button btnBrowse;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.CheckBox chkCustomUserAgent;
private System.Windows.Forms.TextBox txtCustomUserAgent;
private System.Windows.Forms.CheckBox chkRelativePath;
private System.Windows.Forms.Label lblSettingsLocation;
private System.Windows.Forms.RadioButton rbSettingsInAppDataFolder;
private System.Windows.Forms.RadioButton rbSettingsInExeFolder;
private System.Windows.Forms.CheckBox chkUseOriginalFileNames;
private System.Windows.Forms.CheckBox chkVerifyImageHashes;
private System.Windows.Forms.CheckBox chkSaveThumbnails;
private System.Windows.Forms.CheckBox chkRenameDownloadFolderWithDescription;
}
} | 45.037037 | 110 | 0.737664 | [
"MIT"
] | jdpurcell/ChanThreadWatch | frmSettings.Designer.cs | 10,946 | 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/winioctl.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="VIRTUALIZATION_INSTANCE_INFO_OUTPUT" /> struct.</summary>
public static unsafe partial class VIRTUALIZATION_INSTANCE_INFO_OUTPUTTests
{
/// <summary>Validates that the <see cref="VIRTUALIZATION_INSTANCE_INFO_OUTPUT" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<VIRTUALIZATION_INSTANCE_INFO_OUTPUT>(), Is.EqualTo(sizeof(VIRTUALIZATION_INSTANCE_INFO_OUTPUT)));
}
/// <summary>Validates that the <see cref="VIRTUALIZATION_INSTANCE_INFO_OUTPUT" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(VIRTUALIZATION_INSTANCE_INFO_OUTPUT).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="VIRTUALIZATION_INSTANCE_INFO_OUTPUT" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(VIRTUALIZATION_INSTANCE_INFO_OUTPUT), Is.EqualTo(16));
}
}
| 42.228571 | 145 | 0.750338 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/Windows/um/winioctl/VIRTUALIZATION_INSTANCE_INFO_OUTPUTTests.cs | 1,480 | C# |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace Puppet2D_Poly2Tri
{
public struct FixedBitArray3 : IEnumerable<bool>
{
public bool _0, _1, _2;
public bool this[int index]
{
get
{
switch (index)
{
case 0:
return _0;
case 1:
return _1;
case 2:
return _2;
default:
throw new IndexOutOfRangeException();
}
}
set
{
switch (index)
{
case 0:
_0 = value;
break;
case 1:
_1 = value;
break;
case 2:
_2 = value;
break;
default:
throw new IndexOutOfRangeException();
}
}
}
public bool Contains(bool value)
{
for (int i = 0; i < 3; ++i)
{
if (this[i] == value)
{
return true;
}
}
return false;
}
public int IndexOf(bool value)
{
for (int i = 0; i < 3; ++i)
{
if (this[i] == value)
{
return i;
}
}
return -1;
}
public void Clear()
{
_0 = _1 = _2 = false;
}
public void Clear(bool value)
{
for (int i = 0; i < 3; ++i)
{
if (this[i] == value)
{
this[i] = false;
}
}
}
private IEnumerable<bool> Enumerate()
{
for (int i = 0; i < 3; ++i)
{
yield return this[i];
}
}
public IEnumerator<bool> GetEnumerator() { return Enumerate().GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
} | 30.160584 | 89 | 0.483543 | [
"MIT"
] | elitegoliath/ld43-yank-train | LD43 Yank Train/Assets/Dependencies/Puppet2D/Scripts/Triangulation/Utility/FixedBitArray3.cs | 4,134 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace SisoDb.Diagnostics
{
[Serializable]
public class DiagnosticsGroup
{
private readonly Dictionary<string, DiagnosticsGroup> _groups;
private readonly Dictionary<string, DiagnosticsNode> _nodes;
public string Name { get; private set; }
public bool HasGroups
{
get { return _groups.Any(); }
}
public bool HasNodes
{
get { return _nodes.Any(); }
}
public IEnumerable<DiagnosticsGroup> Groups
{
get { return _groups.Values; }
}
public IEnumerable<DiagnosticsNode> Nodes
{
get { return _nodes.Values; }
}
public DiagnosticsGroup(string name, params object[] formattingArgs)
{
Name = formattingArgs.Any() ? string.Format(name, formattingArgs) : name;
_groups = new Dictionary<string, DiagnosticsGroup>();
_nodes = new Dictionary<string, DiagnosticsNode>();
}
public DiagnosticsGroup AddGroup(string name, params object[] formattingArgs)
{
var group = new DiagnosticsGroup(name, formattingArgs);
_groups.Add(group.Name, group);
return group;
}
public DiagnosticsGroup AddNode(string name, object value)
{
_nodes.Add(name, new DiagnosticsNode(name, value.ToString()));
return this;
}
public DiagnosticsGroup AddNode(string name, string value)
{
_nodes.Add(name, new DiagnosticsNode(name, value));
return this;
}
}
} | 28.721311 | 86 | 0.569064 | [
"MIT"
] | eric-swann-q2/SisoDb-Provider | Source/Projects/SisoDb/Diagnostics/DiagnosticsGroup.cs | 1,752 | C# |
namespace LoopingPattern._01_LoppingTypes._02_OneToMany {
[Microsoft.XLANGs.BaseTypes.SchemaReference(@"LoopingPattern._01_LoppingTypes._01_OneToOne.Survays", typeof(global::LoopingPattern._01_LoppingTypes._01_OneToOne.Survays))]
[Microsoft.XLANGs.BaseTypes.SchemaReference(@"LoopingPattern._01_LoppingTypes._02_OneToMany.Lists", typeof(global::LoopingPattern._01_LoppingTypes._02_OneToMany.Lists))]
public sealed class OneToManyMapReadable : global::Microsoft.XLANGs.BaseTypes.TransformBase {
private const string _strMap = @"<?xml version=""1.0"" encoding=""UTF-16""?>
<xsl:stylesheet xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:msxsl=""urn:schemas-microsoft-com:xslt"" xmlns:var=""http://schemas.microsoft.com/BizTalk/2003/var"" exclude-result-prefixes=""msxsl var s0"" version=""1.0"" xmlns:s0=""http://LoopingPattern.Survays"" xmlns:ns0=""http://LoopingPattern.Lists"">
<xsl:output omit-xml-declaration=""yes"" method=""xml"" version=""1.0"" />
<xsl:template match=""/"">
<xsl:apply-templates select=""/s0:Surveys"" />
</xsl:template>
<xsl:template match=""/s0:Surveys"">
<ns0:Lists>
<xsl:for-each select=""GeneralSurvey"">
<Address>
<xsl:attribute name=""Street"">
<xsl:value-of select=""Address/text()"" />
</xsl:attribute>
<xsl:attribute name=""City"">
<xsl:value-of select=""City/text()"" />
</xsl:attribute>
<xsl:attribute name=""State"">
<xsl:value-of select=""State/text()"" />
</xsl:attribute>
<xsl:attribute name=""PostalCode"">
<xsl:value-of select=""PostalCode/text()"" />
</xsl:attribute>
</Address>
</xsl:for-each>
<xsl:for-each select=""GeneralSurvey"">
<Person>
<xsl:attribute name=""Name"">
<xsl:value-of select=""Name/text()"" />
</xsl:attribute>
</Person>
</xsl:for-each>
</ns0:Lists>
</xsl:template>
</xsl:stylesheet>";
private const string _strArgList = @"<ExtensionObjects />";
private const string _strSrcSchemasList0 = @"LoopingPattern._01_LoppingTypes._01_OneToOne.Survays";
private const global::LoopingPattern._01_LoppingTypes._01_OneToOne.Survays _srcSchemaTypeReference0 = null;
private const string _strTrgSchemasList0 = @"LoopingPattern._01_LoppingTypes._02_OneToMany.Lists";
private const global::LoopingPattern._01_LoppingTypes._02_OneToMany.Lists _trgSchemaTypeReference0 = null;
public override string XmlContent {
get {
return _strMap;
}
}
public override string XsltArgumentListContent {
get {
return _strArgList;
}
}
public override string[] SourceSchemas {
get {
string[] _SrcSchemas = new string [1];
_SrcSchemas[0] = @"LoopingPattern._01_LoppingTypes._01_OneToOne.Survays";
return _SrcSchemas;
}
}
public override string[] TargetSchemas {
get {
string[] _TrgSchemas = new string [1];
_TrgSchemas[0] = @"LoopingPattern._01_LoppingTypes._02_OneToMany.Lists";
return _TrgSchemas;
}
}
}
}
| 41.865854 | 316 | 0.606175 | [
"MIT"
] | sandroasp/BizTalk-Server-Learning-Path | Working-with-Maps/Looping-Pattern/LoopingPattern/01-LoppingTypes/02-OneToMany/OneToManyMapReadable.btm.cs | 3,433 | C# |
using Destiny.Core.Flow.Entity;
namespace Destiny.Core.Flow.Dtos.Functions
{
public abstract class FunctionDtoBase<TKey> : DtoBase<TKey>
{ /// <summary>
/// 功能名字 </summary>
public string Name { get; set; }
/// <summary>
/// 是否可用
/// </summary>
public bool IsEnabled { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 链接Url
/// </summary>
public string LinkUrl { get; set; }
}
} | 22.52 | 63 | 0.50444 | [
"MIT"
] | dotNetTreasury/Destiny.Core.Flow | src/Destiny.Core.Flow.Dtos/Functions/FunctionDtoBase.cs | 589 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Sql.Models
{
public partial class DataMaskingPolicy : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(DataMaskingState))
{
writer.WritePropertyName("dataMaskingState");
writer.WriteStringValue(DataMaskingState.Value.ToSerialString());
}
if (Optional.IsDefined(ExemptPrincipals))
{
writer.WritePropertyName("exemptPrincipals");
writer.WriteStringValue(ExemptPrincipals);
}
writer.WriteEndObject();
writer.WriteEndObject();
}
internal static DataMaskingPolicy DeserializeDataMaskingPolicy(JsonElement element)
{
Optional<string> location = default;
Optional<string> kind = default;
Optional<string> id = default;
Optional<string> name = default;
Optional<string> type = default;
Optional<DataMaskingState> dataMaskingState = default;
Optional<string> exemptPrincipals = default;
Optional<string> applicationPrincipals = default;
Optional<string> maskingLevel = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("location"))
{
location = property.Value.GetString();
continue;
}
if (property.NameEquals("kind"))
{
kind = property.Value.GetString();
continue;
}
if (property.NameEquals("id"))
{
id = property.Value.GetString();
continue;
}
if (property.NameEquals("name"))
{
name = property.Value.GetString();
continue;
}
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("dataMaskingState"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
dataMaskingState = property0.Value.GetString().ToDataMaskingState();
continue;
}
if (property0.NameEquals("exemptPrincipals"))
{
exemptPrincipals = property0.Value.GetString();
continue;
}
if (property0.NameEquals("applicationPrincipals"))
{
applicationPrincipals = property0.Value.GetString();
continue;
}
if (property0.NameEquals("maskingLevel"))
{
maskingLevel = property0.Value.GetString();
continue;
}
}
continue;
}
}
return new DataMaskingPolicy(id.Value, name.Value, type.Value, location.Value, kind.Value, Optional.ToNullable(dataMaskingState), exemptPrincipals.Value, applicationPrincipals.Value, maskingLevel.Value);
}
}
}
| 39.061404 | 215 | 0.477656 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/DataMaskingPolicy.Serialization.cs | 4,453 | 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.Azure.IIoT.Services.OpcUa.Vault {
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Azure.IIoT.AspNetCore.Auth;
using Microsoft.Azure.IIoT.AspNetCore.Auth.Clients;
using Microsoft.Azure.IIoT.AspNetCore.Correlation;
using Microsoft.Azure.IIoT.AspNetCore.Cors;
using Microsoft.Azure.IIoT.Auth;
using Microsoft.Azure.IIoT.Crypto.Default;
using Microsoft.Azure.IIoT.Crypto.KeyVault.Clients;
using Microsoft.Azure.IIoT.Crypto.Storage;
using Microsoft.Azure.IIoT.Diagnostics.AppInsights.Default;
using Microsoft.Azure.IIoT.Http.Default;
using Microsoft.Azure.IIoT.Http.Ssl;
using Microsoft.Azure.IIoT.Messaging.Default;
using Microsoft.Azure.IIoT.Messaging.ServiceBus.Clients;
using Microsoft.Azure.IIoT.Messaging.ServiceBus.Services;
using Microsoft.Azure.IIoT.OpcUa.Api.Registry;
using Microsoft.Azure.IIoT.OpcUa.Api.Registry.Clients;
using Microsoft.Azure.IIoT.OpcUa.Registry.Events.v2;
using Microsoft.Azure.IIoT.OpcUa.Vault.Events;
using Microsoft.Azure.IIoT.OpcUa.Vault.Handler;
using Microsoft.Azure.IIoT.OpcUa.Vault.Services;
using Microsoft.Azure.IIoT.OpcUa.Vault.Storage;
using Microsoft.Azure.IIoT.Serializers;
using Microsoft.Azure.IIoT.Services.OpcUa.Vault.Auth;
using Microsoft.Azure.IIoT.Services.OpcUa.Vault.Runtime;
using Microsoft.Azure.IIoT.Storage.CosmosDb.Services;
using Microsoft.Azure.IIoT.Storage.Default;
using Microsoft.Azure.IIoT.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Prometheus;
using System;
using ILogger = Serilog.ILogger;
/// <summary>
/// Webservice startup
/// </summary>
public class Startup {
/// <summary>
/// Configuration - Initialized in constructor
/// </summary>
public Config Config { get; }
/// <summary>
/// Service info - Initialized in constructor
/// </summary>
public ServiceInfo ServiceInfo { get; } = new ServiceInfo();
/// <summary>
/// Current hosting environment - Initialized in constructor
/// </summary>
public IWebHostEnvironment Environment { get; }
/// <summary>
/// Create startup
/// </summary>
/// <param name="env"></param>
/// <param name="configuration"></param>
public Startup(IWebHostEnvironment env, IConfiguration configuration) :
this(env, new Config(new ConfigurationBuilder()
.AddConfiguration(configuration)
.AddFromDotEnvFile()
.AddEnvironmentVariables()
.AddEnvironmentVariables(EnvironmentVariableTarget.User)
// Above configuration providers will provide connection
// details for KeyVault configuration provider.
.AddFromKeyVault(providerPriority: ConfigurationProviderPriority.Lowest)
.Build())) {
}
/// <summary>
/// Create startup
/// </summary>
/// <param name="env"></param>
/// <param name="configuration"></param>
public Startup(IWebHostEnvironment env, Config configuration) {
Environment = env;
Config = configuration;
}
/// <summary>
/// This is where you register dependencies, add services to the
/// container. This method is called by the runtime, before the
/// Configure method below.
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public void ConfigureServices(IServiceCollection services) {
// services.AddLogging(o => o.AddConsole().AddDebug());
services.AddHeaderForwarding();
services.AddCors();
services.AddHealthChecks();
services.AddDistributedMemoryCache();
services.AddAzureDataProtection(Config.Configuration);
services.AddHttpsRedirect();
services.AddAuthentication()
.AddJwtBearerProvider(AuthProvider.AzureAD)
.AddJwtBearerProvider(AuthProvider.AuthService);
services.AddAuthorizationPolicies(
Policies.RoleMapping,
Policies.CanRead,
Policies.CanWrite,
Policies.CanSign,
Policies.CanManage);
// Add controllers as services so they'll be resolved.
services.AddControllers().AddSerializers();
services.AddSwagger(ServiceInfo.Name, ServiceInfo.Description);
// Enable Application Insights telemetry collection.
services.AddApplicationInsightsTelemetry(Config.InstrumentationKey);
services.AddSingleton<ITelemetryInitializer, ApplicationInsightsTelemetryInitializer>();
}
/// <summary>
/// This method is called by the runtime, after the ConfigureServices
/// method above and used to add middleware
/// </summary>
/// <param name="app"></param>
/// <param name="appLifetime"></param>
public void Configure(IApplicationBuilder app, IHostApplicationLifetime appLifetime) {
var applicationContainer = app.ApplicationServices.GetAutofacRoot();
var log = applicationContainer.Resolve<ILogger>();
app.UsePathBase();
app.UseHeaderForwarding();
app.UseRouting();
app.EnableCors();
app.UseJwtBearerAuthentication();
app.UseAuthorization();
app.UseHttpsRedirect();
app.UseCorrelation();
app.UseSwagger();
app.UseMetricServer();
app.UseHttpMetrics();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
endpoints.MapHealthChecks("/healthz");
});
// If you want to dispose of resources that have been resolved in the
// application container, register for the "ApplicationStopped" event.
appLifetime.ApplicationStopped.Register(applicationContainer.Dispose);
// Print some useful information at bootstrap time
log.Information("{service} web service started with id {id}",
ServiceInfo.Name, ServiceInfo.Id);
}
/// <summary>
/// Autofac configuration.
/// </summary>
/// <param name="builder"></param>
public virtual void ConfigureContainer(ContainerBuilder builder) {
// Register service info and configuration interfaces
builder.RegisterInstance(ServiceInfo)
.AsImplementedInterfaces();
builder.RegisterInstance(Config)
.AsImplementedInterfaces();
builder.RegisterInstance(Config.Configuration)
.AsImplementedInterfaces();
// Add diagnostics
builder.AddDiagnostics(Config);
// Register http client module
builder.RegisterModule<HttpClientModule>();
#if DEBUG
builder.RegisterType<NoOpCertValidator>()
.AsImplementedInterfaces();
#endif
// Add serializers
builder.RegisterModule<MessagePackModule>();
builder.RegisterModule<NewtonSoftJsonModule>();
// Add service to service authentication
builder.RegisterModule<WebApiAuthentication>();
// CORS setup
builder.RegisterType<CorsSetup>()
.AsImplementedInterfaces();
// Add key vault
builder.RegisterModule<KeyVaultClientModule>();
// Crypto services
builder.RegisterType<CertificateDatabase>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<CertificateRevoker>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<CertificateFactory>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<CertificateIssuer>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<KeyDatabase>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<KeyHandleSerializer>()
.AsImplementedInterfaces().SingleInstance();
// TODO: Add keyvault here to override ....
// Register event bus ...
builder.RegisterType<EventBusHost>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<ServiceBusClientFactory>()
.AsImplementedInterfaces();
builder.RegisterType<ServiceBusEventBus>()
.AsImplementedInterfaces().SingleInstance();
// ... subscribe to application events ...
builder.RegisterType<ApplicationEventBusSubscriber>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<RegistryEventHandler>()
.AsImplementedInterfaces();
// Register registry micro services adapters
builder.RegisterType<RegistryServiceClient>()
.AsImplementedInterfaces();
builder.RegisterType<RegistryServicesApiAdapter>()
.AsImplementedInterfaces();
builder.RegisterType<EntityInfoResolver>()
.AsImplementedInterfaces();
// Vault services
builder.RegisterType<RequestDatabase>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<GroupDatabase>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<CertificateRequestEventBroker>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<CertificateRequestManager>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<TrustGroupServices>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<CertificateAuthority>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<KeyPairRequestProcessor>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<SigningRequestProcessor>()
.AsImplementedInterfaces().SingleInstance();
// Vault handler
builder.RegisterType<AutoApproveHandler>()
.AsImplementedInterfaces();
builder.RegisterType<KeyPairRequestHandler>()
.AsImplementedInterfaces();
builder.RegisterType<SigningRequestHandler>()
.AsImplementedInterfaces();
// ... with cosmos db collection as storage
builder.RegisterType<ItemContainerFactory>()
.AsImplementedInterfaces();
builder.RegisterType<CosmosDbServiceClient>()
.AsImplementedInterfaces();
// ... and auto start
builder.RegisterType<HostAutoStart>()
.AutoActivate()
.AsImplementedInterfaces().SingleInstance();
}
}
}
| 41.505263 | 100 | 0.623806 | [
"MIT"
] | GBBBAS/Industrial-IoT | services/src/Microsoft.Azure.IIoT.Services.OpcUa.Vault/src/Startup.cs | 11,829 | C# |
using FleetControl.Application.Notifications.Models;
using System.Threading.Tasks;
namespace FleetControl.Application.Interfaces
{
public interface INotificationService
{
Task SendAsync(Message message);
}
}
| 20.909091 | 53 | 0.765217 | [
"MIT"
] | sdemaine/FleetControl_CQRS | FleetControl.Application.Core/Interfaces/INotificationService.cs | 232 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.ML.Data;
using Microsoft.ML.RunTests;
using Xunit;
namespace Microsoft.ML.Tests.Scenarios.Api
{
public partial class ApiScenariosTests
{
/// <summary>
/// Train with initial predictor: Similar to the simple train scenario, but also accept a pre-trained initial model.
/// The scenario might be one of the online linear learners that can take advantage of this, for example, averaged perceptron.
/// </summary>
[Fact]
public void TrainWithInitialPredictor()
{
var ml = new MLContext(seed: 1, conc: 1);
var data = ml.Data.ReadFromTextFile<SentimentData>(GetDataPath(TestDatasets.Sentiment.trainFilename), hasHeader: true);
// Pipeline.
var pipeline = ml.Transforms.Text.FeaturizeText("SentimentText", "Features");
// Train the pipeline, prepare train set. Since it will be scanned multiple times in the subsequent trainer, we cache the
// transformed data in memory.
var trainData = ml.Data.Cache(pipeline.Fit(data).Transform(data));
// Train the first predictor.
var trainer = ml.BinaryClassification.Trainers.StochasticDualCoordinateAscent("Label", "Features",advancedSettings: s => s.NumThreads = 1);
var firstModel = trainer.Fit(trainData);
// Train the second predictor on the same data.
var secondTrainer = ml.BinaryClassification.Trainers.AveragedPerceptron("Label","Features");
var trainRoles = new RoleMappedData(trainData, label: "Label", feature: "Features");
var finalModel = ((ITrainer)secondTrainer).Train(new TrainContext(trainRoles, initialPredictor: firstModel.Model));
}
}
}
| 43.688889 | 151 | 0.677009 | [
"MIT"
] | xadupre/machinelearning | test/Microsoft.ML.Tests/Scenarios/Api/Estimators/TrainWithInitialPredictor.cs | 1,968 | C# |
using System.Reflection;
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("AWSSDK.CognitoSync")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Cognito Sync. Amazon Cognito is a service that makes it easy to save user data, such as app preferences or game state, in the AWS Cloud without writing any backend code or managing any infrastructure. With Amazon Cognito, you can focus on creating great app experiences instead of having to worry about building and managing a backend solution to handle identity management, network state, storage, and sync.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.100.55")] | 55.375 | 495 | 0.760722 | [
"Apache-2.0"
] | costleya/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/CognitoSync/Properties/AssemblyInfo.cs | 1,772 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using Microsoft.Practices.Prism.Modularity;
namespace Microsoft.Practices.Prism.Composition.Tests.Mocks.Modules
{
public abstract class MockAbstractModule : IModule
{
public void Initialize()
{
}
}
public class MockInheritingModule : MockAbstractModule
{
}
}
| 24 | 121 | 0.712963 | [
"Unlicense"
] | SiddharthMishraPersonal/InterviewPreperation | WPF/Installers/Prism/PrismLibrary/Desktop/Prism.Tests/Mocks/Modules/MockAbstractModule.cs | 432 | C# |
//
// InsertAnonymousMethodSignatureTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.CodeActions
{
[TestFixture]
public class InsertAnonymousMethodSignatureTests : ContextActionTestBase
{
[Test()]
public void Test ()
{
string result = RunContextAction (
new InsertAnonymousMethodSignatureAction (),
"using System;" + Environment.NewLine +
"class TestClass" + Environment.NewLine +
"{" + Environment.NewLine +
" void Test ()" + Environment.NewLine +
" {" + Environment.NewLine +
" EventHandler handler = $delegate {" + Environment.NewLine +
" };" + Environment.NewLine +
" }" + Environment.NewLine +
"}"
);
Assert.AreEqual (
"using System;" + Environment.NewLine +
"class TestClass" + Environment.NewLine +
"{" + Environment.NewLine +
" void Test ()" + Environment.NewLine +
" {" + Environment.NewLine +
" EventHandler handler = delegate(object sender, EventArgs e) {" + Environment.NewLine +
" };" + Environment.NewLine +
" }" + Environment.NewLine +
"}", result);
}
}
}
| 35.5 | 93 | 0.705933 | [
"MIT"
] | 4lab/ILSpy | NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeActions/InsertAnonymousMethodSignatureTests.cs | 2,344 | C# |
using MessagePack;
using SocialPlatform.Groups.Shared.Models;
using System;
namespace SocialPlatform.Groups.Shared.Messages.ServerToClient
{
[MessagePackObject]
public class ReceiveGroupMessage : INetworkMessage
{
public ReceiveGroupMessage() { }
public ReceiveGroupMessage(Guid groupId, GroupMessage message)
{
GroupId = groupId;
Message = message;
}
[Key(0)]
public Guid GroupId { get; set; }
[Key(1)]
public GroupMessage Message { get; set; }
[IgnoreMember]
public byte MessageType => ServerToClientMessageTypes.ReceiveGroupMessage;
public byte[] Serialize()
{
return MessagePackSerializer.Serialize(this);
}
}
}
| 23.606061 | 82 | 0.629012 | [
"MIT"
] | tniemenmaa/SocialPlatform | src/SocialPlatform.Groups.Shared/Messages/ServerToClient/ReceiveGroupMessage.cs | 781 | C# |
// -----------------------------------------------------------------------
// <copyright file="SyntaxNodeExtensions.cs">
// Copyright (c) 2021 Dean Edis. All rights reserved.
// </copyright>
// <summary>
// This code is provided on an "as is" basis and without warranty of any kind.
// We do not warrant or make any representations regarding the use or
// results of use of this code.
// </summary>
// -----------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
using Shrinker.Lexer;
using Shrinker.Parser.SyntaxNodes;
namespace UnitTests.Extensions
{
public static class SyntaxNodeExtensions
{
public static IEnumerable<IToken> NonNullChildTokens(this SyntaxNode root) => root.Children.Where(o => o.Token != null).Select(o => o.Token);
}
} | 36.521739 | 149 | 0.589286 | [
"MIT"
] | deanthecoder/GLSLShaderShrinker | ShaderShrinker/UnitTests/Extensions/SyntaxNodeExtensions.cs | 842 | C# |
// Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespace CorrugatedIron.Models.MapReduce.KeyFilters
{
/// <summary>
/// Turns an integer (previously extracted with string_to_int), into a string.
/// </summary>
internal class IntToString : IRiakKeyFilterToken
{
public string FunctionName
{
get { return "int_to_string"; }
}
public override string ToString()
{
return ToJsonString();
}
public string ToJsonString()
{
var sb = new StringBuilder();
using(var sw = new StringWriter(sb))
using(JsonWriter jw = new JsonTextWriter(sw))
{
jw.WriteStartArray();
jw.WriteValue(FunctionName);
jw.WriteEndArray();
}
return sb.ToString();
}
}
} | 28.763636 | 83 | 0.602402 | [
"Apache-2.0"
] | bryanhunter/CorrugatedIron | CorrugatedIron/Models/MapReduce/KeyFilters/IntToString.cs | 1,582 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.