text stringlengths 13 6.01M |
|---|
//
// commercio.sdk - Sdk for Commercio Network
//
// Riccardo Costacurta
// Dec. 30, 2019
// BlockIt s.r.l.
//
/// Allows to easily create a Did Document and perform common related operations
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using commercio.sacco.lib;
namespace commercio.sdk
{
public class DidDocumentHelper
{
#region Properties
#endregion
#region Constructors
#endregion
#region Public Methods
/// Creates a Did Document from the given [wallet], [pubKeys] and optional [service].
public static DidDocument fromWallet(Wallet wallet, List<PublicKey> pubKeys, List<DidDocumentService> service = null)
{
if (pubKeys.Count < 2)
{
System.ArgumentException argEx = new System.ArgumentException("Argument Exception: DidDocument fromWallet - At least two keys are required ");
throw argEx;
}
//String authKeyId = $"{wallet.bech32Address}#keys-1"; // *** CHeck this !!!
//DidDocumentPublicKey authKey = new DidDocumentPublicKey(
// id: authKeyId,
// type: DidDocumentPubKeyType.SECP256K1,
// controller: wallet.bech32Address,
// publicKeyHex: HexEncDec.ByteArrayToString(wallet.publicKey)
//);
//final otherKeys = mapIndexed(
// pubKeys, (index, item) => _convertKey(item, index + 2, wallet))
// .toList();
// No need to have an util here, I think Linq will do
List<DidDocumentPublicKey> otherKeys = pubKeys.Select(item => _convertKey(item, pubKeys.IndexOf(item) + 1, wallet)).ToList();
DidDocumentProofSignatureContent proofContent = new DidDocumentProofSignatureContent(
context: "https://www.w3.org/ns/did/v1",
id: wallet.bech32Address,
publicKeys: otherKeys
);
String verificationMethod = wallet.bech32PublicKey;
DidDocumentProof proof = _computeProof(proofContent.id, verificationMethod, proofContent, wallet);
return new DidDocument(
context: proofContent.context,
id: proofContent.id,
publicKeys: proofContent.publicKeys,
proof: proof,
service: service
);
}
/// Converts the given [pubKey] into a [DidDocumentPublicKey] placed at position [index],
/// [wallet] used to get the controller field of each [DidDocumentPublicKey].
private static DidDocumentPublicKey _convertKey(PublicKey pubKey, int index, Wallet wallet)
{
return new DidDocumentPublicKey(
id: $"{wallet.bech32Address}#keys-{index}", // *** CHeck this !!!
type: pubKey.getType(),
controller: wallet.bech32Address,
publicKeyPem: pubKey.getEncoded()
);
}
/// Computes the [DidDocumentProof] based on the given [controller], [verificationMethod] and [proofSignatureContent]
static DidDocumentProof _computeProof(
String controller,
String verificationMethod,
DidDocumentProofSignatureContent proofSignatureContent,
Wallet wallet,
String proofPurpose = "authentication")
{
return new DidDocumentProof(
type: "EcdsaSecp256k1VerificationKey2019",
timestamp: GenericUtils.getTimeStamp(),
proofPurpose: proofPurpose,
controller: controller,
verificationMethod: verificationMethod,
signatureValue: Convert.ToBase64String(SignHelper.signSorted(proofSignatureContent.toJson(), wallet))
);
}
#endregion
#region Helpers
#endregion
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.Services.FileSystem.Internal
{
public interface IUserSecurityController
{
/// <summary>
/// Checks if the Current user is Host user or Admin user of the provided portal
/// </summary>
/// <param name="portalId">Portal Id to check Admin users</param>
/// <returns>True if the Current user is Host user or Admin user. False otherwise</returns>
bool IsHostAdminUser(int portalId);
/// <summary>
/// Checks if the provided user is Host user or Admin user of the provided portal
/// </summary>
/// <param name="portalId">Portal Id to check Admin users</param>
/// <param name="userId">User Id to check</param>
/// <returns>True if the user is Host user or Admin user. False otherwise</returns>
bool IsHostAdminUser(int portalId, int userId);
/// <summary>
/// Checks if the provided permission is allowed for the current user in the provided folder
/// </summary>
/// <param name="folder">Folder to check</param>
/// <param name="permissionKey">Permission key to check</param>
/// <returns></returns>
bool HasFolderPermission(IFolderInfo folder, string permissionKey);
}
}
|
using alipay.Lib.Core;
using Aop.Api;
using Aop.Api.Request;
using Aop.Api.Response;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace alipay.WebPage
{
public partial class TestPage : System.Web.UI.Page
{
log4net.ILog log = log4net.LogManager.GetLogger("Log.Logging");
static alipayCore alipaycore;
static TestPage()
{
alipaycore = new alipayCore();
}
protected void Page_Load(object sender, EventArgs e)
{
string code = Request.QueryString["auth_code"];
string state = Request.QueryString["state"];
log.Info("code:" + code + "——state:" + state+"--"+ alipaycore.config.privateKey);
if (!string.IsNullOrEmpty(code))
{
try
{
//string publicKey = ConfigurationManager.AppSettings["publicKey"];
//string privateKey = ConfigurationManager.AppSettings["privateKey"];
//string publicKeyPem = GetCurrentPath() + "public-key.pem";
//string privateKeyPem = GetCurrentPath() + "aop-sandbox-RSA-private-c#.pem";
//log.Info("publicKeyPem:" + publicKeyPem);
//log.Info("privateKeyPem:" + privateKeyPem);
IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", "2017062307553030", alipaycore.config.privateKey, "json", "1.0", "RSA", alipaycore.config.publicKey, "GBK", false);
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.GrantType = "authorization_code";
request.Code = code;
//request.RefreshToken = "201208134b203fe6c11548bcabd8da5bb087a83b";
AlipaySystemOauthTokenResponse response = client.Execute(request);
//Console.WriteLine(response.Body);
string result = response.Body;
JObject jobject= (JObject)JsonConvert.DeserializeObject(result);
JObject temp = (JObject)jobject["alipay_system_oauth_token_response"];
string userid = temp["user_id"].ToString();
log.Info(response.Body);
log.Info("userid:"+userid);
}
catch (Exception err)
{
log.Error("err:", err);
}
}
}
private static string GetCurrentPath()
{
string basePath = System.AppDomain.CurrentDomain.BaseDirectory;
return basePath + @"Key\";
}
}
} |
// -----------------------------------------------------------------------
// <copyright file="Native.Windows.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
namespace Mlos.Core.Windows
{
/// <summary>
/// Windows PInvoke functions.
/// </summary>
internal static unsafe class Native
{
private const string AdvapiLib = "advapi32";
private const string KernelLib = "kernel32";
private const string UserLib = "user32";
internal const int SddlRevision1 = 1;
internal const uint Infinite = 0xFFFFFFFF;
internal const int ErrorSuccess = 0;
internal const int ErrorInsufficientBuffer = 122;
/// <summary>
/// Represents invalid pointer (void *) -1.
/// </summary>
internal static IntPtr InvalidPointer = IntPtr.Subtract(IntPtr.Zero, 1);
#region WinAPI
/// <summary>
/// Creates or opens a named or unnamed file mapping object for a specified file.
/// </summary>
/// <param name="fileHandle"></param>
/// <param name="fileMappingAttributes"></param>
/// <param name="fileMapProtect"></param>
/// <param name="maximumSizeHigh"></param>
/// <param name="maximumSizeLow"></param>
/// <param name="name"></param>
/// <returns></returns>
[DllImport(KernelLib, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SharedMemorySafeHandle CreateFileMapping(
IntPtr fileHandle,
ref SECURITY_ATTRIBUTES fileMappingAttributes,
FileMapProtection fileMapProtect,
uint maximumSizeHigh,
uint maximumSizeLow,
string name);
/// <summary>
/// Opens a named file mapping object.
/// </summary>
/// <param name="desiredAccess"></param>
/// <param name="inheritHandle"></param>
/// <param name="name"></param>
/// <returns></returns>
[DllImport(KernelLib, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SharedMemorySafeHandle OpenFileMapping(
MemoryMappedFileAccess desiredAccess,
bool inheritHandle,
string name);
/// <summary>
/// Maps a view of a file mapping into the address space of a calling process.
/// </summary>
/// <param name="fileMapping"></param>
/// <param name="desiredAccess"></param>
/// <param name="fileOffsetHigh"></param>
/// <param name="fileOffsetLow"></param>
/// <param name="numberOfBytesToMap"></param>
/// <returns></returns>
[DllImport(KernelLib, SetLastError = true)]
internal static extern MemoryMappingSafeHandle MapViewOfFile(
SharedMemorySafeHandle fileMapping,
MemoryMappedFileAccess desiredAccess,
int fileOffsetHigh,
int fileOffsetLow,
int numberOfBytesToMap);
/// <summary>
/// Closes an open object handle.
/// </summary>
/// <param name="handle"></param>
/// <returns></returns>
[DllImport(KernelLib, SetLastError = true)]
internal static extern bool CloseHandle(IntPtr handle);
/// <summary>
/// Retrieves information about a range of pages within the virtual address space of a specified process.
/// </summary>
/// <param name="hProcess"></param>
/// <param name="lpAddress"></param>
/// <param name="lpBuffer"></param>
/// <param name="dwLength"></param>
/// <returns></returns>
[DllImport(KernelLib, SetLastError = true)]
internal static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);
/// <summary>
/// Unmaps a mapped view of a file from the calling process's address space.
/// </summary>
/// <param name="lpBaseAddress"></param>
/// <returns></returns>
[DllImport(KernelLib, SetLastError = true)]
internal static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
/// <summary>
/// Creates or opens a named or unnamed event object.
/// </summary>
/// <param name="fileMappingAttributes"></param>
/// <param name="manualReset"></param>
/// <param name="initialState"></param>
/// <param name="name"></param>
/// <returns></returns>
[DllImport(KernelLib, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern EventSafeHandle CreateEvent(
ref SECURITY_ATTRIBUTES fileMappingAttributes,
bool manualReset,
bool initialState,
string name);
[DllImport(KernelLib, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern EventSafeHandle OpenEvent(EventAccess desiredAccess, bool inheritHandle, string lpName);
[DllImport(KernelLib, SetLastError = true)]
internal static extern bool SetEvent(EventSafeHandle hEvent);
[DllImport(KernelLib, SetLastError = true)]
internal static extern int WaitForSingleObject(EventSafeHandle handle, uint milliseconds);
[DllImport(AdvapiLib, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = false)]
internal static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(
[In] string stringSecurityDescriptor,
[In] uint stringSDRevision,
[Out] out SecurityDescriptorSafePtr securityDescriptor,
[Out] out int securityDescriptorSize);
[DllImport(AdvapiLib, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = false)]
internal static extern bool ConvertSecurityDescriptorToStringSecurityDescriptor(
[In] SecurityDescriptorSafePtr securityDescriptor,
[In] uint stringSDRevision,
[In] SecurityInformation securityInformation,
[Out] out string stringSecurityDescriptor,
[Out] out uint stringSecurityDescriptorLength);
[DllImport(KernelLib, SetLastError = true)]
internal static extern ProcessTokenSafeHandle GetCurrentProcess();
[DllImport(AdvapiLib, PreserveSig = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool OpenProcessToken(
ProcessTokenSafeHandle processHandle,
AccessRights desiredAccess,
out AccessTokenSafeHandle tokenHandle);
[DllImport(AdvapiLib, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = false)]
internal static extern bool GetTokenInformation(
[In] AccessTokenSafeHandle tokenHandle,
[In] TokenInformationClass tokenInformationClass,
[In] IntPtr tokenInformation,
[In] uint tokenInformationLength,
[Out] out uint returnLength);
[DllImport(UserLib, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = false)]
internal static extern bool GetUserObjectSecurity(
[In] IntPtr handle,
ref SecurityInformation securityInformation,
[Out] IntPtr securityDescriptor,
[In] uint securityDescriptorSize,
[Out] out uint lengthNeeded);
[DllImport(AdvapiLib, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool ConvertSidToStringSid(IntPtr pSid, out string strSid);
[DllImport(KernelLib)]
internal static extern LocalAllocSafePtr LocalAlloc(LocalMemoryFlags localMemFlags, uint uBytes);
[DllImport(KernelLib, EntryPoint = "LocalAlloc")]
internal static extern SecurityDescriptorSafePtr AllocSecurityDescriptor(LocalMemoryFlags localMemFlags, uint uBytes);
[DllImport(KernelLib, EntryPoint = "LocalAlloc")]
internal static extern SecurityIdentifierSafePtr AllocSecurityIdentifier(LocalMemoryFlags localMemFlags, uint uBytes);
[DllImport(AdvapiLib, EntryPoint = "GetSecurityInfo", SetLastError = true)]
internal static extern int GetSecurityInfo(
[In] SafeHandle handle,
[In] SecurityObjectType objectType,
[In] SecurityInformation securityInformation,
[In] IntPtr sidOwner,
[In] IntPtr sidGroup,
[In] IntPtr dacl,
[In] IntPtr sacl,
[Out] out SecurityDescriptorSafePtr securityDescriptor);
[DllImport(AdvapiLib, SetLastError = true)]
internal static extern bool GetSecurityDescriptorOwner(
SecurityDescriptorSafePtr pSecurityDescriptor,
out IntPtr owner,
out bool ownerDefaulted);
[DllImport(AdvapiLib, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EqualSid(IntPtr sid1, IntPtr sid2);
/// <summary>
/// Copies a security identifier (SID) to a buffer.
/// </summary>
/// <param name="destinationSidLength"></param>
/// <param name="destinationSid"></param>
/// <param name="sourceSid"></param>
/// <returns></returns>
[DllImport(AdvapiLib, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CopySid(uint destinationSidLength, SecurityIdentifierSafePtr destinationSid, IntPtr sourceSid);
/// <summary>
/// Compares a SID to a well-known SID and returns true if they match.
/// </summary>
/// <param name="sid"></param>
/// <param name="type"></param>
/// <returns></returns>
[DllImport(AdvapiLib, EntryPoint = "IsWellKnownSid", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern bool IsWellKnownSid(IntPtr sid, WellKnownSidType type);
/// <summary>
/// Returns the length, in bytes, of a valid security identifier (SID).
/// </summary>
/// <param name="sid"></param>
/// <returns></returns>
[DllImport(AdvapiLib)]
internal static extern uint GetLengthSid(IntPtr sid);
[DllImport(KernelLib, PreserveSig = true)]
internal static extern IntPtr LocalFree(IntPtr hMem);
#endregion
#region Win32 structures
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct MEMORY_BASIC_INFORMATION
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public AllocationProtectEnum AllocationProtect;
public IntPtr RegionSize;
public StateEnum State;
public AllocationProtectEnum Protect;
public TypeEnum Type;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct SECURITY_DESCRIPTOR
{
public byte Revision;
public byte Size;
public short Control;
public IntPtr Owner;
public IntPtr Group;
public IntPtr Sacl;
public IntPtr Dacl;
}
/// <summary>
/// Used to store security information for creating file handles.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_ATTRIBUTES
{
public uint Length;
public IntPtr SecurityDescriptor;
public bool InheritHandle;
}
internal struct TOKEN_USER
{
public SID_AND_ATTRIBUTES User;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public int Attributes;
}
#endregion
#region Enums
/// <summary>
/// The SecurityInformation data type identifies the object-related security information being set or queried.
/// </summary>
[Flags]
internal enum SecurityInformation : uint
{
/// <summary>
/// OWNER_SECURITY_INFORMATION.
/// The owner identifier of the object is being referenced.
/// </summary>
OwnerSecurityInformation = 0x00000001,
/// <summary>
/// GROUP_SECURITY_INFORMATION.
/// The primary group identifier of the object is being referenced.
/// </summary>
GroupSecurityInformation = 0x00000002,
/// <summary>
/// DACL_SECURITY_INFORMATION.
/// The DACL of the object is being referenced.
/// </summary>
DAclSecurityInformation = 0x00000004,
/// <summary>
/// SACL_SECURITY_INFORMATION.
/// The SACL of the object is being referenced.
/// </summary>
SAclSecurityInformation = 0x00000008,
/// <summary>
/// ATTRIBUTE_SECURITY_INFORMATION.
/// The resource properties of the object being referenced.
/// </summary>
AttributeSecurityInformation = 0x00000020,
/// <summary>
/// SCOPE_SECURITY_INFORMATION.
/// The Central Access Policy (CAP) identifier applicable on the object that is being referenced.
/// </summary>
ScopeSecurityInformation = 0x00000040,
/// <summary>
/// UNPROTECTED_SACL_SECURITY_INFORMATION.
/// The SACL inherits ACEs from the parent object.
/// </summary>
UnprotectedSAclSecurityInformation = 0x10000000,
/// <summary>
/// UNPROTECTED_DACL_SECURITY_INFORMATION.
/// The DACL inherits ACEs from the parent object.
/// </summary>
UnprotectedDAclSecurityInformation = 0x20000000,
/// <summary>
/// PROTECTED_SACL_SECURITY_INFORMATION.
/// The SACL cannot inherit ACEs.
/// </summary>
ProtectedSAclSecurityInformation = 0x40000000,
/// <summary>
/// PROTECTED_DACL_SECURITY_INFORMATION.
/// The DACL cannot inherit access control entries (ACEs).
/// </summary>
ProtectedDAclSecurityInformation = 0x80000000,
}
[Flags]
internal enum EventAccess : uint
{
StandardRightsRequired = 0x000F0000,
Synchronize = 0x00100000,
EvenyModifyState = 0x0002,
EventAllAccess = StandardRightsRequired | Synchronize | 0x3,
}
[Flags]
internal enum MemoryMappedFileAccess : uint
{
SectionQuery = 0x0001,
SectionMapWrite = 0x0002,
SectionMapRead = 0x0004,
SectionMapExecute = 0x0008,
SectionExtendSize = 0x0010,
SectionMapExecuteExplicit = 0x0020,
StandardRightsRequired = 0x000F0000,
SectionAllAccess = StandardRightsRequired | SectionQuery | SectionMapWrite | SectionMapRead | SectionMapExecute | SectionExtendSize,
FileMapWrite = SectionMapWrite,
FileMapRead = SectionMapRead,
FileMapAllAccess = SectionAllAccess,
}
[Flags]
internal enum FileMapProtection : uint
{
PageReadonly = 0x02,
PageReadWrite = 0x04,
PageWriteCopy = 0x08,
PageExecuteRead = 0x20,
PageExecuteReadWrite = 0x40,
SectionCommit = 0x8000000,
SectionImage = 0x1000000,
SectionNoCache = 0x10000000,
SectionReserve = 0x4000000,
}
[Flags]
internal enum AllocationProtectEnum : uint
{
PageExecute = 0x00000010,
PageExecuteRead = 0x00000020,
PageExecuteReadWrite = 0x00000040,
PageExecuteWriteCopy = 0x00000080,
PageNoAccess = 0x00000001,
PageReadOnly = 0x00000002,
PageReadWrite = 0x00000004,
PageWriteCopy = 0x00000008,
PageGuard = 0x00000100,
PageNoCache = 0x00000200,
PageWriteCombine = 0x00000400,
}
[Flags]
internal enum AccessRights : uint
{
/// <summary>
/// Required to delete the object.
/// </summary>
Delete = 0x00010000,
/// <summary>
/// Required to read information in the security descriptor for the object, not including the information in the SACL.
/// </summary>
ReadControl = 0x00020000,
/// <summary>
/// The right to use the object for synchronization. This enables a thread to wait until the object is in the signaled state.
/// </summary>
Synchronize = 0x00100000,
StandardRightsAll = 0x001F0000,
StandardRightsRequired = 0x000F0000,
/// <summary>
/// Modify state access, which is required for the SetEvent, ResetEvent and PulseEvent functions.
/// </summary>
EventModifyState = 0x0002,
/// <summary>
/// All possible access rights for an event object.
/// </summary>
EventAllAccess = 0x001F0003,
TokenAssignPrimary = 0x0001,
TokenDuplicate = 0x0002,
TokenImpersonate = 0x0004,
TokenQuery = 0x0008,
TokenQuerySource = 0x0010,
TokenAdjustPrivileges = 0x0020,
TokenAdjustGroups = 0x0040,
TokenAdjustDefaukt = 0x0080,
TokenAdjustSessionId = 0x0100,
}
[Flags]
internal enum StateEnum : uint
{
MemCommit = 0x1000,
MemFree = 0x10000,
MemReserve = 0x2000,
}
[Flags]
internal enum TypeEnum : uint
{
MemImage = 0x1000000,
MemMapped = 0x40000,
MemPrivate = 0x20000,
}
[Flags]
internal enum LocalMemoryFlags
{
Fixed = 0x0000,
Moveable = 0x0002,
NoCompact = 0x0010,
NoDiscard = 0x0020,
ZeroInit = 0x0040,
Modify = 0x0080,
Discardable = 0x0F00,
ValidFlags = 0x0F72,
InvalidHandle = 0x8000,
LHnd = Moveable | ZeroInit,
LPtr = Fixed | ZeroInit,
NonZeroLHnd = Moveable,
NonZeroLPtr = Fixed,
}
internal enum TokenInformationClass : uint
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
}
internal enum SecurityObjectType
{
SecurityUnknownObjectType = 0,
SecurityFileObject,
SecurityService,
SecurityPrinter,
SecurityRegistryKey,
SecurityLMShare,
SecurityKernelObject,
SecurityWindowObject,
SecurityDirectoryServiceObject,
SecurityDirectoryServiceObjectAll,
SecurityProviderDefinedObject,
SecurityWmiGuidObject,
SecurityRegistryWow6432Key,
}
internal enum WellKnownSidType : uint
{
WinNullSid = 0,
WinWorldSid = 1,
WinLocalSid = 2,
WinCreatorOwnerSid = 3,
WinCreatorGroupSid = 4,
WinCreatorOwnerServerSid = 5,
WinCreatorGroupServerSid = 6,
WinNtAuthoritySid = 7,
WinDialupSid = 8,
WinNetworkSid = 9,
WinBatchSid = 10,
WinInteractiveSid = 11,
WinServiceSid = 12,
WinAnonymousSid = 13,
WinProxySid = 14,
WinEnterpriseControllersSid = 15,
WinSelfSid = 16,
WinAuthenticatedUserSid = 17,
WinRestrictedCodeSid = 18,
WinTerminalServerSid = 19,
WinRemoteLogonIdSid = 20,
WinLogonIdsSid = 21,
WinLocalSystemSid = 22,
WinLocalServiceSid = 23,
WinNetworkServiceSid = 24,
WinBuiltinDomainSid = 25,
WinBuiltinAdministratorsSid = 26,
WinBuiltinUsersSid = 27,
WinBuiltinGuestsSid = 28,
WinBuiltinPowerUsersSid = 29,
WinBuiltinAccountOperatorsSid = 30,
WinBuiltinSystemOperatorsSid = 31,
WinBuiltinPrintOperatorsSid = 32,
WinBuiltinBackupOperatorsSid = 33,
WinBuiltinReplicatorSid = 34,
WinBuiltinPreWindows2000CompatibleAccessSid = 35,
WinBuiltinRemoteDesktopUsersSid = 36,
WinBuiltinNetworkConfigurationOperatorsSid = 37,
WinAccountAdministratorSid = 38,
WinAccountGuestSid = 39,
WinAccountKrbtgtSid = 40,
WinAccountDomainAdminsSid = 41,
WinAccountDomainUsersSid = 42,
WinAccountDomainGuestsSid = 43,
WinAccountComputersSid = 44,
WinAccountControllersSid = 45,
WinAccountCertAdminsSid = 46,
WinAccountSchemaAdminsSid = 47,
WinAccountEnterpriseAdminsSid = 48,
WinAccountPolicyAdminsSid = 49,
WinAccountRasAndIasServersSid = 50,
WinNTLMAuthenticationSid = 51,
WinDigestAuthenticationSid = 52,
WinSChannelAuthenticationSid = 53,
WinThisOrganizationSid = 54,
WinOtherOrganizationSid = 55,
WinBuiltinIncomingForestTrustBuildersSid = 56,
WinBuiltinPerfMonitoringUsersSid = 57,
WinBuiltinPerfLoggingUsersSid = 58,
WinBuiltinAuthorizationAccessSid = 59,
WinBuiltinTerminalServerLicenseServersSid = 60,
}
#endregion
}
/// <summary>
/// Represents an allocated memory.
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class LocalAllocSafePtr : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Initializes a new instance of the <see cref="LocalAllocSafePtr"/> class.
/// Constructor.
/// </summary>
internal LocalAllocSafePtr()
: base(true)
{
}
/// <inheritdoc/>
protected override bool ReleaseHandle()
{
return Native.LocalFree(handle) == IntPtr.Zero;
}
}
/// <summary>
/// Represents an allocated memory for the security descriptor.
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class SecurityDescriptorSafePtr : LocalAllocSafePtr
{
internal static SecurityDescriptorSafePtr Invalid = new SecurityDescriptorSafePtr();
}
/// <summary>
/// Represents an allocated memory for the security identifier (sid).
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class SecurityIdentifierSafePtr : LocalAllocSafePtr
{
}
/// <summary>
/// Shared memory handle.
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class SharedMemorySafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Initializes a new instance of the <see cref="SharedMemorySafeHandle"/> class.
/// </summary>
internal SharedMemorySafeHandle()
: base(true)
{
}
/// <inheritdoc/>
protected override bool ReleaseHandle()
{
return Native.CloseHandle(handle);
}
}
/// <summary>
/// Memory mapping handle.
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class MemoryMappingSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Initializes a new instance of the <see cref="MemoryMappingSafeHandle"/> class.
/// </summary>
public MemoryMappingSafeHandle()
: base(true)
{
}
/// <inheritdoc/>
protected override bool ReleaseHandle()
{
return Native.UnmapViewOfFile(handle);
}
}
/// <summary>
/// Event handle.
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class EventSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Initializes a new instance of the <see cref="EventSafeHandle"/> class.
/// </summary>
internal EventSafeHandle()
: base(true)
{
}
/// <inheritdoc/>
protected override bool ReleaseHandle()
{
return Native.CloseHandle(handle);
}
}
/// <summary>
/// Access token handle.
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class AccessTokenSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Initializes a new instance of the <see cref="AccessTokenSafeHandle"/> class.
/// </summary>
internal AccessTokenSafeHandle()
: base(true)
{
}
/// <inheritdoc/>
protected override bool ReleaseHandle()
{
return Native.CloseHandle(handle);
}
}
/// <summary>
/// Process token handle.
/// </summary>
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class ProcessTokenSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Initializes a new instance of the <see cref="ProcessTokenSafeHandle"/> class.
/// </summary>
public ProcessTokenSafeHandle()
: base(true)
{
}
/// <inheritdoc/>
protected override bool ReleaseHandle()
{
return Native.CloseHandle(handle);
}
}
}
|
// Use Instructions: All obstacles should be generated through
// the use of the DD_GenObstacle class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DD_Obstacle : MonoBehaviour
{
private const int MAX_LEVEL = 3;
private static int mTotalNumObstacles = 0;
private static int mLevelNumber = 0;
public enum ObstacleType // Type to indicate type of obstacle
{
spikeTrap, healSpot, levelExit, dodoEgg, pressurePlate, lever,
doubleDamage, halfDamage, doubleArmor, halfArmor, doubleSpeed,
halfSpeed, healthPotion, hurtPotion, invulnerabilityPotion
};
private ObstacleType mObsType;
public ObstacleType GetObstacleType()
{
return mObsType;
}
public void SetObstacleType(ObstacleType obs)
{
mObsType = obs;
}
public void addObstacle() {
mTotalNumObstacles++;
}
public int getNumObstacles() {
return mTotalNumObstacles;
}
public int getLevelNumber() {
return mLevelNumber;
}
public void nextLevel() {
mLevelNumber++;
}
public int getMaxLevel() {
return MAX_LEVEL;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace BPiaoBao.Common.Enums
{
public enum EnumPnrImportType
{
/// <summary>
/// 白屏预定
/// </summary>
[Description("白屏预定")]
WhiteScreenDestine = 0,
/// <summary>
/// 编码导入
/// </summary>
[Description("编码导入")]
GenericPnrImport = 1,
/// <summary>
/// 儿童编码导入
/// </summary>
[Description("儿童编码导入")]
CHDPnrImport = 2,
/// <summary>
/// 升舱换开
/// </summary>
[Description("升舱换开")]
UpSeatChangePnrImport = 3,
/// <summary>
/// 手机预定
/// </summary>
[Description("手机预定")]
MobileDestine = 4,
/// <summary>
/// PNR内容导入
/// </summary>
[Description(" PNR内容导入")]
PnrContentImport = 5
}
}
|
using UnityEditor;
public static class ClearEditorProgressBar
{
[MenuItem("SNN/ClearEditorProgressBar")]
public static void Clear()
{
EditorUtility.ClearProgressBar();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lance : Piece
{
[SerializeField] public bool promoted;
private Vector3 piecePosition;
public void Awake()
{
this.piecePosition = transform.position;
this.currentX = (int)piecePosition.x;
this.currentY = (int)piecePosition.y;
this.currentZ = (int)piecePosition.z;
this.isPlayer1 = true;
this.selected = false;
this.promoted = false;
this.pt = pieceType.Lance;
}
public void Update()
{
updatePossibleMoves();
}
private void promote()
{
promoted = true;
}
public override void updatePossibleMoves()
{
int boardSize = Game.Board.boardSize;
List<Vector3> moves = new List<Vector3>();
if (isPlayer1)
{
for (int i = 1; i < (boardSize - currentZ); ++i)
{
// if within bounds
if (currentZ + i < boardSize)
{
Piece c = Game.Board.board[currentX, currentY, currentZ + i].Piece;
if (c == null)
{
moves.Add(new Vector3(currentX, currentY, currentZ + i));
}
else if (c.isPlayer1 != isPlayer1)
{
moves.Add(new Vector3(currentX, currentY, currentZ + i));
break;
}
else
{
break;
}
}
}
}
else
{
for (int i = 1; i <= currentZ; ++i)
{
Piece c = Game.Board.board[currentX, currentY, currentZ - i].Piece;
if (c == null)
{
moves.Add(new Vector3(currentX, currentY, currentZ - i));
}
else if (c.isPlayer1 != isPlayer1)
{
moves.Add(new Vector3(currentX, currentY, currentZ - i));
break;
}
else
{
break;
}
}
}
setPossibleMoves(moves);
}
}
|
using System;
namespace WorldHardestGame.Core.Entities
{
public class Coin : BaseEntityIA
{
private static Map _map;
private static int _count;
public Coin(Position position, IA.BaseIA? ia, Rectangle boundingBox, Map map)
: base(position, ia, boundingBox, map)
{
if (!ReferenceEquals(_map, Map))
{
_count = 0;
_map = Map;
_map.FinishedUnlocked = false;
}
_count++;
}
public override bool IsEnnemy
=> false;
protected override void UpdateImpl(TimeSpan deltaTime)
=> IA?.Update(deltaTime);
protected override bool HasContactWith(Player player)
{
if (--_count <= 0)
_map.FinishedUnlocked = true;
IsKilled = true;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
namespace ConsoleApp2_1_
{
class List
{
private static void Add()
{
var theMyLists = new List<MyList>
{
new MyList() { Element = "element 3", Index = 11123},
new MyList() { Element = "element 4", Index = 11213},
new MyList() { Element = "element 5", Index = 11312},
new MyList() { Element = "element 6", Index = 11321}
};
foreach (MyList theMyList in theMyLists)
{
Console.WriteLine(theMyList.Element + " index " + theMyList.Index );
}
}
class MyList
{
public string Element { get; set; }
public int Index { get; set; }
}
static void Main(string[] args)
{
MyList myList1 = new MyList { Index = 12345 };
MyList myList2 = new MyList { Index = 12435 };
myList1.Element = "element 1";
myList2.Element = "element 2";
string element1 = myList1.Element;
string element2 = myList2.Element;
Console.WriteLine(element1);
Console.WriteLine(element2);
Add();
Console.ReadKey();
}
}
}
|
using System;
using MonoTouch.ObjCRuntime;
[assembly: LinkWith ("libGreystripeSDK.a", LinkTarget.ArmV7 | LinkTarget.ArmV6 | LinkTarget.Simulator, ForceLoad = true, Frameworks = "AudioToolbox AVFoundation CoreGraphics MediaPlayer OpenAL QuartzCore SystemConfiguration", LinkerFlags = "-lz -lsqlite3")]
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GoodItem : MonoBehaviour
{
public enum Item { Cherry=0,Gem=1 }
public Item item;
// Start is called before the first frame update
void Start()
{
GetComponent<Animator>().SetInteger("Type", (int)item);
}
public void PickItem()
{
GetComponent<Animator>().SetBool("Pick", true);
}
// Update is called once per frame
private void OnTriggerEnter2D(Collider2D collision)
{
GetComponent<AudioSource>().Play();
if (collision.CompareTag("Player")) { PickItem(); }
}
public void Killme()
{
Destroy(gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MovieCruiserUserStories.DAO;
using MovieCruiserUserStories.Models;
namespace MovieCruiserUserStories.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize(Roles = "Admin")]
public class AdminController : ControllerBase
{
private readonly DbCon con;
public AdminController(DbCon _con)
{
con = _con;
}
[HttpGet]
public IEnumerable<Movies> Get()
{
return con.Movies.ToList();
}
[HttpPut("{id}")]
public string Put(int id,[FromBody]Movies movie)
{
var data = con.Movies.Find(id);
if (data != null)
{
data.Id = movie.Id;
data.Title = movie.Title;
data.BoxOffice = movie.BoxOffice;
data.Active = movie.Active;
data.DateOfLaunch = movie.DateOfLaunch;
data.Genre = movie.Genre;
data.HasTeaser = movie.HasTeaser;
//data.Favorite = movie.Favorite;
con.SaveChanges();
}
else
return "Id is not in the Database";
return "Movie Updated";
}
}
} |
using UnityEngine;
using System.Collections;
public class leafset1Lightup : MonoBehaviour {
public Material litmaterial;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(GoalTracker.goal4){
renderer.material = litmaterial;
}
}
}
|
using System.Xml;
using System.Xml.Serialization;
namespace TestTask.DataClasses
{
public class categoryId
{
[XmlAttribute]
public string type { get; set; }
[XmlText]
public string Value { get; set; }
}
}
|
using System;
using Zillow.Core.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Identity;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Zillow.Core.Constant;
using Zillow.Core.Dto.CreateDto;
using Zillow.Core.Dto.UpdateDto;
using Zillow.Core.Exceptions;
using Zillow.Data.Data;
using Zillow.Data.DbEntity;
using Zillow.Service.Services.EmailServices;
namespace Zillow.Service.Services.UserServices
{
public class UserService : IUserService
{
private readonly UserManager<UserDbEntity> _manager;
private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper;
private readonly IEmailService _emailService;
private readonly EntityNotFoundException _notFoundException;
public UserService(UserManager<UserDbEntity> manager, ApplicationDbContext dbContext, IMapper mapper,
IEmailService emailService)
{
_manager = manager;
_dbContext = dbContext;
_mapper = mapper;
_emailService = emailService;
_notFoundException = new EntityNotFoundException("User");
}
public async Task<PagingViewModel> GetAll(int page, int pageSize)
{
var pagesCount = (int) Math.Ceiling(await _dbContext.Users.CountAsync() / (double) pageSize);
if (page > pagesCount || page < 1)
page = 1;
var skipVal = (page - 1) * pagesCount;
var users = await _dbContext.Users
.Skip(skipVal).Take(pageSize).ToListAsync();
var usersViewModel = _mapper.Map<List<UserViewModel>>(users);
return new PagingViewModel()
{
CurrentPage = page,
PagesCount = pagesCount,
Data = usersViewModel
};
}
public async Task<UserViewModel> Get(string id)
{
var user = await _dbContext.Users.SingleOrDefaultAsync(x => x.Id.Equals(id));
if (user == null) throw _notFoundException;
return _mapper.Map<UserViewModel>(user);
}
public async Task<string> Create(CreateUserDto dto)
{
if (!IsEmailValid(dto.Email))
throw new UserRegistrationException(ExceptionMessage.InvalidEmail);
var createdUser = _mapper.Map<UserDbEntity>(dto);
createdUser.UserName = createdUser.Email;
// if user added not successfully Throw UserRegistrationException
var result = await _manager.CreateAsync(createdUser, dto.Password);
if (result.Succeeded)
{
await _emailService.SendEmail(createdUser.Email, "Welcome Email", "");
return createdUser.Id;
}
var errorsMessage =
result.Errors.Aggregate("", (current, error) => current + $"\n{error.Code}");
throw new UserRegistrationException(errorsMessage);
}
public async Task<string> Update(string id, UpdateUserDto dto, string userId)
{
var oldUser = await _dbContext.Users
.SingleOrDefaultAsync(x => x.Id.Equals(id));
if (oldUser == null) throw _notFoundException;
// Note : We Don't Map (Email) for User , it's unchangeable
// See MapperProfile Line 63
if (!id.Equals(dto.Id))
throw new UpdateEntityException(ExceptionMessage.UpdateEntityIdError);
var updatedUser = _mapper.Map(dto, oldUser);
updatedUser.UpdatedAt = DateTime.Now;
updatedUser.UpdatedBy = userId;
await _manager.UpdateAsync(updatedUser);
return updatedUser.Id;
}
public async Task<string> Delete(string id, string userId)
{
var deletedUser = await _dbContext.Users.SingleOrDefaultAsync(x => x.Id.Equals(id));
if (deletedUser == null) throw _notFoundException;
deletedUser.UpdatedAt = DateTime.Now;
deletedUser.UpdatedBy = userId;
await _manager.UpdateAsync(deletedUser);
return deletedUser.Id;
}
private static bool IsEmailValid(string email)
{
var regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
var match = regex.Match(email);
return match.Success;
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure.Interception;
using System.IO;
using System.Linq;
using Voronov.Nsudotnet.BuildingCompanyIS.DBClasses;
using Voronov.Nsudotnet.BuildingCompanyIS.Interfaces;
namespace Voronov.Nsudotnet.BuildingCompanyIS.Impl
{
class BuildingRepositoryImpl : IBuildingRepository
{
public Building GetBuildingsById(int buildingId)
{
using (var dbConnection = new DatabaseModel())
{
return dbConnection.Buildings.FirstOrDefault(b => b.Id == buildingId);
}
}
public ICollection<Building> GetBuildings()
{
using (var dbConnection = new DatabaseModel())
{
return dbConnection.Buildings.ToList();
}
}
class BuildingAttribute : IAttribute
{
public string Name { get; internal set; }
public string Value { get; internal set; }
internal int Id { get; set; }
internal int BuildingId { get; set;}
internal int CategoryId { get; set; }
}
class WorkProcedure : IWorkProcedure
{
public string Name
{
get { return WorkType.Name; }
}
public DateTime? StartTime
{
get {
if (BuildResult != null)
{
return BuildResult.StartDate;
}
if (BuildPlan != null)
{
return BuildPlan.PlannedStartTime;
}
throw new InvalidDataException();
}
}
public DateTime? EndTime
{
get
{
if (BuildResult != null)
{
return BuildResult.EndDate;
}
if (BuildPlan != null)
{
return BuildPlan.PlannedEndTime;
}
throw new InvalidDataException();
}
}
internal WorkType WorkType { get; set; }
internal BuildPlan BuildPlan { get; set; }
internal BuildResult BuildResult { get; set; }
}
class BuildingResource : IBuildingResource
{
public string Name
{
get { return Resource.Name; }
}
public int? Count
{
get
{
if (ResourcePlan != null)
{
return ResourcePlan.ResourceCount;
}
if (ResourceResult != null)
{
return ResourceResult.ResourceCount;
}
throw new InvalidDataException();
}
}
internal Resource Resource { get; set; }
internal ResourcePlan ResourcePlan { get; set; }
internal ResourceResult ResourceResult { get; set; }
}
public ICollection<IAttribute> GetAttributesByBuildingId(int buildingId)
{
using (var dbConnection = new DatabaseModel())
{
var attributes = dbConnection.BuildingAttributeValues
.Where(e => e.BuildingId == buildingId)
.Join(dbConnection.BuildingAttributes
, c => c.BuildingAttributeId
, cx => cx.Id
, (c, cx) => new {c, cx});
return attributes.ToList().Select(attribute => new BuildingAttribute()
{
Id = attribute.c.BuildingAttributeId,
BuildingId = buildingId,
CategoryId = attribute.c.BuildingCategoryId,
Name = attribute.cx.Name,
Value = attribute.c.Value
}).Cast<IAttribute>().ToList();
}
}
public IDictionary<Building, ICollection<IWorkProcedure>> GetBuildPlansByOrganizationUnitId(int organizationUnitId)
{
using (var dbConnection = new DatabaseModel())
{
var result = new Dictionary<Building, ICollection<IWorkProcedure>>();
var buildings = dbConnection.Buildings.Where(b => b.OrganizationUnitId == organizationUnitId);
foreach (var building in buildings)
{
result.Add(building,_getBuildPlanByBuildingId(building.Id, dbConnection));
}
return result;
}
}
public IDictionary<Building, ICollection<IWorkProcedure>> GetBuildPlansBySiteId(int siteId)
{
using (var dbConnection = new DatabaseModel())
{
var result = new Dictionary<Building, ICollection<IWorkProcedure>>();
var buildings = dbConnection.Buildings.Where(b => b.SiteId == siteId);
foreach (var building in buildings)
{
result.Add(building,_getBuildPlanByBuildingId(building.Id, dbConnection));
}
return result;
}
}
public ICollection<IWorkProcedure> GetBuildPlanByBuildingId(int buildingId)
{
using (var dbConnection = new DatabaseModel())
{
return _getBuildPlanByBuildingId(buildingId, dbConnection);
}
}
private ICollection<IWorkProcedure> _getBuildPlanByBuildingId(int buildingId, DatabaseModel dbConnection)
{
var procedures = dbConnection.BuildPlans.Where(e => e.BuildingId == buildingId)
.Join(dbConnection.WorkTypes,
buildPlan => buildPlan.WorkTypeId,
workType => workType.Id,
(buildPlan, workType) => new { buildPlan, workType });
var result = new List<IWorkProcedure>();
foreach (var procedure in procedures)
{
result.Add(new WorkProcedure()
{
BuildPlan = procedure.buildPlan,
BuildResult = null,
WorkType = procedure.workType
});
}
return result;
}
public ICollection<IBuildingResource> GetResourcesByBuildingId(int buildingId)
{
using (var dbConnections = new DatabaseModel())
{
var resourcesForProcedure = dbConnections.BuildPlans.Where(bp => bp.BuildingId == buildingId)
.Join(
dbConnections.ResourcePlans,
bp => bp.Id,
rp => rp.BuildPlanId,
(bp, rp) => new {bp, rp})
.Join(
dbConnections.Resources,
bprp => bprp.rp.ResourceId,
r => r.Id,
(bprp, r) => new {bprp, r});
var resources = new List<IBuildingResource>();
foreach (var res in resourcesForProcedure)
{
resources.Add(new BuildingResource()
{
Resource = res.r,
ResourcePlan = res.bprp.rp,
ResourceResult = null
});
}
return resources;
}
}
public ICollection<IWorkProcedure> GetPerformedWorkByBuildingId(int buildingId)
{
using (var dbConnection = new DatabaseModel())
{
var allPerformedWork = dbConnection.BuildPlans.Where(e => e.BuildingId == buildingId)
.Join(
dbConnection.BuildResults,
buildPlan => buildPlan.Id,
buildReslt => buildReslt.BuildPlanId,
(buildPlan, buildResult) => new {buildPlan, buildResult})
.Join(
dbConnection.WorkTypes,
performedWork => performedWork.buildResult.WorkTypeId,
workType => workType.Id,
(performedWork, workType) => new {performedWork, workType});
var result = new List<IWorkProcedure>();
foreach (var performed in allPerformedWork)
{
result.Add(new WorkProcedure()
{
BuildPlan = null,
BuildResult = performed.performedWork.buildResult,
WorkType = performed.workType;
});
}
return result;
}
}
public ICollection<IBuildingResource> GetActualResourcesCostByBuildingId(int buildingId)
{
throw new NotImplementedException();
}
public ICollection<Building> GetBuildingsByWorkProcedure(IWorkProcedure procedure, DateTime startTime, DateTime endTime)
{
throw new NotImplementedException();
}
public ICollection<Building> GetBuildingsByWorkProcedure(IWorkProcedure procedure, DateTime startTime, DateTime endTime,
int organizationUnitId)
{
throw new NotImplementedException();
}
public ICollection<IWorkProcedure> GetWorkProceduresNotCompletedInTime()
{
throw new NotImplementedException();
}
public ICollection<IWorkProcedure> GetWorkProceduresNotCompletedInTimeBySiteId(int siteId)
{
throw new NotImplementedException();
}
public ICollection<IWorkProcedure> GetWorkProceduresNotCompletedInTimeByOrganizationUnit(int organizationUnitId)
{
throw new NotImplementedException();
}
public ICollection<IBuildingResource> GetResourcesWithOverExpenditure()
{
throw new NotImplementedException();
}
public ICollection<IBuildingResource> GetResourcesWithOverExpenditureBySiteId(int siteId)
{
throw new NotImplementedException();
}
public ICollection<IBuildingResource> GetResourcesWithOverExpenditureByOrganizationUnitId(int organizationUnitId)
{
throw new NotImplementedException();
}
public IDictionary<IWorkProcedure, Building> GetWorkProcedurePerformedByBrigade(int brigadeId, DateTime startTime, DateTime endTime)
{
throw new NotImplementedException();
}
public IDictionary<Brigade, Building> GetBrigadesPerformedWorkProcedure(IWorkProcedure procedure, DateTime startTime, DateTime endTime)
{
throw new NotImplementedException();
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using TestApplicationDomain.Entities;
using TestApplicationInterface.Repository;
namespace TestApplicationDB.Repository
{
public class Repository<T> : IRepository<T> where T : class
{
private readonly DbFactory _dbFactory;
private DbSet<T> _dbSet;
protected DbSet<T> DbSet
{
get => _dbSet ?? (_dbSet = _dbFactory.DbContext.Set<T>());
}
public Repository(DbFactory dbFactory)
{
_dbFactory = dbFactory;
}
public void Add(T entity)
{
if (typeof(IAuditEntity).IsAssignableFrom(typeof(T)))
{
((IAuditEntity)entity).CreatedDate = DateTime.UtcNow;
}
DbSet.Add(entity);
}
public void Delete(T entity)
{
if (typeof(IDeleteEntity).IsAssignableFrom(typeof(T)))
{
((IDeleteEntity)entity).IsDeleted = true;
DbSet.Update(entity);
}
else
DbSet.Remove(entity);
}
public IQueryable<T> Get(Expression<Func<T, bool>> expression)
{
return DbSet.Where(expression);
}
public async Task<T> GetById(object id)
{
return await DbSet.FindAsync(id);
}
public void Update(T entity)
{
if (typeof(IAuditEntity).IsAssignableFrom(typeof(T)))
{
((IAuditEntity)entity).UpdatedDate = DateTime.UtcNow;
}
DbSet.Update(entity);
}
public IQueryable<T> GetAll(Expression<Func<T, bool>> expression = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, int? skip = null, int? take = null, params string[] includePathTypes)
{
var result = DbSet.Where(expression);
if (skip.HasValue) result = result.Skip(skip.Value);
if (take.HasValue) result = result.Take(take.Value);
if(includePathTypes != null && includePathTypes.Length > 0)
{
foreach (var item in includePathTypes)
{
result = result.Include(item);
}
}
if(orderBy != null)
{
result = orderBy(result);
}
return result;
}
public Task<IQueryable<T>> GetAllAsync(Expression<Func<T, bool>> expression = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, int? skip = null, int? take = null, params string[] includePathTypes)
{
return Task.Run(() => GetAll(expression, orderBy, skip, take, includePathTypes));
}
}
}
|
using System.Collections.Generic;
namespace Grapfs.CriticalNodes
{
public class DictionaryNode
{
string _word;
Dictionary<char, DictionaryNode> _dict; // Slow.
public DictionaryNode Add(char value)
{
// Add individual node as child.
// ... Handle null field.
if (this._dict == null)
{
this._dict = new Dictionary<char, DictionaryNode>();
}
// Look up and return if possible.
DictionaryNode result;
if (this._dict.TryGetValue(value, out result))
{
return result;
}
// Store.
result = new DictionaryNode();
this._dict[value] = result;
return result;
}
public DictionaryNode Get(char value)
{
// Get individual child node.
if (this._dict == null)
{
return null;
}
DictionaryNode result;
if (this._dict.TryGetValue(value, out result))
{
return result;
}
return null;
}
public void SetWord(string word)
{
this._word = word;
}
public string GetWord()
{
return this._word;
}
}
} |
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Meziantou.Analyzer.Rules;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class ParameterAttributeForRazorComponentAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor s_supplyParameterFromQueryRule = new(
RuleIdentifiers.SupplyParameterFromQueryRequiresParameterAttributeForRazorComponent,
title: "Parameters with [SupplyParameterFromQuery] attributes should also be marked as [Parameter]",
messageFormat: "Parameters with [SupplyParameterFromQuery] attributes should also be marked as [Parameter]",
RuleCategories.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "",
helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.SupplyParameterFromQueryRequiresParameterAttributeForRazorComponent));
private static readonly DiagnosticDescriptor s_supplyParameterFromQueryRoutableRule = new(
RuleIdentifiers.SupplyParameterFromQueryRequiresRoutableComponent,
title: "Parameters with [SupplyParameterFromQuery] attributes are only valid in routable components (@page)",
messageFormat: "Parameters with [SupplyParameterFromQuery] attributes are only valid in routable components (@page)",
RuleCategories.Design,
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: "",
helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.SupplyParameterFromQueryRequiresRoutableComponent));
private static readonly DiagnosticDescriptor s_editorRequiredRule = new(
RuleIdentifiers.EditorRequiredRequiresParameterAttributeForRazorComponent,
title: "Parameters with [EditorRequired] attributes should also be marked as [Parameter]",
messageFormat: "Parameters with [EditorRequired] attributes should also be marked as [Parameter]",
RuleCategories.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "",
helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.EditorRequiredRequiresParameterAttributeForRazorComponent));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_supplyParameterFromQueryRule, s_editorRequiredRule, s_supplyParameterFromQueryRoutableRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterCompilationStartAction(ctx =>
{
var analyzerContext = new AnalyzerContext(ctx.Compilation);
if (analyzerContext.IsValid)
{
ctx.RegisterSymbolAction(analyzerContext.AnalyzeProperty, SymbolKind.Property);
}
});
}
private sealed class AnalyzerContext
{
private static readonly Version Version8 = new(8, 0);
public AnalyzerContext(Compilation compilation)
{
ParameterSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.ParameterAttribute");
SupplyParameterFromQuerySymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.SupplyParameterFromQueryAttribute");
EditorRequiredSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.EditorRequiredAttribute");
RouteAttributeSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.RouteAttribute");
AspNetCoreVersion = SupplyParameterFromQuerySymbol?.ContainingAssembly.Identity.Version;
}
public Version? AspNetCoreVersion { get; }
public INamedTypeSymbol? ParameterSymbol { get; }
public INamedTypeSymbol? SupplyParameterFromQuerySymbol { get; }
public INamedTypeSymbol? EditorRequiredSymbol { get; }
public INamedTypeSymbol? RouteAttributeSymbol { get; }
public bool IsValid => ParameterSymbol != null && (SupplyParameterFromQuerySymbol != null || EditorRequiredSymbol != null);
internal void AnalyzeProperty(SymbolAnalysisContext context)
{
// note: All attributes are sealed, no need for checking inherited types
var property = (IPropertySymbol)context.Symbol;
// https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-8-preview-6/?WT.mc_id=DT-MVP-5003978#cascade-query-string-values-to-blazor-components
if (AspNetCoreVersion < Version8)
{
if (property.HasAttribute(SupplyParameterFromQuerySymbol, inherits: false))
{
if (!property.HasAttribute(ParameterSymbol, inherits: false))
{
context.ReportDiagnostic(s_supplyParameterFromQueryRule, property);
}
if (!property.ContainingType.HasAttribute(RouteAttributeSymbol))
{
context.ReportDiagnostic(s_supplyParameterFromQueryRoutableRule, property);
}
}
}
if (property.HasAttribute(EditorRequiredSymbol, inherits: false))
{
if (!property.HasAttribute(ParameterSymbol, inherits: false))
{
context.ReportDiagnostic(s_editorRequiredRule, property);
}
}
}
}
}
|
using UnityEngine;
using System;
public class AttackController : MonoBehaviour
{
[SerializeField] AimController m_AimControl;
const float ATTACK_MOVEDIR_SQR = 0.4f * 0.4f;
const float AIM_MOVEDIR_SQR = 0.4f * 0.4f;
public struct Args
{
public bool IsAttack;
public bool ClickAttack;
public Vector3 AttackDir;
}
public event Action<Args> AttackEvents;
void CallEvent(Args args)
{
if (AttackEvents != null) AttackEvents(args);
}
Args m_DeferredArgs;
bool m_DeferredEvent;
void OnAttackTouchEvents(TouchPad.Args args)
{
if(args.IsStart)
{
m_BeginAttack = true;
}
else if (args.IsEnd)
{
var dir = args.EndMoveDir;
bool clickAttack = dir.sqrMagnitude < ATTACK_MOVEDIR_SQR;
//прицельный выстрел или быстрый тап
bool attack = (!clickAttack && m_BeginAim) || (clickAttack && !m_BeginAim);
SetDefault();
m_DeferredEvent = true;
m_DeferredArgs.ClickAttack = clickAttack;
m_DeferredArgs.IsAttack = attack;
if (!clickAttack)
{
m_DeferredArgs.AttackDir = RotateByCamera(dir);
}
}
}
bool m_BeginAttack;
bool m_BeginAim;
public void SetDefault()
{
m_BeginAttack = false;
m_BeginAim = false;
m_DeferredEvent = false;
m_AimControl.Active(false);
}
TouchPad Joy { get { return JoysticksManager.AttackJoystick; } }
public void Init(Transform target)
{
m_AimControl.SetTarget(target);
Joy.TouchEvent -= OnAttackTouchEvents;
Joy.TouchEvent += OnAttackTouchEvents;
}
protected Vector3 RotateByCamera(Vector2 move)
{
var rot = ManagerCameras.GetMainCameraTransform().rotation;
Vector3 forw = rot * Vector3.forward;
Vector3 right = rot * Vector3.right;
Vector3 dir;
dir.x = forw.x * move.y + right.x * move.x;
dir.y = 0f;
dir.z = forw.z * move.y + right.z * move.x;
return dir;
}
public void ManualUpdate ()
{
if (m_DeferredEvent)
{
m_DeferredEvent = false;
CallEvent(m_DeferredArgs);
}
if (!m_BeginAttack) return;
var dir = Joy.MotionDir;
bool aim = dir.sqrMagnitude >= AIM_MOVEDIR_SQR;
if (aim) m_BeginAim = true;
m_AimControl.Active(aim);
if (aim)
{
m_AimControl.ManualUpdate(RotateByCamera(dir));
}
}
}
|
using GameTimeClient.Tracking.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace GameTime.IO
{
/// <summary>
/// Class handling all state and communication between client and
/// server.
/// </summary>
class GameTimeConnection
{
private HttpClient httpGT = new HttpClient();
public GameTimeConnection()
{
httpGT.BaseAddress = new Uri("http://localhost:8282");
}
private JsonSerializerSettings jsonSettings =
new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
public bool sendSlices(Dictionary<String, List<TimeSlice>> slices)
{
try
{
//String jsonSlices = JsonConvert.SerializeObject(slices);
//Console.WriteLine(jsonSlices);
var postResponse = httpGT.PostAsJsonAsync("/", slices).Result;
return postResponse.StatusCode == System.Net.HttpStatusCode.OK;
//TODO: * build HTTPS url with auth token
// * deal with token renewal, etc.
// -> This should be handled in a separate wrapper
// class.
// GameTimeConnection.upload(jsonSlices)
//return true;
}
catch (Exception e)
{
Console.WriteLine("Failed to upload slices: {0}", e.Message);
}
return false;
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreController : MonoBehaviour {
public Text scoreText;
private long score;
public void AddScore (long scoreToAdd) {
score += scoreToAdd;
UpdateScore ();
}
public void UpdateScore () {
scoreText.text = "SCORE: " + score;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Platformer.Mechanics
{
public class PlayerAggro : MonoBehaviour
{
public float aggroRange;
public LayerMask enemyLayerMask = 8;
public LayerMask hittableLayerMask;
PlayerController playerController;
List<Collider2D> enemiesToAggro = new List<Collider2D>();
List<Collider2D> oldEnemiesToAggro = new List<Collider2D>();
void Start() {
playerController = GetComponent<PlayerController>();
}
public void findEnemies(){
if(playerController.controlEnabled){
Collider2D[] entitiesFound = Physics2D.OverlapCircleAll(transform.position, aggroRange, enemyLayerMask);
enemiesToAggro.Clear();
for(int i = 0; i < entitiesFound.Length; i++){
if(entitiesFound[i].gameObject.CompareTag("enemy") || entitiesFound[i].gameObject.CompareTag("Boss")){
Vector3 direction = transform.position - entitiesFound[i].transform.position;
RaycastHit2D hit = Physics2D.Raycast(entitiesFound[i].transform.position,direction,aggroRange,hittableLayerMask);
Debug.DrawLine(entitiesFound[i].transform.position, hit.point, Color.red);
if(hit != false && hit.collider.name == gameObject.name){
enemiesToAggro.Add(entitiesFound[i]);
}
}
}
}
}
public void toUpdate(){
oldEnemiesToAggro = new List<Collider2D>(enemiesToAggro);
findEnemies();
foreach(Collider2D oldEnemy in oldEnemiesToAggro)
{
if(!enemiesToAggro.Contains(oldEnemy))
{
if(oldEnemy != null)
oldEnemy.GetComponent<EnemyAggro>().StopAggro();
}
}
foreach(Collider2D enemy in enemiesToAggro)
{
enemy.GetComponent<EnemyAggro>().aggroedPlayer = gameObject.transform;
enemy.GetComponent<EnemyAggro>().AggroRoutine();
}
}
void OnDrawGizmosSelected() {
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, aggroRange);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Abogado
{
public partial class Generador_de_Reporte : Form
{
public Generador_de_Reporte()
{
InitializeComponent();
}
private void Generador_de_Reporte_Load(object sender, EventArgs e)
{
// TODO: esta línea de código carga datos en la tabla 'ProcesosDataSet4.Clientes' Puede moverla o quitarla según sea necesario.
this.ClientesTableAdapter.Fill(this.ProcesosDataSet4.Clientes);
this.reportViewer1.RefreshReport();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StopLightStrategy.Enum;
using StopLightStrategy.Interfaces;
namespace StopLightStrategy.Classes
{
public class YellowLight : ILight
{
public bool CanBuild(int signalId)
{
return signalId == (int) SignalColor.Yellow;
}
public SignalReaction BuildSignalReaction()
{
SignalReaction reaction = new SignalReaction
{
LightColor = SignalColor.Yellow.ToString(),
Reaction = "Slow down."
};
return reaction;
}
}
}
|
using UnityEngine;
using System;
using System.Collections.Generic;
/// <summary>
/// The Phylogenetic tree composed of Genotypes.
/// </summary>
[Serializable]
public class Phylogeny
{
/// The time when the simulation ended for this population sample.
private readonly int _cutoffTime;
// The Genotypes in the phylogeny. Unique ID mapped to a unique Genotype.
private Dictionary<int, Genotype> _population;
// The attribute name associated with an Attribute object.
// The key is the attribute name found in the Avida files.
private readonly MapList <string, AvidaAttribute> _genotypeAttributes;
/// <summary>
/// Sets up the phylogeny to start adding Genotypes. Genotypes should be added via Genotype constructor.
/// </summary>
/// <param name="rawPopulation">Raw population.</param>
public Phylogeny(MapList<string, AvidaAttribute> genoAttribNames, int cutoffTime, int startCapacity=5000)
{
_cutoffTime = cutoffTime;
_genotypeAttributes = genoAttribNames;
_population = new Dictionary<int, Genotype>(startCapacity);
}
/// <summary>
/// Links the Genotype parents to children from the raw population.
/// </summary>
public bool CreateHierarchy()
{
foreach (Genotype geno in _population.Values) {
// Ignore first born since it has no parent.
if (geno.ID == MainAttributeValues.FirstBornID)
continue;
// Obtain the parent and link it to the child.
Genotype parent = null;
if (!_population.TryGetValue(geno.ParentID, out parent)) {
Debug.Log("Failed to find parent (id=" + geno.ParentID + ") for Genotype (id =" + geno.ID + ") when constructing phylogeny hierarchy.");
return false;
}
geno.SetParent(parent);
}
return true;
}
/// <summary>
/// Gets the first born Genotype.
/// </summary>
/// <returns></returns>
public Genotype GetRoot()
{
return _population[MainAttributeValues.FirstBornID];
}
/// <summary>
/// The time when the simulation ended for this population sample.
/// </summary>
public int CutoffTime
{
get { return _cutoffTime; }
}
/// <summary>
/// The Genotypes in the phylogeny. Associated to a unique ID.
/// </summary>
public Dictionary<int, Genotype> Population
{
get { return _population; }
}
/// <summary>
/// The attribute name associated with an Attribute object.
/// </summary>
public MapList<string, AvidaAttribute> GenotypeAttributes
{
get { return _genotypeAttributes; }
}
}
|
using AcessarCep.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AcessarCep.Interfaces
{
public interface ICepService
{
public Task<Address> GetAddress(string cep);
}
}
|
using Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace EFDataAccess.Configurations
{
public class TagConfiguration : IEntityTypeConfiguration<Tag>
{
public void Configure(EntityTypeBuilder<Tag> builder)
{
builder.HasMany(t=> t.PostTags).WithOne(pt => pt.Tag).HasForeignKey(pt => pt.TagId).OnDelete(DeleteBehavior.Cascade);
builder.Property(t => t.Content).HasMaxLength(15).IsRequired();
builder.HasIndex(t => t.Content).IsUnique();
builder.Property(t => t.IsDeleted).IsRequired().HasDefaultValue(true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ast.Models;
using Ast.IBll;
using Ast.Common;
using System.Configuration;
namespace Ast.UI.Controllers
{
public class LoginController : Controller
{
private IOTAUsersService userservice { get; set; }
private IOTALoginLogService logservice { get; set; }
// GET: Loginasdad
public ActionResult Index()
{
ViewBag.Title = ConfigurationManager.AppSettings["webtitle"];
ViewBag.Name = ConfigurationManager.AppSettings["webname"];
ViewBag.Version = ConfigurationManager.AppSettings["webversion"];
ViewBag.Company = ConfigurationManager.AppSettings["company"];
ViewBag.Url = ConfigurationManager.AppSettings["weburl"];
return View();
}
public JsonResult Go(LoginUser user)
{
user.PassWord = CommFun.Md5(user.PassWord);
var userinfo = userservice.GetSingle(u => u.LoginName == user.LoginName && u.PassWord == user.PassWord && u.IsDel == 0);
var log = new OTALoginLog()
{
IP = CommFun.GetIPAddress(),
LoginName = user.LoginName,
Memo = "帐号或密码错误",
UserId = 0,
AddTime = DateTime.Now,
ModifyTime = DateTime.Now
};
if (userinfo == null)
{
logservice.Add(log);
return Json(new { success = false, msg = "帐号或密码错误!" }, JsonRequestBehavior.AllowGet);
}
Session["LoginUser"] = userinfo;
Session.Timeout = 60;
log.LoginName = userinfo.LoginName;
log.OTAMSGUID = userinfo.OTAMSGUID;
log.UserId = userinfo.Id;
log.Memo = "登录成功";
logservice.Add(log);
return Json(new
{
success = true,
msg = "登录成功!",
uid = userinfo.Id
}, JsonRequestBehavior.AllowGet);
}
}
} |
using System;
using System.Collections.Generic;
namespace RMAT3.Models
{
public class EventType
{
public EventType()
{
AuditTypes = new List<AuditType>();
EventTaskTypes = new List<EventTaskType>();
}
public int EventTypeId { get; set; }
public string AddedByUserId { get; set; }
public DateTime AddTs { get; set; }
public string UpdatedByUserId { get; set; }
public string UpdatedCommentTxt { get; set; }
public DateTime UpdatedTs { get; set; }
public bool IsActiveInd { get; set; }
public DateTime EffectiveFromDt { get; set; }
public decimal? EffectiveToDt { get; set; }
public string EventTypeCd { get; set; }
public string EventTypeLTxt { get; set; }
public string EventTypeTxt { get; set; }
public virtual ICollection<AuditType> AuditTypes { get; set; }
public virtual ICollection<EventTaskType> EventTaskTypes { get; set; }
}
}
|
using System;
using UnityEngine;
namespace RO
{
[CustomLuaClass]
public class RoleRender_Alpha
{
private float timeElapsed;
public float from
{
get;
private set;
}
public float to
{
get;
private set;
}
public float current
{
get;
private set;
}
public float duration
{
get;
private set;
}
public bool on
{
get
{
return this.running || 1f > this.current;
}
}
public bool running
{
get
{
return this.current != this.to;
}
}
public RoleRender_Alpha()
{
this.from = 1f;
this.to = 1f;
this.current = 1f;
}
public void SetDuration(float d)
{
this.duration = d;
if (0f >= this.duration)
{
this.current = this.to;
}
}
public void LerpTo(float t, float d)
{
if (this.to != t)
{
this.from = this.current;
this.to = t;
this.timeElapsed = 0f;
}
this.SetDuration(d);
}
public void LerpTo(float f, float t, float d)
{
if (f != t)
{
this.from = f;
this.to = t;
this.current = f;
this.timeElapsed = 0f;
}
this.SetDuration(d);
}
public void Update()
{
if (0f < this.duration)
{
this.current = Mathf.Lerp(this.from, this.to, this.timeElapsed / this.duration);
this.timeElapsed += Time.get_deltaTime();
}
else
{
this.current = this.to;
}
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
//
using ppatierno.AzureSBLite;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
namespace Microsoft.IoT.Connections.Azure
{
public sealed class TokenProvider
{
public static string CreateSharedAcessSignatureToken(Uri serviceBusNamespaceUri,
string eventHubName,
string publisher,
string keyName,
string keyValue,
TimeSpan tokenTimeToLive)
{
try
{
string token = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
serviceBusNamespaceUri,
eventHubName,
publisher,
keyName,
keyValue,
tokenTimeToLive);
return token;
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
throw ex;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuickGraph;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Settings;
using Microsoft.Pex.Framework.Exceptions;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PexAPIWrapper;
using QuickGraph.Interfaces;
using QuickGraph.Utility;
using Microsoft.ExtendedReflection.Interpretation.Interpreter;
using QuickGraphTest.Factories;
namespace QuickGraphTest
{
[PexClass(typeof(QuickGraph.UndirectedGraph<int, Edge<int>>))]
[TestClass]
public partial class UndirectedGraphCommuteTest
{
[PexMethod]
public void PUT_CommutativityAddVertexAddVertexComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
PexSymbolicValue.Minimize(node1);
PexSymbolicValue.Minimize(node2);
UndirectedGraph<int, Edge<int>> g2 = g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexAssume.IsTrue(node1 > -11 && node1 < 11);
PexAssume.IsTrue(node2 > -11 && node2 < 11);
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
AssumePrecondition.IsTrue(true);
g1.AddVertex(node1);
g1.AddVertex(node2);
g2.AddVertex(node2);
g2.AddVertex(node1);
//NotpAssume.IsTrue(eq.Equals(g1, g2));
//try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexRemoveVertexComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexAssume.IsTrue(node1 > -11 && node1 < 11);
PexAssume.IsTrue(node2 > -11 && node2 < 11);
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( (g1.ContainsVertex(node2) && (((!(g1.ContainsVertex(node1)))))) );
bool rv1 = true, rv2 = true;
g1.AddVertex(node1);
rv1 = g1.RemoveVertex(node2);
rv2 = g2.RemoveVertex(node2);
g2.AddVertex(node1);
NotpAssume.IsTrue(rv1 == rv2 && eq.Equals(g1, g2));
try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(rv1 == rv2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexClearAdjacentEdgesComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexAssume.IsTrue(node1 > -11 && node1 < 11);
PexAssume.IsTrue(node2 > -11 && node2 < 11);
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
//try
//{
AssumePrecondition.IsTrue( (g1.ContainsVertex(node2) && (((!(g1.ContainsVertex(node1)))))) );
//}
//catch { throw new PexAssumeFailedException(); }
g1.AddVertex(node1);
g1.ClearAdjacentEdges(node2);
g2.ClearAdjacentEdges(node2);
g2.AddVertex(node1);
NotpAssume.IsTrue(eq.Equals(g1, g2));
try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexContainsEdgeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node, [PexAssumeNotNull]Edge<int> e)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexAssume.IsTrue(node > -11 && node < 11);
PexAssume.IsTrue(e.Source > -11 && e.Source < 11);
PexAssume.IsTrue(e.Target > -11 && e.Target < 11);
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_SourceNode", e.Source);
PexObserve.ValueForViewing("$input_TargetNode", e.Target);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
PexObserve.ValueForViewing("$input_ContainsNodeSrc", g1.ContainsVertex(e.Source));
PexObserve.ValueForViewing("$input_ContainsNodeTar", g1.ContainsVertex(e.Target));
PexObserve.ValueForViewing("$input_ContainsEdge", g1.ContainsVertex(e.Source) && g1.ContainsVertex(e.Target) ? g1.ContainsEdge(e.Source, e.Target) : false);
//try
//{
AssumePrecondition.IsTrue( (g1.ContainsVertex(e.Source) && (((!(g1.ContainsVertex(node)))))) );
//}
//catch { throw new PexAssumeFailedException(); }
bool ce1 = true, ce2 = true;
g1.AddVertex(node);
ce1 = g1.ContainsEdge(e.Source, e.Target);
ce2 = g2.ContainsEdge(e.Source, e.Target);
g2.AddVertex(node);
NotpAssume.IsTrue(ce1 == ce2 && eq.Equals(g1, g2));
try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(ce1 == ce2 && eq.Equals(g1, g2));
}
//[PexMethod(TestEmissionFilter= PexTestEmissionFilter.All)]
[PexMethod] // All failures
public void PUT_CommutativityAddVertexAdjacentEdgeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1/*, [PexAssumeNotNull]QuickGraph.UndirectedGraph<int, Edge<int>> g2*/, int node1, int node2, int index)
{
//PexSymbolicValue.Minimize(node1);
PexAssume.IsTrue(node1 > -11 && node1 < 11);
PexAssume.IsTrue(node2 > -11 && node2 < 11);
PexAssume.IsTrue(index >= 0 && index <= 11);
UndirectedGraph<int, Edge<int>> g2 = g1.Clone();
UndirectedGraphEqualityComparer eq1 = new UndirectedGraphEqualityComparer();
//PexAssume.IsTrue(eq1.Equals(g1, g2) && !PexAssume.ReferenceEquals(g1,g2));
EdgeEqualityComparer eqc2 = new EdgeEqualityComparer();
//PexAssume.IsTrue(node1 > -11 && node1 < 11);
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_Index", index);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
//AssumePrecondition.IsTrue(true);
AssumePrecondition.IsTrue(true);
g1.AddVertex(node1);
Edge<int> ae1 = g1.AdjacentEdge(node2, index);
Edge<int> ae2 = g2.AdjacentEdge(node2, index);
g2.AddVertex(node1);
//NotpAssume.IsTrue(eqc2.Equals(ae1, ae2) && eq1.Equals(g1, g2));
//try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(eqc2.Equals(ae1,ae2) && eq1.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexIsVerticesEmptyComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexAssume.IsTrue(node > -101 && node < 101);
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
//try
//{
AssumePrecondition.IsTrue(true);
//}
//catch { throw new PexAssumeFailedException(); }
bool ive1 = true, ive2 = true;
g1.AddVertex(node);
ive1 = g1.IsVerticesEmpty;
ive2 = g2.IsVerticesEmpty;
g2.AddVertex(node);
//NotpAssume.IsTrue(ive1 == ive2 && eq.Equals(g1, g2));
//try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(ive1 == ive2 && eq.Equals(g1, g2));
}
[PexMethod] // All exceptions
public void PUT_CommutativityAddVertexVertexCountComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
//try
//{
AssumePrecondition.IsTrue( false);
//}
//catch { throw new PexAssumeFailedException(); }
int vc1 = 0, vc2 = 0;
g1.AddVertex(node);
vc1 = g1.VertexCount;
vc2 = g2.VertexCount;
g2.AddVertex(node);
NotpAssume.IsTrue(vc1 == vc2 && eq.Equals(g1, g2));
try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(vc1 == vc2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexContainsVertexComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
//PexAssume.IsTrue(node1 > -11 && node1 < 11);
//PexAssume.IsTrue(node2 > -11 && node2 < 11);
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
//try
//{
AssumePrecondition.IsTrue( ((!(node1 == node2))) );
//}
//catch { throw new PexAssumeFailedException(); }
bool cv1 = true, cv2 = true;
g1.AddVertex(node1);
cv1 = g1.ContainsVertex(node2);
cv2 = g2.ContainsVertex(node2);
g2.AddVertex(node1);
NotpAssume.IsTrue(cv1 == cv2 && eq.Equals(g1, g2));
try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(cv1 == cv2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexAddEdgeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node, int src, int tar/*, [PexAssumeNotNull]Edge<int> e*/)
{
Edge<int> e = new Edge<int>(src, tar);
UndirectedGraph<int, Edge<int>> g2 = g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexAssume.IsTrue(node > -11 && node < 11);
PexAssume.IsTrue(e.Source > -11 && e.Source < 11);
PexAssume.IsTrue(e.Target > -11 && e.Target < 11);
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_SourceNode", e.Source);
PexObserve.ValueForViewing("$input_TargetNode", e.Target);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
PexObserve.ValueForViewing("$input_ContainsNodeSrc", g1.ContainsVertex(e.Source));
PexObserve.ValueForViewing("$input_ContainsNodeTar", g1.ContainsVertex(e.Target));
PexObserve.ValueForViewing("$input_ContainsEdge", g1.ContainsVertex(e.Source) && g1.ContainsVertex(e.Target) ? g1.ContainsEdge(e.Source, e.Target) : false);
//try
//{
AssumePrecondition.IsTrue( (g1.ContainsEdge(e) && (((!(g1.ContainsVertex(node)))))) );
//}
//catch { throw new PexAssumeFailedException(); }
bool ae1 = true, ae2 = true;
ae1 = g1.AddEdge(e);
g1.AddVertex(node);
g2.AddVertex(node);
ae2 = g2.AddEdge(e);
NotpAssume.IsTrue(ae1 == ae2 && eq.Equals(g1, g2));
try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(ae1 == ae2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexRemoveEdgeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node, int src, int tar)
{
Edge<int> e = new Edge<int>(src, tar);
UndirectedGraph<int, Edge<int>> g2 = g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexAssume.IsTrue(node > -11 && node < 11);
PexAssume.IsTrue(e.Source > -11 && e.Source < 11);
PexAssume.IsTrue(e.Target > -11 && e.Target < 11);
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_SourceNode", e.Source);
PexObserve.ValueForViewing("$input_TargetNode", e.Target);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
PexObserve.ValueForViewing("$input_ContainsNodeSrc", g1.ContainsVertex(e.Source));
PexObserve.ValueForViewing("$input_ContainsNodeTar", g1.ContainsVertex(e.Target));
PexObserve.ValueForViewing("$input_ContainsEdge", g1.ContainsVertex(e.Source) && g1.ContainsVertex(e.Target) ? g1.ContainsEdge(e.Source, e.Target) : false);
AssumePrecondition.IsTrue(true);
bool re1 = true, re2 = true;
g1.AddVertex(node);
re1 = g1.RemoveEdge(e);
re2 = g2.RemoveEdge(e);
g2.AddVertex(node);
NotpAssume.IsTrue(re1 == re2 && eq.Equals(g1, g2));
try{PexAssert.IsTrue(false);}catch{return;}
PexAssert.IsTrue(re1 == re2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexIsEdgesEmptyComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
AssumePrecondition.IsTrue( ((!(g1.ContainsVertex(node)))) );
bool iee1 = true, iee2 = true;
g1.AddVertex(node);
iee1 = g1.IsEdgesEmpty;
iee2 = g2.IsEdgesEmpty;
g2.AddVertex(node);
NotpAssume.IsTrue(iee1 == iee2 && eq.Equals(g1, g2));
PexAssert.IsTrue(iee1 == iee2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexEdgeCountComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
AssumePrecondition.IsTrue( ((!(g1.ContainsVertex(node)))) );
int ec1 = 0, ec2 = 0;
g1.AddVertex(node);
ec1 = g1.EdgeCount;
ec2 = g2.EdgeCount;
g2.AddVertex(node);
NotpAssume.IsTrue(ec1 == ec2 && eq.Equals(g1, g2));
PexAssert.IsTrue(ec1 == ec2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexAdjacentEdgesComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( (g1.ContainsVertex(node2) && (((!(g1.ContainsVertex(node1)))))) );
g1.AddVertex(node1);
var ae1 = g1.AdjacentEdges(node2);
var ae2 = g2.AdjacentEdges(node2);
g2.AddVertex(node1);
bool equal = true;
if (ae1.Count() != ae2.Count())
{
equal = false;
}
for (int i = 0; i < ae1.Count(); i++)
{
if (ae1.ElementAt(i).Source != ae2.ElementAt(i).Source || ae1.ElementAt(i).Source != ae2.ElementAt(i).Source)
{
equal = false;
}
}
NotpAssume.IsTrue(equal && eq.Equals(g1, g2));
PexAssert.IsTrue(equal && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexAdjacentDegreeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( (g1.ContainsVertex(node2) && (((!(g1.ContainsVertex(node1)))))) );
int ad1 = 0, ad2 = 0;
g1.AddVertex(node1);
ad1 = g1.AdjacentDegree(node2);
ad2 = g2.AdjacentDegree(node2);
g2.AddVertex(node1);
NotpAssume.IsTrue(ad1 == ad2 && eq.Equals(g1, g2));
PexAssert.IsTrue(ad1 == ad2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityAddVertexIsAdjacentEdgesEmptyComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( (g1.ContainsVertex(node2) && (((!(g1.ContainsVertex(node1)))))) );
bool iaee1 = true, iaee2 = true;
g1.AddVertex(node1);
iaee1 = g1.IsAdjacentEdgesEmpty(node2);
iaee2 = g2.IsAdjacentEdgesEmpty(node2);
g2.AddVertex(node1);
NotpAssume.IsTrue(iaee1 == iaee2 && eq.Equals(g1, g2));
PexAssert.IsTrue(iaee1 == iaee2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexRemoveVertexComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( ((!(node1 == node2)) && ((g1.ContainsVertex(node1) && ((g1.ContainsVertex(node2)))))) );
bool rv11 = true, rv12 = true, rv21 = true, rv22 = true;
rv11 = g1.RemoveVertex(node1);
rv12 = g1.RemoveVertex(node2);
rv22 = g2.RemoveVertex(node2);
rv21 = g2.RemoveVertex(node1);
NotpAssume.IsTrue(rv11 == rv21 && rv12 == rv22 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv11 == rv21 && rv12 == rv22 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexClearAdjacentEdgesComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( false);
bool rv1 = true, rv2 = true;
rv1 = g1.RemoveVertex(node1);
g1.ClearAdjacentEdges(node2);
g2.ClearAdjacentEdges(node2);
rv2 = g2.RemoveVertex(node1);
NotpAssume.IsTrue(rv1 == rv2 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexAdjacentEdgeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2, int index)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq1 = new UndirectedGraphEqualityComparer();
EdgeEqualityComparer eq2 = new EdgeEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_Index", index);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( false);
bool rv1 = true, rv2 = true;
rv1 = g1.RemoveVertex(node1);
var ae1 = g1.AdjacentEdge(node2, index);
var ae2 = g2.AdjacentEdge(node2, index);
rv2 = g2.RemoveVertex(node1);
NotpAssume.IsTrue(rv1 == rv2 && eq2.Equals(ae1, ae2) && eq1.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && eq2.Equals(ae1, ae2) && eq1.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexIsVerticesEmptyComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
AssumePrecondition.IsTrue( false);
bool rv1 = true, rv2 = true, ive1 = true, ive2 = true;
rv1 = g1.RemoveVertex(node);
ive1 = g1.IsVerticesEmpty;
ive2 = g2.IsVerticesEmpty;
rv2 = g2.RemoveVertex(node);
NotpAssume.IsTrue(rv1 == rv2 && ive1 == ive2 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && ive1 == ive2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexVertexCountComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
AssumePrecondition.IsTrue( false);
bool rv1 = true, rv2 = true;
int vc1 = 0, vc2 = 0;
rv1 = g1.RemoveVertex(node);
vc1 = g1.VertexCount;
vc2 = g2.VertexCount;
rv2 = g2.RemoveVertex(node);
NotpAssume.IsTrue(rv1 == rv2 && vc1 == vc2 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && vc1 == vc2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexContainsVertexComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( (g1.IsEdgesEmpty && (((!(node1 == node2))))) );
bool rv1 = true, rv2 = true, cv1 = true, cv2 = true;
rv1 = g1.RemoveVertex(node1);
cv1 = g1.ContainsVertex(node2);
cv2 = g2.ContainsVertex(node2);
rv2 = g2.RemoveVertex(node1);
NotpAssume.IsTrue(rv1 == rv2 && cv1 == cv2 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && cv1 == cv2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexAddEdgeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node, [PexAssumeNotNull]Edge<int> e)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_SourceNode", e.Source);
PexObserve.ValueForViewing("$input_TargetNode", e.Target);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
PexObserve.ValueForViewing("$input_ContainsNodeSrc", g1.ContainsVertex(e.Source));
PexObserve.ValueForViewing("$input_ContainsNodeTar", g1.ContainsVertex(e.Target));
PexObserve.ValueForViewing("$input_ContainsEdge", g1.ContainsVertex(e.Source) && g1.ContainsVertex(e.Target) ? g1.ContainsEdge(e.Source, e.Target) : false);
AssumePrecondition.IsTrue( false);
bool rv1 = true, rv2 = true, ae1 = true, ae2 = true;
rv1 = g1.RemoveVertex(node);
ae1 = g1.AddEdge(e);
ae2 = g2.AddEdge(e);
rv2 = g2.RemoveVertex(node);
NotpAssume.IsTrue(rv1 == rv2 && ae1 == ae2 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && ae1 == ae2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexRemoveEdgeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node, [PexAssumeNotNull]Edge<int> e)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_SourceNode", e.Source);
PexObserve.ValueForViewing("$input_TargetNode", e.Target);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
PexObserve.ValueForViewing("$input_ContainsNodeSrc", g1.ContainsVertex(e.Source));
PexObserve.ValueForViewing("$input_ContainsNodeTar", g1.ContainsVertex(e.Target));
PexObserve.ValueForViewing("$input_ContainsEdge", g1.ContainsVertex(e.Source) && g1.ContainsVertex(e.Target) ? g1.ContainsEdge(e.Source, e.Target) : false);
AssumePrecondition.IsTrue( false);
bool rv1 = true, rv2 = true, re1 = true, re2 = true;
rv1 = g1.RemoveVertex(node);
re1 = g1.RemoveEdge(e);
re2 = g2.RemoveEdge(e);
rv2 = g2.RemoveVertex(node);
NotpAssume.IsTrue(rv1 == rv2 && re1 == re2 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && re1 == re2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexIsEdgesEmptyComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
AssumePrecondition.IsTrue( (g1.IsEdgesEmpty && (((!(g1.IsVerticesEmpty))))) );
bool rv1 = true, rv2 = true, iee1 = true, iee2 = true;
rv1 = g1.RemoveVertex(node);
iee1 = g1.IsEdgesEmpty;
iee2 = g2.IsEdgesEmpty;
rv2 = g2.RemoveVertex(node);
NotpAssume.IsTrue(rv1 == rv2 && iee1 == iee2 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && iee1 == iee2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexEdgeCountComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree", g1.ContainsVertex(node) ? g1.AdjacentDegree(node) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
AssumePrecondition.IsTrue( (g1.IsEdgesEmpty && ((g1.ContainsVertex(node)))) );
bool rv1 = true, rv2 = true;
int ec1 = 0, ec2 = 0;
rv1 = g1.RemoveVertex(node);
ec1 = g1.EdgeCount;
ec2 = g2.EdgeCount;
rv2 = g2.RemoveVertex(node);
NotpAssume.IsTrue(rv1 == rv2 && ec1 == ec2 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && ec1 == ec2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexAdjacentEdgesComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree1", g1.ContainsVertex(node1) ? g1.AdjacentDegree(node1) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegree2", g1.ContainsVertex(node2) ? g1.AdjacentDegree(node2) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( false);
bool rv1 = true, rv2 = true;
rv1 = g1.RemoveVertex(node1);
var ae1 = g1.AdjacentEdges(node2);
var ae2 = g2.AdjacentEdges(node2);
rv2 = g2.RemoveVertex(node1);
bool equal = true;
if (ae1.Count() != ae2.Count())
{
equal = false;
}
for (int i = 0; i < ae1.Count(); i++)
{
if (ae1.ElementAt(i).Source != ae2.ElementAt(i).Source || ae1.ElementAt(i).Source != ae2.ElementAt(i).Source)
{
equal = false;
}
}
NotpAssume.IsTrue(rv1 == rv2 && equal && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 == rv2 && equal && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityRemoveVertexIsAdjacentEdgesEmptyComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree1", g1.ContainsVertex(node1) ? g1.AdjacentDegree(node1) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegree2", g1.ContainsVertex(node2) ? g1.AdjacentDegree(node2) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( false);
bool rv1 = true, rv2 = true, iaee1 = true, iaee2 = true;
rv1 = g1.RemoveVertex(node1);
iaee1 = g1.IsAdjacentEdgesEmpty(node2);
iaee2 = g2.IsAdjacentEdgesEmpty(node2);
rv2 = g2.RemoveVertex(node1);
NotpAssume.IsTrue(rv1 ==rv2 && iaee1 == iaee2 && eq.Equals(g1, g2));
PexAssert.IsTrue(rv1 ==rv2 && iaee1 == iaee2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityClearAdjacentEdgesClearAdjacentEdgesComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree1", g1.ContainsVertex(node1) ? g1.AdjacentDegree(node1) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegree2", g1.ContainsVertex(node2) ? g1.AdjacentDegree(node2) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue( (g1.IsEdgesEmpty && (((!(g1.IsVerticesEmpty))))) );
g1.ClearAdjacentEdges(node1);
g1.ClearAdjacentEdges(node2);
g2.ClearAdjacentEdges(node2);
g2.ClearAdjacentEdges(node1);
NotpAssume.IsTrue(eq.Equals(g1, g2));
PexAssert.IsTrue(eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityClearAdjacentEdgesIsVerticesEmptyComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree", g1.ContainsVertex(node) ? g1.AdjacentDegree(node) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
AssumePrecondition.IsTrue(true);
bool ive1 = true, ive2 = true;
g1.ClearAdjacentEdges(node);
ive1 = g1.IsVerticesEmpty;
ive2 = g2.IsVerticesEmpty;
g2.ClearAdjacentEdges(node);
//NotpAssume.IsTrue(ive1 == ive2 && eq.Equals(g1, g2));
PexAssert.IsTrue(ive1 == ive2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityClearAdjacentEdgesVertexCountComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree", g1.ContainsVertex(node) ? g1.AdjacentDegree(node) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
AssumePrecondition.IsTrue(true);
int vc1 = 0, vc2 = 0;
g1.ClearAdjacentEdges(node);
vc1 = g1.VertexCount;
vc2 = g2.VertexCount;
g2.ClearAdjacentEdges(node);
//NotpAssume.IsTrue(vc1 == vc2 && eq.Equals(g1, g2));
PexAssert.IsTrue(vc1 == vc2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityClearAdjacentEdgesContainsVertexComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree1", g1.ContainsVertex(node1) ? g1.AdjacentDegree(node1) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegree2", g1.ContainsVertex(node2) ? g1.AdjacentDegree(node2) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue(true);
bool cv1 = true, cv2 = true;
g1.ClearAdjacentEdges(node1);
cv1 = g1.ContainsVertex(node2);
cv2 = g2.ContainsVertex(node2);
g2.ClearAdjacentEdges(node1);
//NotpAssume.IsTrue(cv1 == cv2 && eq.Equals(g1, g2));
PexAssert.IsTrue(cv1 == cv2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityClearAdjacentEdgesAddEdgeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node, [PexAssumeNotNull]Edge<int> e)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_SourceNode", e.Source);
PexObserve.ValueForViewing("$input_TargetNode", e.Target);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegreeNode", g1.ContainsVertex(node) ? g1.AdjacentDegree(node) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegreeNodeSrc", g1.ContainsVertex(e.Source) ? g1.AdjacentDegree(e.Source) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegreeNodeTar", g1.ContainsVertex(e.Target) ? g1.AdjacentDegree(e.Target) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
PexObserve.ValueForViewing("$input_ContainsNodeSrc", g1.ContainsVertex(e.Source));
PexObserve.ValueForViewing("$input_ContainsNodeTar", g1.ContainsVertex(e.Target));
PexObserve.ValueForViewing("$input_ContainsEdge", g1.ContainsVertex(e.Source) && g1.ContainsVertex(e.Target) ? g1.ContainsEdge(e.Source, e.Target) : false);
AssumePrecondition.IsTrue(true);
bool ae1 = true, ae2 = true;
g1.ClearAdjacentEdges(node);
ae1 = g1.AddEdge(e);
ae2 = g2.AddEdge(e);
g2.ClearAdjacentEdges(node);
//NotpAssume.IsTrue(ae1 == ae2 && eq.Equals(g1, g2));
PexAssert.IsTrue(ae1 == ae2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityClearAdjacentEdgesRemoveEdgeComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node, [PexAssumeNotNull]Edge<int> e)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_SourceNode", e.Source);
PexObserve.ValueForViewing("$input_TargetNode", e.Target);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegreeNode", g1.ContainsVertex(node) ? g1.AdjacentDegree(node) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegreeNodeSrc", g1.ContainsVertex(e.Source) ? g1.AdjacentDegree(e.Source) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegreeNodeTar", g1.ContainsVertex(e.Target) ? g1.AdjacentDegree(e.Target) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
PexObserve.ValueForViewing("$input_ContainsNodeSrc", g1.ContainsVertex(e.Source));
PexObserve.ValueForViewing("$input_ContainsNodeTar", g1.ContainsVertex(e.Target));
PexObserve.ValueForViewing("$input_ContainsEdge", g1.ContainsVertex(e.Source) && g1.ContainsVertex(e.Target) ? g1.ContainsEdge(e.Source, e.Target) : false);
AssumePrecondition.IsTrue(true);
bool re1 = true, re2 = true;
g1.ClearAdjacentEdges(node);
re1 = g1.RemoveEdge(e);
re2 = g2.RemoveEdge(e);
g2.ClearAdjacentEdges(node);
//NotpAssume.IsTrue(re1 == re2 && eq.Equals(g1, g2));
PexAssert.IsTrue(re1 == re2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityClearAdjacentEdgesIsEdgesEmptyComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node", node);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree", g1.ContainsVertex(node) ? g1.AdjacentDegree(node) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode", g1.ContainsVertex(node));
AssumePrecondition.IsTrue(true);
bool iee1 = true, iee2 = true;
g1.ClearAdjacentEdges(node);
iee1 = g1.IsEdgesEmpty;
iee2 = g2.IsEdgesEmpty;
g2.ClearAdjacentEdges(node);
//NotpAssume.IsTrue(iee1 == iee2 && eq.Equals(g1, g2));
PexAssert.IsTrue(iee1 == iee2 && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityClearAdjacentEdgesAdjacentEdgesComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree1", g1.ContainsVertex(node1) ? g1.AdjacentDegree(node1) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegree2", g1.ContainsVertex(node2) ? g1.AdjacentDegree(node2) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue(true);
g1.ClearAdjacentEdges(node1);
var ae1 = g1.AdjacentEdges(node2);
var ae2 = g2.AdjacentEdges(node2);
g2.ClearAdjacentEdges(node1);
bool equal = true;
if (ae1.Count() != ae2.Count())
{
equal = false;
}
for (int i = 0; i < ae1.Count(); i++)
{
if (ae1.ElementAt(i).Source != ae2.ElementAt(i).Source || ae1.ElementAt(i).Source != ae2.ElementAt(i).Source)
{
equal = false;
}
}
//NotpAssume.IsTrue(equal && eq.Equals(g1, g2));
PexAssert.IsTrue(equal && eq.Equals(g1, g2));
}
[PexMethod]
public void PUT_CommutativityClearAdjacentEdgesIsAdjacentEdgesEmptyComm([PexAssumeUnderTest] QuickGraph.UndirectedGraph<int, Edge<int>> g1, int node1, int node2)
{
UndirectedGraph<int, Edge<int>> g2 = (UndirectedGraph<int, Edge<int>>)g1.Clone();
UndirectedGraphEqualityComparer eq = new UndirectedGraphEqualityComparer();
PexObserve.ValueForViewing("$input_Node1", node1);
PexObserve.ValueForViewing("$input_Node2", node2);
PexObserve.ValueForViewing("$input_VertexCount", g1.VertexCount);
PexObserve.ValueForViewing("$input_EdgeCount", g1.EdgeCount);
PexObserve.ValueForViewing("$input_AdjacentDegree1", g1.ContainsVertex(node1) ? g1.AdjacentDegree(node1) : 0);
PexObserve.ValueForViewing("$input_AdjacentDegree2", g1.ContainsVertex(node2) ? g1.AdjacentDegree(node2) : 0);
PexObserve.ValueForViewing("$input_IsVerticesEmpty", g1.IsVerticesEmpty);
PexObserve.ValueForViewing("$input_IsEdgesEmpty", g1.IsEdgesEmpty);
PexObserve.ValueForViewing("$input_AllowParallelEdges", g1.AllowParallelEdges);
PexObserve.ValueForViewing("$input_ContainsNode1", g1.ContainsVertex(node1));
PexObserve.ValueForViewing("$input_ContainsNode2", g1.ContainsVertex(node2));
AssumePrecondition.IsTrue(true);
bool iaee1 = true, iaee2 = true;
g1.ClearAdjacentEdges(node1);
iaee1 = g1.IsAdjacentEdgesEmpty(node2);
iaee2 = g2.IsAdjacentEdgesEmpty(node2);
g2.ClearAdjacentEdges(node1);
//NotpAssume.IsTrue(iaee1 == iaee2 && eq.Equals(g1, g2));
PexAssert.IsTrue(iaee1 == iaee2 && eq.Equals(g1, g2));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using TQVaultAE.Domain.Contracts.Services;
using TQVaultAE.Domain.Exceptions;
using TQVaultAE.Domain.Results;
using TQVaultAE.Presentation;
using TQVaultAE.Domain.Entities;
using TQVaultAE.Domain.Helpers;
using System.Reflection;
namespace TQVaultAE.Services.Win32;
/// <summary>
/// Win32 IGamePathResolver implementation
/// </summary>
public class GamePathServiceWin : IGamePathService
{
private const StringComparison noCase = StringComparison.OrdinalIgnoreCase;
internal const string LOCAL_GIT_REPOSITORY_DIRNAME = "LocalGitRepository";
internal const string VAULTFILES_DEFAULT_DIRNAME = @"TQVaultData";
internal const string SAVEDATA_DIRNAME = @"SaveData";
internal const string SAVE_DIRNAME_TQ = @"Titan Quest";
internal const string SAVE_DIRNAME_TQIT = @"Titan Quest - Immortal Throne";
internal const string ARCHIVE_DIRNAME = @"ArchivedCharacters";
public string ArchiveDirName => ARCHIVE_DIRNAME;
public string VaultFilesDefaultDirName => VAULTFILES_DEFAULT_DIRNAME;
public string SaveDataDirName => SAVEDATA_DIRNAME;
public string SaveDirNameTQIT => SAVE_DIRNAME_TQIT;
public string SaveDirNameTQ => SAVE_DIRNAME_TQ;
internal const string TRANSFERSTASHFILENAME = "winsys.dxb";
internal const string RELICVAULTSTASHFILENAME = "miscsys.dxb";
internal const string PLAYERSAVEFILENAME = "Player.chr";
internal const string PLAYERSTASHFILENAMEB = "winsys.dxb";
internal const string PLAYERSTASHFILENAMEG = "winsys.dxg";
internal const string PLAYERSETTINGSFILENAME = "settings.txt";
internal const string VAULTFILENAME_EXTENSION_OLD = ".vault";
internal const string VAULTFILENAME_EXTENSION_JSON = ".vault.json";
public string VaultFileNameExtensionJson => VAULTFILENAME_EXTENSION_JSON;
public string VaultFileNameExtensionOld => VAULTFILENAME_EXTENSION_OLD;
private readonly ILogger Log;
private readonly ITQDataService TQData;
public GamePathServiceWin(ILogger<GamePathServiceWin> log, ITQDataService tQDataService)
{
this.Log = log;
this.TQData = tQDataService;
}
string _ResolveTQVaultPath;
private string ResolveTQVaultPath
{
get
{
if (string.IsNullOrWhiteSpace(_ResolveTQVaultPath))
{
var currentPath = new System.Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath;
_ResolveTQVaultPath = Path.GetDirectoryName(currentPath);
}
return _ResolveTQVaultPath;
}
}
public string LocalGitRepositoryDirectory => Path.Combine(ResolveTQVaultPath, LOCAL_GIT_REPOSITORY_DIRNAME);
public string LocalGitRepositoryGitDir => Path.Combine(ResolveTQVaultPath, LOCAL_GIT_REPOSITORY_DIRNAME, @".git");
public bool LocalGitRepositoryGitDirExist => Directory.Exists(LocalGitRepositoryGitDir);
/// <summary>
/// Parses filename to try to determine the base character name.
/// </summary>
/// <param name="filename">filename of the character file</param>
/// <returns>string containing the character name</returns>
public string GetNameFromFile(string filename)
{
// Strip off the filename
string basePath = Path.GetDirectoryName(filename);
// Get the containing folder
string charName = Path.GetFileName(basePath);
if (charName.ToUpperInvariant() == "SYS")
{
string fileAndExtension = Path.GetFileName(filename);
if (fileAndExtension.ToUpperInvariant().Contains("MISC"))
// Check for the relic vault stash.
charName = Resources.GlobalRelicVaultStash;
else if (fileAndExtension.ToUpperInvariant().Contains("WIN"))
// Check for the transfer stash.
charName = Resources.GlobalTransferStash;
else
charName = null;
}
else if (charName.StartsWith("_", StringComparison.Ordinal))
// See if it is a character folder.
charName = charName.Substring(1);
else
// The name is bogus so return a null.
charName = null;
return charName;
}
/// <summary>
/// Name of the vault folder
/// </summary>
private string _VaultFolder;
/// <summary>
/// Gets the Immortal Throne Character save folder.
/// Resolve as "%USERPROFILE%\Documents\My Games\Titan Quest - Immortal Throne".
/// </summary>
public string SaveFolderTQIT
=> Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games", SAVE_DIRNAME_TQIT);
/// <summary>
/// Gets the Titan Quest Character save folder.
/// Resolve as "%USERPROFILE%\Documents\My Games\Titan Quest".
/// </summary>
public string SaveFolderTQ
=> Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games", SAVE_DIRNAME_TQ);
/// <summary>
/// Gets the name of the game settings file.
/// </summary>
public string SettingsFileTQ
=> Path.Combine(SaveFolderTQ, "Settings", "options.txt");
/// <summary>
/// Gets the name of the game settings file.
/// </summary>
public string SettingsFileTQIT
=> Path.Combine(SaveFolderTQIT, "Settings", "options.txt");
/// <summary>
/// Gets or sets the Titan Quest game path.
/// </summary>
public string GamePathTQ { get; set; }
/// <summary>
/// Gets or sets the Immortal Throne game path.
/// </summary>
public string GamePathTQIT { get; set; }
/// <summary>
/// Gets the filename for the game's transfer stash.
/// Stash files for Mods all have their own subdirectory which is the same as the mod's custom map folder
/// </summary>
public string TransferStashFileFullPath
{
get
{
if (IsCustom)
return Path.Combine(SaveFolderTQIT, SAVEDATA_DIRNAME, "Sys", Path.GetFileName(MapName), TRANSFERSTASHFILENAME);
return Path.Combine(SaveFolderTQIT, SAVEDATA_DIRNAME, "Sys", TRANSFERSTASHFILENAME);
}
}
/// <summary>
/// Gets the filename for the game's relic vault stash.
/// Stash files for Mods all have their own subdirectory which is the same as the mod's custom map folder
/// </summary>
public string RelicVaultStashFileFullPath
{
get
{
if (IsCustom)
return Path.Combine(SaveFolderTQIT, SAVEDATA_DIRNAME, "Sys", Path.GetFileName(MapName), RELICVAULTSTASHFILENAME);
return Path.Combine(SaveFolderTQIT, SAVEDATA_DIRNAME, "Sys", RELICVAULTSTASHFILENAME);
}
}
public string GetBaseCharacterFolder(bool IsTQIT, bool isArchive)
{
return GetBaseCharacterFolder(IsTQIT, this.IsCustom, isArchive);
}
public string GetBaseCharacterFolder(bool IsTQIT, bool isCustomCharacter, bool isArchive)
{
string mapSaveFolder = "Main";
if (isCustomCharacter)
mapSaveFolder = "User";
if (IsTQIT)
{
if (isArchive)
return Path.Combine(SaveFolderTQIT, SAVEDATA_DIRNAME, mapSaveFolder, this.ArchiveDirName);
else
return Path.Combine(SaveFolderTQIT, SAVEDATA_DIRNAME, mapSaveFolder);
}
else
{
if (isArchive)
return Path.Combine(SaveFolderTQ, SAVEDATA_DIRNAME, mapSaveFolder, this.ArchiveDirName);
else
return Path.Combine(SaveFolderTQ, SAVEDATA_DIRNAME, mapSaveFolder);
}
}
public string ArchiveTogglePath(string oldFolder)
{
// Case insensitive replace
string newFolder;
if (oldFolder.ContainsIgnoreCase(this.ArchiveDirName))
{
newFolder = Regex.Replace(oldFolder, @$"\\Main\\{this.ArchiveDirName}\\_", @"\Main\_", RegexOptions.IgnoreCase);
newFolder = Regex.Replace(newFolder, @$"\\User\\{this.ArchiveDirName}\\_", @"\User\_", RegexOptions.IgnoreCase);// Cannot be both
return newFolder;
}
newFolder = Regex.Replace(oldFolder, @"\\Main\\_", @$"\Main\{this.ArchiveDirName}\_", RegexOptions.IgnoreCase);
newFolder = Regex.Replace(newFolder, @"\\User\\_", @$"\User\{this.ArchiveDirName}\_", RegexOptions.IgnoreCase);// Cannot be both
return newFolder;
}
public string GetPlayerFile(string characterName, bool IsTQIT, bool isArchive)
=> Path.Combine(GetBaseCharacterFolder(IsTQIT, isArchive), string.Concat("_", characterName), PLAYERSAVEFILENAME);
/// <summary>
/// Gets the full path to the player's stash file.
/// </summary>
/// <param name="characterName">name of the character</param>
/// <returns>full path to the player stash file</returns>
public string GetPlayerStashFile(string characterName, bool isArchive)
=> Path.Combine(GetBaseCharacterFolder(true, isArchive), string.Concat("_", characterName), PLAYERSTASHFILENAMEB);
/// <summary>
/// Gets a list of all of the character files in the save folder.
/// </summary>
/// <returns>List of character files in a string array</returns>
public string[] GetCharacterList()
{
List<string> dirs = new();
// Get all folders that start with a '_'.
var TQDir = GetBaseCharacterFolder(false, false);// From TQ
var TQITDir = GetBaseCharacterFolder(true, false);// From TQIT
if (Config.UserSettings.Default.EnableOriginalTQSupport && Directory.Exists(TQDir))
dirs.AddRange(Directory.GetDirectories(TQDir, "_*"));
if (Directory.Exists(TQITDir))
dirs.AddRange(Directory.GetDirectories(TQITDir, "_*"));
// Archived
TQDir = GetBaseCharacterFolder(false, true);// From TQ
TQITDir = GetBaseCharacterFolder(true, true);// From TQIT
if (Config.UserSettings.Default.EnableOriginalTQSupport && Directory.Exists(TQDir))
dirs.AddRange(Directory.GetDirectories(TQDir, "_*"));
if (Directory.Exists(TQITDir))
dirs.AddRange(Directory.GetDirectories(TQITDir, "_*"));
return dirs.ToArray();
}
/// <summary>
/// Return all known custom map directories
/// </summary>
/// <returns>List of custom maps in a string array</returns>
public GamePathEntry[] GetCustomMapList()
=> new GamePathEntry[][] { GetCustomMapListLegacy(), GetCustomMapListSteamWork() }
.Where(g => g?.Any() ?? false)
.SelectMany(g => g)
.ToArray();
/// <summary>
/// Gets a value indicating whether Ragnarok DLC has been installed.
/// </summary>
public bool IsRagnarokInstalled
=> Directory.Exists(Path.Combine(GamePathTQIT, "Resources", "XPack2"));
/// <summary>
/// Gets a value indicating whether Atlantis DLC has been installed.
/// </summary>
public bool IsAtlantisInstalled
=> Directory.Exists(Path.Combine(GamePathTQIT, "Resources", "XPack3"));
/// <summary>
/// Gets a value indicating whether Eternal Embers DLC has been installed.
/// </summary>
public bool IsEmbersInstalled
=> Directory.Exists(Path.Combine(GamePathTQIT, "Resources", "XPack4"));
/// <summary>
/// Gets or sets the name of the custom map.
/// Added to support custom quest characters
/// </summary>
public string MapName { get; set; }
/// <summary>
/// Gets a value indicating whether a custom map has been specified.
/// </summary>
public bool IsCustom
=> !string.IsNullOrEmpty(MapName) && (MapName.Trim().ToUpperInvariant() != "MAIN");
/// <summary>
/// Converts a file path to a backup file. Adding the current date and time to the name.
/// </summary>
/// <param name="prefix">prefix of the backup file.</param>
/// <param name="filePath">Full path of the file to backup.</param>
/// <returns>Returns the name of the backup file to use for this file. The backup file will have the given prefix.</returns>
public string ConvertFilePathToBackupPath(string prefix, string filePath)
{
// Get the actual filename without any path information
string filename = Path.GetFileName(filePath);
// Strip the extension off of it.
string extension = Path.GetExtension(filename);
if (!string.IsNullOrEmpty(extension))
filename = Path.GetFileNameWithoutExtension(filename);
// Now come up with a timestamp string
string timestamp = DateTime.Now.ToString("-yyyyMMdd-HHmmss-fffffff-", CultureInfo.InvariantCulture);
string pathHead = Path.Combine(TQVaultBackupFolder, prefix);
pathHead = string.Concat(pathHead, "-", filename, timestamp);
int uniqueID = 0;
// Now loop and construct the filename and check to see if the name
// is already in use. If it is, increment uniqueID and try again.
while (true)
{
string fullFilePath = string.Concat(pathHead, uniqueID.ToString("000", CultureInfo.InvariantCulture), extension);
if (!File.Exists(fullFilePath))
return fullFilePath;
// try again
++uniqueID;
}
}
/// <summary>
/// Gets a value indicating whether the vault save folder has been changed.
/// Usually done via settings and triggers a reload of the vaults.
/// </summary>
public bool VaultFolderChanged { get; private set; }
/// <summary>
/// Gets or sets the vault save folder path.
/// </summary>
public string TQVaultSaveFolder
{
get
{
if (string.IsNullOrEmpty(_VaultFolder))
{
string folderPath = Path.Combine(SaveFolderTQ, VAULTFILES_DEFAULT_DIRNAME);
// Lets see if our path exists and create it if it does not
if (!Directory.Exists(folderPath))
{
try
{
Directory.CreateDirectory(folderPath);
}
catch (Exception e)
{
throw new InvalidOperationException(string.Concat("Error creating directory: ", folderPath), e);
}
}
_VaultFolder = folderPath;
VaultFolderChanged = true;
}
return _VaultFolder;
}
// Added by VillageIdiot
// Used to set vault path by configuration UI.
set
{
if (Directory.Exists(value))
_VaultFolder = value;
}
}
public string TQVaultConfigFolder
{
get
{
var path = Path.Combine(TQVaultSaveFolder, @"Config");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return path;
}
}
/// <summary>
/// Gets the vault backup folder path.
/// </summary>
public string TQVaultBackupFolder
{
get
{
string baseFolder = TQVaultSaveFolder;
string folderPath = Path.Combine(baseFolder, "Backups");
// Create the path if it does not yet exist
if (!Directory.Exists(folderPath))
{
try
{
Directory.CreateDirectory(folderPath);
}
catch (Exception e)
{
throw new InvalidOperationException(string.Concat("Error creating directory: ", folderPath), e);
}
}
return folderPath;
}
}
public string TransferStashFileName => TRANSFERSTASHFILENAME;
public string RelicVaultStashFileName => RELICVAULTSTASHFILENAME;
public string PlayerSaveFileName => PLAYERSAVEFILENAME;
public string PlayerStashFileNameB => PLAYERSTASHFILENAMEB;
public string PlayerStashFileNameG => PLAYERSTASHFILENAMEG;
public string PlayerSettingsFileName => PLAYERSETTINGSFILENAME;
public bool GameInstallDirectoryIsITOrAE { get; private set; }
/// <summary>
/// Gets the file name and path for a vault.
/// </summary>
/// <param name="vaultName">The name of the vault file.</param>
/// <returns>The full path along with extension of the vault file.</returns>
public string GetVaultFile(string vaultName)
=> string.Concat(Path.Combine(TQVaultSaveFolder, vaultName), VAULTFILENAME_EXTENSION_JSON);
/// <summary>
/// Gets a list of all of the vault files.
/// </summary>
/// <returns>The list of all of the vault files in the save folder.</returns>
public string[] GetVaultList()
{
string[] empty = new string[0];
try
{
// Get all files that have a .vault extension.
string[] filesOld = Directory.GetFiles(TQVaultSaveFolder, $"*{VAULTFILENAME_EXTENSION_OLD}");
string[] filesJson = Directory.GetFiles(TQVaultSaveFolder, $"*{VAULTFILENAME_EXTENSION_JSON}");
if (!filesOld.Any() && !filesJson.Any())
return empty;
List<string> vaultList = new List<string>();
// Strip out the path information and extension.
foreach (string file in filesOld)
{
vaultList.Add(Path.GetFileNameWithoutExtension(file));
}
// Pure Json vaults
foreach (string newfile in filesJson)
{
if (!filesOld.Any(oldfile => newfile.StartsWith(oldfile)))
{
var remain = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(newfile));
vaultList.Add(remain);
}
}
// sort alphabetically
vaultList.Sort();
return vaultList.ToArray();
}
catch (DirectoryNotFoundException)
{
return empty;
}
}
/// <summary>
/// Gets a list of all of the custom maps "old path".
/// </summary>
/// <returns>List of custom maps in a string array</returns>
GamePathEntry[] GetCustomMapListSteamWork()
{
try
{
// Get all folders in the Steam\steamapps\workshop\content directory.
string TQITFolder = GamePathTQIT;
var steamworkshopRootDir = Regex.Replace(TQITFolder, @"(?i)^(?<SteamappsRoot>.+steamapps).*", @"${SteamappsRoot}\workshop\content\475150");
if (steamworkshopRootDir == TQITFolder)// regex failed ! This is not a steamapps path
return null;
var modDir = Directory.GetDirectories(steamworkshopRootDir, "*");
if (!(modDir?.Any() ?? false))
return null;
var customMapList = modDir
// Find SubModDir having readable Mod names
.SelectMany(rd => Directory.GetDirectories(rd, "*"))
// Make entries
.Select(p => new GamePathEntry(p, $"SteamWorkshop : {Path.GetFileName(p)}"))
.OrderBy(e => e.DisplayName)// sort alphabetically
.ToArray();
return customMapList;
}
catch (DirectoryNotFoundException)
{
return null;
}
}
/// <summary>
/// Gets a list of all of the custom maps "old path".
/// </summary>
/// <returns>List of custom maps in a string array</returns>
GamePathEntry[] GetCustomMapListLegacy()
{
try
{
// Get all folders in the CustomMaps directory.
string saveFolder = SaveFolderTQIT;
var mapFolders = Directory.GetDirectories(Path.Combine(saveFolder, "CustomMaps"), "*");
if (!(mapFolders?.Any() ?? false))
return null;
var customMapList = mapFolders
.Select(p => new GamePathEntry(p, $"Legacy : {Path.GetFileName(p)}"))
.OrderBy(e => e.DisplayName)// sort alphabetically
.ToArray();
return customMapList;
}
catch (DirectoryNotFoundException)
{
return null;
}
}
/// <summary>
/// Try to resolve the local game path
/// </summary>
/// <returns></returns>
public string ResolveGamePath()
{
string titanQuestGamePath = null;
// ForceGamePath precedence for dev on PC with partial installation
if (!string.IsNullOrEmpty(Config.UserSettings.Default.ForceGamePath))
titanQuestGamePath = Config.UserSettings.Default.ForceGamePath;
// We are either autodetecting or the path has not been set
//
// Detection logic for a GOG install of the anniversary edition ~Malgardian
if (string.IsNullOrEmpty(titanQuestGamePath))
{
string[] path = { "SOFTWARE", "GOG.com", "Games", "1196955511", "PATH" };
titanQuestGamePath = ReadRegistryKey(Microsoft.Win32.Registry.LocalMachine, path);
}
if (string.IsNullOrEmpty(titanQuestGamePath))
{
string[] path = { "SOFTWARE", "WOW6432Node", "GOG.com", "Games", "1196955511", "PATH" };
titanQuestGamePath = ReadRegistryKey(Microsoft.Win32.Registry.LocalMachine, path);
}
// Detection logic for a Steam install of the anniversary edition ~Malgardian
if (string.IsNullOrEmpty(titanQuestGamePath))
{
string steamTQPath = "SteamApps\\common\\Titan Quest Anniversary Edition";
string[] registryPath = { "Software", "Valve", "Steam", "SteamPath" };
string steamPath = ReadRegistryKey(Microsoft.Win32.Registry.CurrentUser, registryPath).Replace("/", "\\");
string fullPath = Path.Combine(steamPath, steamTQPath);
string fullPathExe = Path.Combine(fullPath, @"TQ.exe");
if (File.Exists(fullPathExe))
titanQuestGamePath = fullPath;
else
{
//further looking for Steam library
//read libraryfolders.vdf
var vdfFile = Path.Combine(steamPath, @"SteamApps\libraryfolders.vdf");
if (File.Exists(vdfFile))
{
string[] libFile = File.ReadAllLines(vdfFile);
// TODO Old file format ? Is it obsolete ?
Regex vdfPathRegex = new Regex(@"""\d+""\t+""([^""]+)"""); // "2" "D:\\games\\Steam"
foreach (var line in libFile)
{
if (vdfPathRegex.Match(line.Trim()) is { Success: true } match)
{
fullPath = Path.Combine(match.Groups[1].Value, steamTQPath);
if (Directory.Exists(fullPath))
{
titanQuestGamePath = fullPath;
break;
}
}
}
if (string.IsNullOrWhiteSpace(titanQuestGamePath))
{
// New File Format
var regExPath = new Regex(@"""path""\s+""(?<path>[^""]+)""");
var gameIdMarkup = @"""475150""";
steamPath = string.Empty;
foreach (var line in libFile)
{
// Match "path"
if (regExPath.Match(line) is { Success: true } match)
steamPath = match.Groups["path"].Value;
// Match gameId
if (line.Contains(gameIdMarkup))
break;
}
if (steamPath != string.Empty)
{
var fullpath = Path.Combine(steamPath, steamTQPath);
if (Directory.Exists(fullpath))
titanQuestGamePath = fullpath;
}
}
}
}
}
// Disc version detection logic -old
if (string.IsNullOrEmpty(titanQuestGamePath))
{
string[] path = { "SOFTWARE", "Iron Lore", "Titan Quest", "Install Location" };
titanQuestGamePath = ReadRegistryKey(Microsoft.Win32.Registry.LocalMachine, path);
}
if (string.IsNullOrEmpty(titanQuestGamePath))
throw new ExGamePathNotFound(@"Unable to locate Titan Quest installation directory.
Please select the game installation directory.");
this.GameInstallDirectoryIsITOrAE = titanQuestGamePath.ContainsIgnoreCase("Anniversary") || titanQuestGamePath.ContainsIgnoreCase("Immortal");
return titanQuestGamePath;
}
/// <summary>
/// Reads a value from the registry
/// </summary>
/// <param name="key">registry hive to be read</param>
/// <param name="path">path of the value to be read</param>
/// <returns>string value of the key and value that was read or empty string if there was a problem.</returns>
string ReadRegistryKey(Microsoft.Win32.RegistryKey key, string[] path)
{
// The last item in the path array is the actual value name.
int valueKey = path.Length - 1;
// All other values in the path are keys which will need to be navigated.
int lastSubKey = path.Length - 2;
for (int i = 0; i <= lastSubKey; ++i)
{
key = key.OpenSubKey(path[i]);
if (key == null)
return string.Empty;
}
return (string)key.GetValue(path[valueKey]);
}
/// <summary>
/// Return the vault name from <paramref name="vaultFilePath"/>
/// </summary>
/// <param name="vaultFilePath"></param>
/// <returns>name stripted from path and extension</returns>
public string GetVaultNameFromPath(string vaultFilePath)
{
string vaultname = null;
if (vaultFilePath.EndsWith(VAULTFILENAME_EXTENSION_JSON, StringComparison.InvariantCultureIgnoreCase))
vaultname = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(vaultFilePath));
else if (vaultFilePath.EndsWith(VAULTFILENAME_EXTENSION_OLD, StringComparison.InvariantCultureIgnoreCase))
vaultname = Path.GetFileNameWithoutExtension(vaultFilePath);
return vaultname;
}
/// <summary>
/// Return ARC filename from <paramref name="resourceIdOrPrefix"/>
/// </summary>
/// <param name="resourceIdOrPrefix"></param>
/// <returns></returns>
public (string ArcFileName, bool IsDLC) ResolveArcFileName(RecordId resourceIdOrPrefix)
{
var segments = resourceIdOrPrefix.Normalized.Split('\\');
string path;
bool isDLC = true;
switch (segments.First())
{
case "XPACK" when segments[1] != "SOUNDS":
// Comes from Immortal Throne
path = Path.Combine(GamePathTQIT, "Resources", "XPack", segments[1] + ".arc");
break;
case "XPACK" when segments[1] == "SOUNDS": // Sounds file exception for IT
// Comes from Immortal Throne
path = Path.Combine(GamePathTQIT, "Resources", segments[1] + ".arc");
break;
case "XPACK2":
// Comes from Ragnarok
path = Path.Combine(GamePathTQIT, "Resources", "XPack2", segments[1] + ".arc");
break;
case "XPACK3":
// Comes from Atlantis
path = Path.Combine(GamePathTQIT, "Resources", "XPack3", segments[1] + ".arc");
break;
case "XPACK4":
// Comes from Eternal Embers
path = Path.Combine(GamePathTQIT, "Resources", "XPack4", segments[1] + ".arc");
break;
case "SOUNDS":
// Regular Dialogs/Sounds/Music/PlayerSounds
path = Path.Combine(GamePathTQIT, "Audio", segments[0] + ".arc");
isDLC = false;
break;
default:
// Base game
path = Path.Combine(GamePathTQIT, "Resources", segments[0] + ".arc");
isDLC = false;
break;
}
return (path, isDLC);
}
} |
using System;
namespace QAToolKit.Auth.Exceptions
{
/// <summary>
/// Keycloak access denied exception
/// </summary>
[Serializable]
public class AccessDeniedException : Exception
{
/// <summary>
/// Keycloak access denied exception
/// </summary>
/// <param name="message"></param>
public AccessDeniedException(string message) : base(message)
{
}
/// <summary>
/// Keycloak access denied exception
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public AccessDeniedException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace Common.Wpf.ViewModel
{
[ComVisible(true)]
[Serializable]
public partial class WebPageViewModel : SingleContentUIViewModel
{
/// <summary>
/// Gets / sets the Body value
/// </summary>
public string Body { get; set; }
/// <summary>
/// Gets / sets the JavaScript value
/// </summary>
public string JavaScript { get; set; }
/// <summary>
/// Gets / sets the Css value
/// </summary>
public string Css { get; set; }
/// <summary>
/// Gets / sets the Css value
/// </summary>
public string Source { get; set; }
public void CallJavaScript(string functionName, params object[] args)
{
if (View != null)
{
View.CallJavaScript(functionName, args);
}
}
}
}
|
using System;
using System.Diagnostics;
using System.Text;
using UnityEngine;
namespace EditorTool
{
public class CommandHelper
{
public static void ExcutePython(string argument)
{
Debug.Log("excute python:" + argument);
if (Application.get_platform() == 7)
{
CommandHelper.ExcuteExternalCommandNoLog("python", argument);
}
else
{
CommandHelper.ExcuteExternalCommand("python", argument);
}
}
public static void ExcuteLua(string argument)
{
Debug.Log("excute lua:" + argument);
if (Application.get_platform() == 7)
{
CommandHelper.ExcuteExternalCommandNoLog("lua", argument);
}
else
{
CommandHelper.ExcuteExternalCommand("lua", argument);
}
}
public static void ExcuteExternalCommand(string command, string argument)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo(command, argument);
processStartInfo.set_CreateNoWindow(true);
processStartInfo.set_UseShellExecute(false);
processStartInfo.set_RedirectStandardOutput(true);
processStartInfo.set_RedirectStandardError(true);
processStartInfo.set_RedirectStandardInput(true);
processStartInfo.set_StandardOutputEncoding(Encoding.get_UTF8());
processStartInfo.set_StandardErrorEncoding(Encoding.get_UTF8());
Process process = new Process();
process.set_StartInfo(processStartInfo);
process.Start();
process.WaitForExit();
Debug.Log(process.get_StandardError().ReadToEnd());
Debug.Log(process.get_StandardOutput().ReadToEnd());
process.Close();
}
public static void ExcuteExternalCommand2(string command, string argument)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo(command, argument);
processStartInfo.set_CreateNoWindow(true);
processStartInfo.set_UseShellExecute(false);
processStartInfo.set_RedirectStandardOutput(true);
processStartInfo.set_RedirectStandardError(true);
processStartInfo.set_RedirectStandardInput(true);
processStartInfo.set_StandardOutputEncoding(Encoding.get_UTF8());
processStartInfo.set_StandardErrorEncoding(Encoding.get_UTF8());
Process process = Process.Start(processStartInfo);
process.WaitForExit();
Debug.Log(process.get_StandardError().ReadToEnd());
Debug.Log(process.get_StandardOutput().ReadToEnd());
process.Close();
}
public static void ExcuteExternalCommandNoLog(string command, string argument)
{
Process process = Process.Start(command, argument);
process.WaitForExit();
process.Close();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CherryController : MonoBehaviour
{
private int sideSelect;
private float timeElapsed;
public GameObject Cherry;
private GameObject newCherry;
private Camera mainCamera;
private Vector3 newPosition;
private float duration = 5f;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("GenerateCherry", 10f, 15f);
mainCamera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}
// Update is called once per frame
void Update()
{
if (timeElapsed >= duration)
{
Destroy(newCherry);
timeElapsed = 0;
}
if (newCherry != null)
{
newCherry.transform.position = Vector3.Lerp(newPosition, Vector3.Scale(newPosition, new Vector3(-1, -1, 0)), timeElapsed / duration);
timeElapsed += Time.deltaTime;
}
}
void GenerateCherry()
{
sideSelect = Random.Range(1, 3);
if (sideSelect == 1)
{
float verborderPos = Random.Range(-mainCamera.orthographicSize, mainCamera.orthographicSize);
float horborderPos = -mainCamera.orthographicSize * mainCamera.aspect + 1;
newPosition = new Vector3(horborderPos - 1, verborderPos + 1, 0f);
newCherry = Instantiate(Cherry, newPosition, Quaternion.identity);
}
if (sideSelect == 2)
{
float verborderPos = Random.Range(-mainCamera.orthographicSize, mainCamera.orthographicSize);
float horborderPos = mainCamera.orthographicSize * mainCamera.aspect + 1;
newPosition = new Vector3(horborderPos, verborderPos, 0f);
newCherry = Instantiate(Cherry, newPosition, Quaternion.identity);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TRUTH
{
public partial class Magnifier : Form
{
Graphics g;
public Magnifier()
{
InitializeComponent();
g = this.CreateGraphics();
this.Resize += NeedInvalidate;
this.Move += NeedInvalidate;
this.TransparencyKey = this.BackColor;
new Background().Show();
}
private void NeedInvalidate(object sender, EventArgs e)
{
var s = Background.Instance.ImgLoc;
var d = this.Location;
this.pictureBox1.Location = new Point(s.X - d.X, s.Y - d.Y);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TaxiDriverSystem
{
public partial class drivermainpanel : Form
{
SQLWebServiceReference5.WebService1SoapClient client = null;
public drivermainpanel()
{
InitializeComponent();
client = new SQLWebServiceReference5.WebService1SoapClient();
}
private void btnStart_Click(object sender, EventArgs e)
{
DriverStartEndDay login = new DriverStartEndDay();
login.Show();
client = new SQLWebServiceReference5.WebService1SoapClient();
}
private void drivermainpanel_Load(object sender, EventArgs e)
{
PopulateGrid();
}
void PopulateGrid()
{
int DID = Login.DriverID;
dataGridView1.DataSource = client.HoursWord(DID);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUpSpawn : MonoBehaviour
{
public GameObject powerUp;
public float respawnTime;
GameObject lastSpawnedObject;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("SpawnPowerUp", 5.0f, respawnTime);
}
// Update is called once per frame
void Update()
{
}
void SpawnPowerUp()
{
Destroy(lastSpawnedObject);
lastSpawnedObject = Instantiate(powerUp,transform.position,transform.rotation);
}
}
|
using System;
using System.Collections.Generic;
namespace RMAT3.Models
{
public class PreferenceType
{
public PreferenceType()
{
UserPreferences = new List<UserPreference>();
}
public int PreferenceTypeId { get; set; }
public string AddedByUserId { get; set; }
public DateTime AddTs { get; set; }
public string UpdatedByUserId { get; set; }
public string UpdatedCommentTxt { get; set; }
public DateTime UpdatedTs { get; set; }
public bool IsActiveInd { get; set; }
public DateTime EffectiveFromDt { get; set; }
public DateTime? EffectiveToDt { get; set; }
public string PreferenceTypeCd { get; set; }
public string PreferenceTypeTxt { get; set; }
public virtual ICollection<UserPreference> UserPreferences { get; set; }
}
}
|
using System.Web.Http;
using calculatorRestAPI.Models.DTOs;
using calculatorRestAPI.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace calculatorRestAPI.Controllers
{
public class CalculatorProfileController : ApiController
{
/// <summary>
/// Get calculator data for given <code>userName</code>
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
// GET api/calculatorprofile
public CalculatorDTO Get( string userName )
{
CalculatorDTO result = Service.getService().getCalculatorData(userName);
return result;
}
/// <summary>
/// Insert/Update calculator data belong to the given <code>userName</code>
/// </summary>
/// <param name="jsonData">JSON string represents the data to save For example: {"paramA":"200","paramB":"300","result":"500","operator":"+"}</param>
// PUT api/calculatorprofile
public void Put( [FromBody]CalculatorDTO data)
{
//JObject JsonData = JObject.Parse(jsonData);
//CalculatorDTO data = JsonData.ToObject<CalculatorDTO>();
Service.getService().saveCalculatorData(data );
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
namespace Combination
{
public partial class 入庫檢核表 : Form
{
string query1, query2, query3, query4, query5;
string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string inputPath = System.Environment.CurrentDirectory;
string exportPath;
string filePath;
Excel.Application excelApp;
Excel._Workbook wBook;
Excel._Worksheet wSheet;
Excel.Range wRange;
Sql sql = new Sql();
public 入庫檢核表()
{
InitializeComponent();
}
private void btnSeek_Click(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
if (TotCheckedBox.Checked == true)
{
this.dataGridView3.Rows.Clear();
query4 = @"/*▼金蝶入库汇总▼*/
select fbatchno as 制造单号,fmodel as 产品名称,数量 AS 生产数量,FNAME as 单位,入库数量,单位,convert (decimal(18,0),v3.fauxqty) as 订单数量 from
(select FbatchNO,convert (decimal(18,0),sum(qty)) as 入库数量, FCUUnitName as 单位 from
((select a.FKFDate,a.FbatchNo,d.Fmodel,Sum(isnull(a.FAuxQty,0)) as Qty,b.FCUUnitName,Sum(isnull(a.FAuxQty,0))*b.FEntrySelfA0245 as PCS
from ["+ sql.CYDB +"].[dbo].[ICStockbillentry] a,["+ sql.CYDB +"].[dbo].[vwICBill_2] b,["+ sql.CYDB +"].[dbo].[t_ICItem] d " +
"where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID and FbatchNo <> '' " +
"group by a.FKFDate,a.FbatchNo,d.Fmodel,b.FEntrySelfA0245,b.FCUUnitName) " +
"union " +
"(select a.FKFDate,a.FbatchNo,d.Fmodel,Sum(isnull(a.FAuxQty,0)) as Qty,b.FCUUnitName,Sum(isnull(a.FAuxQty,0))*b.FEntrySelfA0245 as PCS " +
"from ["+ sql.CKDB +"].[dbo].[ICStockbillentry] a,["+ sql.CKDB +"].[dbo].[vwICBill_2] b,["+ sql.CKDB +"].[dbo].[t_ICItem] d " +
"where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID and FbatchNo <> '' " +
"group by a.FKFDate,a.FbatchNo,d.Fmodel,b.FEntrySelfA0245,b.FCUUnitName) ) v where (FCUUnitName='箱' or FCUUnitName='板' ) " +
"group by fbatchno,fmodel,fcuunitname)v1, " +
"/*程奎程益生产*/ " +
"(select fbillno,fmodel,sum(ppqty) as 数量,fname from " +
"(SELECT c.FBILLNO,a.[FModel],b.FNAME FROM ["+ sql.CYDB +"].[dbo].[t_ICItem]a, ["+ sql.CYDB +"].[dbo].[t_measureUnit]b,["+ sql.CYDB +"].[dbo].[ICMO]c " +
"where b.FmeasureUnitID=a.FStoreUnitID " +
"and a.fitemid=c.FitemID)a,/*入庫單位*/ " +
"((select convert(varchar(10),fcheckdate,120)as pdate,oid,case when moutunit ='张' then ppqty*f_110/f_102 else ppqty end as ppqty, " +
"case when moutunit ='张' then '板'else moutunit end as unit ,f_110,F_122,F_123,F_102 " +
"from [ChengyiYuntech].[dbo].[ProduceOrder] a,[ChengyiYuntech].[dbo].[scanrecord]b,[ChengyiYuntech].[dbo].[Machine] c, " +
"["+ sql.CYDB +"].[dbo].[ICMO] d,["+ sql.CYDB +"].[dbo].[T_ICItem] e " +
"where a.oid = d.fbillno " +
"and d.FitemID = e.FitemID " +
"and a.omachinecode=c.mcode " +
"and a.id=b.poid " +
"and e.f_102 <> 0)/*CY*/ " +
"union all " +
"(select convert(varchar(10),fcheckdate,120)as pdate,oid,case when moutunit ='张' then ppqty*f_110/f_102 else ppqty end as ppqty, " +
"case when moutunit ='张' then '板'else moutunit end as unit ,f_110,F_122,F_123,F_102 " +
"from [ChengyiYuntech].[dbo].[ProduceOrder] a,[ChengyiYuntech].[dbo].[scanrecord]b,[ChengyiYuntech].[dbo].[Machine] c, " +
"["+ sql.CKDB +"].[dbo].[ICMO] d,["+ sql.CKDB +"].[dbo].[T_ICItem] e " +
"where a.oid = d.fbillno " +
"and d.FitemID = e.FitemID " +
"and a.omachinecode=c.mcode " +
"and a.id=b.poid " +
"and e.f_102 <> 0) /*CK*/ )b " +
"where b.oid=a.fbillno " +
"and unit =fname " +
"and pdate between '" + dateTimePicker1.Value.ToString("yyyyMMdd") + "' and '" + dateTimePicker2.Value.ToString("yyyyMMdd") + "' " +
"and fmodel like '%" + textBox5.Text + "%' " +
"group by fbillno,fmodel,fname)v2,[" + sql.CYDB + "].[dbo].[ICMO] " +
"v3 " +
"where v2.fbillno=v1.FbatchNO " +
"and v3.fbillno = v2.fbillno";
Load_Data(query4);
if (dataGridView3.Rows.Count == 0)
{
MessageBox.Show("查无信息");
}
}
else if(ckbDate.Checked == true)
{
query5 = @"with v0 as
(select b.FKFDATE,a.FbatchNo,d.Fmodel,isnull(a.FAuxQty,0) as Qty,b.FCUUnitName,isnull(a.FAuxQty,0)*b.FEntrySelfA0245 as PCS from ["+ sql.CYDB +"].[dbo].[ICStockbillentry] a,["+ sql.CYDB +"].[dbo].[vwICBill_2] b,["+ sql.CYDB +"].[dbo].[t_ICItem] d " +
"where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID and FbatchNo <> '' " +
"union all " +
"select b.FKFDATE,a.FbatchNo,d.Fmodel,isnull(a.FAuxQty,0) as Qty,b.FCUUnitName,isnull(a.FAuxQty,0)*b.FEntrySelfA0245 as PCS from ["+ sql.CKDB +"].[dbo].[ICStockbillentry] a,["+ sql.CKDB +"].[dbo].[vwICBill_2] b,["+ sql.CKDB +"].[dbo].[t_ICItem] d " +
"where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID and FbatchNo <> '' ), " +
"storeNum as " +
"(select convert(varchar(10),FKFDATE,120) as idate,FbatchNo,Fmodel,convert(decimal(18,0),Sum(Qty)) as Qty,FCUUnitName,convert(decimal(18,0),Sum(PCS)) as PCS from v0 " +
"where (fcuunitname ='箱' or fcuunitname = '板') and (FKFdate between '" + dateTimePicker1.Value.ToString("yyyyMMdd") + "' and '" + dateTimePicker2.Value.ToString("yyyyMMdd") + "') " +
"group by FKFDATE,FbatchNo,Fmodel,FCUUnitName ), " +
"inUnit as " +
"(SELECT c.fbillno,a.[FModel],b.FNAME " +
"FROM["+ sql.CYDB +"].[dbo].[t_ICItem] a, ["+ sql.CYDB +"].[dbo].[t_measureUnit] b,["+ sql.CYDB +"].[dbo].[ICMO] " +
"c " +
"where b.FmeasureUnitID=a.FStoreUnitID " +
"and a.fitemid=c.FitemID " +
"union all " +
"SELECT c.fbillno,a.[FModel],b.FNAME " +
"FROM["+ sql.CKDB +"].[dbo].[t_ICItem] a, ["+ sql.CKDB +"].[dbo].[t_measureUnit] b,["+ sql.CKDB +"].[dbo].[ICMO] " +
"c " +
"where b.FmeasureUnitID=a.FStoreUnitID " +
"and a.fitemid=c.FitemID), " +
"productInfo as ( " +
"select convert(varchar(10),odate,120)as pdate,oid,c.moutunit,case when moutunit = '张' then ppqty*f_110/f_102 else ppqty end as ppqty, " +
"case when moutunit = '张' then '板'else moutunit end as unit ,f_110,F_122,F_123,F_102 " +
"from[ChengyiYuntech].[dbo].[ProduceOrder] a,[ChengyiYuntech].[dbo].[scanrecord] b,[ChengyiYuntech].[dbo].[Machine] c, " +
"["+ sql.CYDB +"].[dbo].[ICMO] d,["+ sql.CYDB +"].[dbo].[T_ICItem] " +
"e " +
"where a.oid = d.fbillno " +
"and d.FitemID = e.FitemID " +
"and a.omachinecode=c.mcode " +
"and a.id=b.poid " +
"and e.f_102<> 0 " +
"and phour<>'0.01' " +
"union all " +
"select convert(varchar(10),odate,120)as pdate,oid,c.moutunit,case when moutunit = '张' then ppqty*f_110/f_102 else ppqty end as ppqty, " +
"case when moutunit = '张' then '板'else moutunit end as unit ,f_110,F_122,F_123,F_102 " +
"from[ChengyiYuntech].[dbo].[ProduceOrder] a,[ChengyiYuntech].[dbo].[scanrecord] b,[ChengyiYuntech].[dbo].[Machine] c, " +
"["+ sql.CKDB +"].[dbo].[ICMO] d,["+ sql.CKDB +"].[dbo].[T_ICItem] " +
"e " +
"where a.oid = d.fbillno " +
"and d.FitemID = e.FitemID " +
"and a.omachinecode=c.mcode " +
"and a.id=b.poid " +
"and e.f_102<> 0 " +
"and phour<>'0.01' ), " +
"productInfo2 as ( " +
"select pdate, oid, sum(ppqty) as ppqty,unit from productInfo a, inUnit b where(pdate between '" + dateTimePicker1.Value.ToString("yyyyMMdd") + "' and '" + dateTimePicker2.Value.ToString("yyyyMMdd") + "') and(unit = '箱' or unit = '板') and b.Fbillno = a.oid " +
"and a.unit= b.fname " +
"group by pdate, oid, unit) " +
"select isnull(convert(varchar(10),pdate,120),idate) as 日期,isnull(oid,'') as 生产单号,isnull(unit,'') as 单位, " +
"isnull(convert(varchar, convert(float, ceiling(ppqty*100)/100)),'') as 生产数量, " +
"isnull(convert(varchar, qty),'') as 入库数量,isnull(fcuunitname,'') as 单位,isnull(FbatchNo,'') as 入库单号 " +
"from productInfo2 " +
"full outer join storeNum " +
"on oid = fbatchno and pdate = idate and unit = fcuunitname " +
"order by pdate desc,oid";
Load_Data(query5);
}
else
{
this.dataGridView1.Rows.Clear();
this.dataGridView2.Rows.Clear();
query1 = @"select isnull(pdate,'合计') as 日期,convert(decimal(18,0),ppqty)as 生产数量,isnull(unit,'') as 生产单位,
convert(decimal(18,2),storenum)as 入库数量,case when storeunit='张' then '板' else isnull(storeunit,'') end as 入库单位,convert(decimal(18,2),ppcs)as PCS
from
(select pdate ,sum(ppqty) as ppqty,unit,sum(storenum)as storenum,storeunit,sum(ppcs) as ppcs from
(select Pdate,ppqty,unit,case when unit='张' then ppqty*f_110/f_102 else ppqty end as storenum,
case when unit ='张' then '板' else unit end as storeunit,
case when unit ='张' then ppqty*f_110 else ppqty*f_102 end as ppcs from
((select a.FbatchNo,case when b.FCUUnitName='板' then '张' else b.FCUUnitName end as FCUUnitName
from ["+ sql.CYDB +"].[dbo].[ICStockbillentry] a,["+ sql.CYDB +"].[dbo].[vwICBill_2] b,["+ sql.CYDB +"].[dbo].[t_ICItem] d " +
"where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID and FbatchNo <> '' " +
"and FbatchNo like '%" + textBox1.Text + "') " +
"union " +
"(select a.FbatchNo,case when b.FCUUnitName = '板' then '张' else b.FCUUnitName end as FCUUnitName " +
"from["+ sql.CKDB +"].[dbo].[ICStockbillentry] a,["+ sql.CKDB +"].[dbo].[vwICBill_2] b,["+ sql.CKDB +"].[dbo].[t_ICItem] d " +
"where a.FinterID = b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID and FbatchNo <> '' " +
"and FbatchNo like '%" + textBox1.Text + "')) a ,/*K3程益程奎入库*/ " +
"((select oid, convert(char, odate, 23) as Pdate, b.ppqty, c.moutunit as unit, f_110, F_122, F_123, F_102 " +
"from[ChengyiYuntech].[dbo].[ProduceOrder] a,[ChengyiYuntech].[dbo].[scanrecord] b,[ChengyiYuntech].[dbo].[Machine] c, " +
"["+ sql.CYDB +"].[dbo].[ICMO] d,["+ sql.CYDB +"].[dbo].[T_ICItem] " +
"e " +
"where a.oid = d.fbillno " +
"and d.FitemID = e.FitemID " +
"and a.omachinecode=c.mcode " +
"and a.id=b.poid " +
"and oid like '%" + textBox1.Text + "' )/*CY*/ " +
"union all " +
"(select oid, convert(char, odate,23) as Pdate,b.ppqty,c.moutunit as unit ,f_110,F_122,F_123,F_102 " +
"from[ChengyiYuntech].[dbo].[ProduceOrder] a,[ChengyiYuntech].[dbo].[scanrecord] b,[ChengyiYuntech].[dbo].[Machine] c, " +
"["+ sql.CKDB +"].[dbo].[ICMO] d,["+ sql.CKDB +"].[dbo].[T_ICItem] " +
"e " +
"where a.oid = d.fbillno " +
"and d.FitemID = e.FitemID " +
"and a.omachinecode=c.mcode " +
"and a.id=b.poid " +
"and oid like '%" + textBox1.Text + "') /*CK*/ )b /*程奎程益生产*/ " +
"where b.unit=a.FCUUnitName)c /*b生产资料换算*/ " +
"group by pdate, unit, storeunit with rollup)d " +
"where storeunit is not null or pdate is null";
query2 = @"select isnull(日期,'合计')as 日期,入库数量,isnull(单位,'') as 单位 ,PCS from
(select 日期,sum(入库数量) as 入库数量,单位,sum(PCS) as PCS from
(select a.FbatchNo,convert(char,FKFDate,23) as 日期,convert (decimal(18,0),qty) as 入库数量, FCUUnitName as 单位,convert (decimal(18,2),PCS) as PCS from
((select a.FKFDate,a.FbatchNo,d.Fmodel,Sum(isnull(a.FAuxQty,0)) as Qty,b.FCUUnitName,Sum(isnull(a.FAuxQty,0))*b.FEntrySelfA0245 as PCS
from ["+ sql.CYDB +"].[dbo].[ICStockbillentry] a,["+ sql.CYDB +"].[dbo].[vwICBill_2] b,["+ sql.CYDB +"].[dbo].[t_ICItem] d " +
"where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID and FbatchNo <> '' " +
"group by a.FKFDate,a.FbatchNo,d.Fmodel,b.FEntrySelfA0245,b.FCUUnitName) " +
"union " +
"(select a.FKFDate,a.FbatchNo,d.Fmodel,Sum(isnull(a.FAuxQty,0)) as Qty,b.FCUUnitName,Sum(isnull(a.FAuxQty,0))*b.FEntrySelfA0245 as PCS " +
"from ["+ sql.CKDB +"].[dbo].[ICStockbillentry] a,["+ sql.CKDB +"].[dbo].[vwICBill_2] b,["+ sql.CKDB +"].[dbo].[t_ICItem] d " +
"where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID and FbatchNo <> '' " +
"group by a.FKFDate,a.FbatchNo,d.Fmodel,b.FEntrySelfA0245,b.FCUUnitName)) a " +
"where a.FbatchNo like '%" + textBox1.Text + "')b " +
"group by 日期,单位 with rollup)c " +
"where 单位 is not null or 日期 is null";
query3 = @"select a.Fmodel as 产品名称,convert(decimal(18,0),a.FAuxQty) as 订单量,a.FCUUnitName as 订单单位,isnull(convert(decimal(18,0),c.Qty),0) as 金蝶领料,isnull(c.FbaseUnitID,'kg') as 领料单位 from
((select v1.Fbillno,v1.Fmodel,v1.F_149,v1.FAuxQty,v1.需求pcs,isnull(v2.Qty,0) as Qty,V1.FName as FCUUnitName,isnull(v2.PCS,0) as PCS from (select a.Fbillno,b.Fmodel,a.FAuxQty,a.FAuxQty*b.F_102 as 需求pcs,a.FStatus,c.FName,b.F_149 from ["+ sql.CYDB +"].[dbo].[ICMO] a,["+ sql.CYDB +"].[dbo].[t_ICItem] b,["+ sql.CYDB +"].[dbo].[t_measureUnit] c where a. FitemId = b.FitemID and a.FUnitID = c.FMeasureUnitID) v1 left join " +
"(select a.FbatchNo,d.Fmodel,Sum(a.FAuxQty) as Qty,b.FCUUnitName,Sum(a.FAuxQty)*b.FEntrySelfA0245 as PCS from ["+ sql.CYDB +"].[dbo].[ICStockbillentry] a,["+ sql.CYDB +"].[dbo].[vwICBill_2] b,["+ sql.CYDB +"].[dbo].[t_ICItem] d where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID group by a.FbatchNo,d.Fmodel,b.FEntrySelfA0245,b.FCUUnitName) v2 on v1.Fbillno = v2.FbatchNo) union " +
"(select v1.Fbillno,v1.Fmodel,v1.F_149,v1.FAuxQty,v1.需求pcs,isnull(v2.Qty,0) as Qty,V1.FName as FCUUnitName,isnull(v2.PCS,0) as PCS from (select a.Fbillno,b.Fmodel,a.FAuxQty,a.FAuxQty*b.F_102 as 需求pcs,a.FStatus,c.FName,b.F_149 from ["+ sql.CKDB +"].[dbo].[ICMO] a,["+ sql.CKDB +"].[dbo].[t_ICItem] b,["+ sql.CKDB +"].[dbo].[t_measureUnit] c where a. FitemId = b.FitemID and a.FUnitID = c.FMeasureUnitID) v1 left join " +
"(select a.FbatchNo,d.Fmodel,Sum(isnull(a.FAuxQty,0)) as Qty,b.FCUUnitName,Sum(isnull(a.FAuxQty,0))*b.FEntrySelfA0245 as PCS from ["+ sql.CKDB +"].[dbo].[ICStockbillentry] a,["+ sql.CKDB +"].[dbo].[vwICBill_2] b,["+ sql.CKDB +"].[dbo].[t_ICItem] d where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID group by a.FbatchNo,d.Fmodel,b.FEntrySelfA0245,b.FCUUnitName) v2 on v1.Fbillno = v2.Fbatchno)) a left join " +
"(select b.Fuse,SUM(b.FBaseQty) as Qty,b.FbaseUnitID from ((select b.Fuse,d.Fmodel,SUM(b.FBaseQty) as FBaseQty,b.FBaseUnitID from ["+ sql.CYDB +"].[dbo].[ICStockbillentry] a,["+ sql.CYDB +"].[dbo].[vwICBill_11] b,["+ sql.CYDB +"].[dbo].[ICStockbill] c,["+ sql.CYDB +"].[dbo].[T_ICItem] d where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FinterID = c.FinterID and d.FitemID = a.FitemID and (d.Fnumber like '11%' or d.Fnumber like '12.C%') group by b.Fuse,d.Fmodel,b.FBaseUnitID) union " +
"(select b.Fuse,d.Fmodel,SUM(b.FBaseQty) as FBaseQty,b.FBaseUnitID from ["+ sql.CKDB +"].[dbo].[ICStockbillentry] a,["+ sql.CKDB +"].[dbo].[vwICBill_11] b,["+ sql.CKDB +"].[dbo].[ICStockbill] c,["+ sql.CKDB +"].[dbo].[T_ICItem] d where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FinterID = c.FinterID and d.FitemID = a.FitemID and (d.Fnumber like '11%' or d.Fnumber like '12.C%') group by b.Fuse,d.Fmodel,b.FBaseUnitID)) b group by b.Fuse,b.FbaseUnitID) c on a.Fbillno = c.Fuse " +
"where a.Fbillno = '" + textBox1.Text + "' ";
Load_Data(query3);
Load_Data(query1);
Load_Data(query2);
Cursor = Cursors.Default;
Check_DgvData();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void btnExport_Click(object sender, EventArgs e)
{
}
private void btnExport_Click_1(object sender, EventArgs e)
{
try
{
Export_Data();
}
catch (Exception)
{
MessageBox.Show("请将先前导出关闭");
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
this.ActiveControl = btnSeek;
}
}
private void Export_Data()
{
if (TotCheckedBox.Checked == true)
{
exportPath = path + @"\生产入库检核汇总表导出";
filePath = inputPath + @"\生产入库检核汇总表";
}
else if (ckbDate.Checked == true)
{
exportPath = path + @"\生产日期入库汇总表导出";
filePath = inputPath + @"\生产日期入库汇总表";
}
else
{
exportPath = path + @"\生产与入库检核表导出";
filePath = inputPath + @"\生产与入库检核表";
}
// 開啟一個新的應用程式
excelApp = new Excel.Application();
// 讓Excel文件可見
excelApp.Visible = false;
// 停用警告訊息
excelApp.DisplayAlerts = false;
// 加入新的活頁簿
excelApp.Workbooks.Add(Type.Missing);
wBook = excelApp.Workbooks.Open(filePath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
// 設定活頁簿焦點
wBook.Activate();
wSheet = (Excel._Worksheet)wBook.Worksheets[1];
if (TotCheckedBox.Checked == true)
{
wSheet.Name = "生产入库汇总表";
wSheet.Cells[2, 1] = "生产入库汇总表 (" + dateTimePicker1.Value.ToString("yyyy/MM/dd") + ") - (" + dateTimePicker2.Value.ToString("yyyy/MM/dd") + ")";
wRange = wSheet.Range[wSheet.Cells[2, 1], wSheet.Cells[2, 1]];
wRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
for (int j = 0; j < dataGridView3.ColumnCount; j++)
{
wSheet.Cells[i + 4, j + 1] = Convert.ToString(dataGridView3.Rows[i].Cells[j].Value);
}
}
}
else if (ckbDate.Checked == true)
{
wSheet.Name = "生产日期入库汇总表";
wSheet.Cells[2, 1] = "生产日期入库汇总表";
wRange = wSheet.Range[wSheet.Cells[2, 1], wSheet.Cells[2, 1]];
wRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
for (int i = 0; i < dgvDate.Rows.Count; i++)
{
for (int j = 0; j < dgvDate.ColumnCount; j++)
{
wSheet.Cells[i + 4, j + 1] = Convert.ToString(dgvDate.Rows[i].Cells[j].Value);
}
}
}
else
{
wSheet.Name = "生产入库检核表";
wSheet.Cells[2, 1] = "生产入库检核表";
wRange = wSheet.Range[wSheet.Cells[2, 1], wSheet.Cells[2, 1]];
wRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
wSheet.Cells[3, 2] = textBox1.Text;
wSheet.Cells[3, 6] = textBox3.Text;
wSheet.Cells[4, 2] = textBox2.Text;
wSheet.Cells[4, 4] = UnitOrder.Text;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
wSheet.Cells[i + 7, j + 1] = Convert.ToString(dataGridView1.Rows[i].Cells[j].Value);
}
}
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.ColumnCount; j++)
{
wSheet.Cells[i + 7, j + 7] = Convert.ToString(dataGridView2.Rows[i].Cells[j].Value);
}
}
}
// storing Each row and column value to excel sheet
Excel.Range last = wSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range allRange = wSheet.get_Range("A1", last);
allRange.Font.Size = "14";
allRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous; //格線
allRange.Columns.AutoFit();
//Save Excel
wBook.SaveAs(exportPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
wBook = null;
wSheet = null;
wRange = null;
excelApp = null;
GC.Collect();
MessageBox.Show("导出成功");
}
private void textBox1_Leave(object sender, EventArgs e)
{
query3 = @"select a.Fmodel as 产品名称,convert(decimal(18,0),a.FAuxQty) as 订单量,a.FCUUnitName as 订单单位,isnull(convert(decimal(18,0),c.Qty),0) as 金蝶领料,isnull(c.FbaseUnitID,'kg') as 领料单位 from
((select v1.Fbillno,v1.Fmodel,v1.F_149,v1.FAuxQty,v1.需求pcs,isnull(v2.Qty,0) as Qty,V1.FName as FCUUnitName,isnull(v2.PCS,0) as PCS from (select a.Fbillno,b.Fmodel,a.FAuxQty,a.FAuxQty*b.F_102 as 需求pcs,a.FStatus,c.FName,b.F_149 from ["+ sql.CYDB +"].[dbo].[ICMO] a,["+ sql.CYDB +"].[dbo].[t_ICItem] b,["+ sql.CYDB +"].[dbo].[t_measureUnit] c where a. FitemId = b.FitemID and a.FUnitID = c.FMeasureUnitID) v1 left join " +
"(select a.FbatchNo,d.Fmodel,Sum(a.FAuxQty) as Qty,b.FCUUnitName,Sum(a.FAuxQty)*b.FEntrySelfA0245 as PCS from ["+ sql.CYDB +"].[dbo].[ICStockbillentry] a,["+ sql.CYDB +"].[dbo].[vwICBill_2] b,["+ sql.CYDB +"].[dbo].[t_ICItem] d where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID group by a.FbatchNo,d.Fmodel,b.FEntrySelfA0245,b.FCUUnitName) v2 on v1.Fbillno = v2.FbatchNo) union " +
"(select v1.Fbillno,v1.Fmodel,v1.F_149,v1.FAuxQty,v1.需求pcs,isnull(v2.Qty,0) as Qty,V1.FName as FCUUnitName,isnull(v2.PCS,0) as PCS from (select a.Fbillno,b.Fmodel,a.FAuxQty,a.FAuxQty*b.F_102 as 需求pcs,a.FStatus,c.FName,b.F_149 from ["+ sql.CKDB +"].[dbo].[ICMO] a,["+ sql.CKDB +"].[dbo].[t_ICItem] b,["+ sql.CKDB +"].[dbo].[t_measureUnit] c where a. FitemId = b.FitemID and a.FUnitID = c.FMeasureUnitID) v1 left join " +
"(select a.FbatchNo,d.Fmodel,Sum(isnull(a.FAuxQty,0)) as Qty,b.FCUUnitName,Sum(isnull(a.FAuxQty,0))*b.FEntrySelfA0245 as PCS from ["+ sql.CKDB +"].[dbo].[ICStockbillentry] a,["+ sql.CKDB +"].[dbo].[vwICBill_2] b,["+ sql.CKDB +"].[dbo].[t_ICItem] d where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FitemID = d.FitemID group by a.FbatchNo,d.Fmodel,b.FEntrySelfA0245,b.FCUUnitName) v2 on v1.Fbillno = v2.Fbatchno)) a left join " +
"(select b.Fuse,SUM(b.FBaseQty) as Qty,b.FbaseUnitID from ((select b.Fuse,d.Fmodel,SUM(b.FBaseQty) as FBaseQty,b.FBaseUnitID from ["+ sql.CYDB +"].[dbo].[ICStockbillentry] a,["+ sql.CYDB +"].[dbo].[vwICBill_11] b,["+ sql.CYDB +"].[dbo].[ICStockbill] c,["+ sql.CYDB +"].[dbo].[T_ICItem] d where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FinterID = c.FinterID and d.FitemID = a.FitemID and (d.Fnumber like '11%' or d.Fnumber like '12.C%') group by b.Fuse,d.Fmodel,b.FBaseUnitID) union " +
"(select b.Fuse,d.Fmodel,SUM(b.FBaseQty) as FBaseQty,b.FBaseUnitID from ["+ sql.CKDB +"].[dbo].[ICStockbillentry] a,["+ sql.CKDB +"].[dbo].[vwICBill_11] b,["+ sql.CKDB +"].[dbo].[ICStockbill] c,["+ sql.CKDB +"].[dbo].[T_ICItem] d where a.FinterID= b.FinterID and a.FentryID = b.FentryID and a.FinterID = c.FinterID and d.FitemID = a.FitemID and (d.Fnumber like '11%' or d.Fnumber like '12.C%') group by b.Fuse,d.Fmodel,b.FBaseUnitID)) b group by b.Fuse,b.FbaseUnitID) c on a.Fbillno = c.Fuse " +
"where a.Fbillno = '" + textBox1.Text + "' ";
Load_Data(query3);
}
private void dgvDate_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex > -1)
{
string execute = Convert.ToString(this.dgvDate.Rows[e.RowIndex].Cells[3].Value);
string execute2 = Convert.ToString(this.dgvDate.Rows[e.RowIndex].Cells[4].Value);
if (execute != execute2)
{
dgvDate.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
private void ckbDate_OnChange(object sender, EventArgs e)
{
if(ckbDate.Checked == true)
{
label1.Text = "生产日期";
dateTimePicker1.Visible = true;
dateTimePicker2.Visible = true;
textBox1.Visible = false;
textBox2.Visible = false;
textBox3.Visible = false;
textBox5.Visible = false;
label2.Visible = false;
label3.Visible = false;
label6.Visible = true;
UnitOrder.Visible = false;
tableLayoutPanel1.Visible = false;
TotCheckedBox.Checked = false;
dgvDate.Visible = true;
}
else
{
label1.Text = "制造单号";
textBox1.Visible = true;
textBox5.Visible = false;
label3.Visible = true;
label3.Text = "产品名称";
textBox3.Visible = true;
dateTimePicker1.Visible = false;
label6.Visible = false;
dateTimePicker2.Visible = false;
label2.Visible = true;
textBox2.Visible = true;
UnitOrder.Visible = true;
tableLayoutPanel1.Visible = true;
dgvDate.Visible = false;
ckbDate.Checked = false;
}
}
private void TotCheckedBox_OnChange(object sender, EventArgs e)
{
if(TotCheckedBox.Checked == true)
{
label1.Text = "制单日期";
textBox1.Visible = false;
textBox5.Visible = true;
label3.Visible = true;
label3.Text = "产品名称";
textBox3.Visible = false;
dateTimePicker1.Visible = true;
label6.Visible = true;
dateTimePicker2.Visible = true;
label2.Visible = false;
textBox2.Visible = false;
UnitOrder.Visible = false;
tableLayoutPanel1.Visible = false;
dgvDate.Visible = false;
ckbDate.Checked = false;
}
else
{
label1.Text = "制造单号";
textBox1.Visible = true;
textBox5.Visible = false;
label3.Text = "产品名称";
textBox3.Visible = true;
dateTimePicker1.Visible = false;
label6.Visible = false;
dateTimePicker2.Visible = false;
label2.Visible = true;
textBox2.Visible = true;
UnitOrder.Visible = true;
tableLayoutPanel1.Visible = true;
dgvDate.Visible = false;
ckbDate.Checked = false;
}
}
private void Check_DgvData()
{
if(dataGridView1.Rows.Count == 0 || dataGridView2.Rows.Count == 0)
{
MessageBox.Show("查无信息");
}
}
private void Load_Data(string query)
{
if (query == query1)
{
DataTable dt = new DataTable();
dt = sql.getQuery(query);
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = Convert.ToString(item["日期"]);
dataGridView1.Rows[n].Cells[1].Value = Convert.ToDecimal(item["生产数量"]).ToString("N0");
dataGridView1.Rows[n].Cells[2].Value = item["生产单位"].ToString();
dataGridView1.Rows[n].Cells[3].Value = Convert.ToDecimal(item["入库数量"]).ToString("N0");
dataGridView1.Rows[n].Cells[4].Value = item["入库单位"].ToString();
dataGridView1.Rows[n].Cells[5].Value = Convert.ToDecimal(item["PCS"]).ToString("N0");
}
}
else if (query == query2)
{
DataTable dt = new DataTable();
dt = sql.getQuery(query);
foreach (DataRow item in dt.Rows)
{
int n = dataGridView2.Rows.Add();
dataGridView2.Rows[n].Cells[0].Value = Convert.ToString(item["日期"]);
dataGridView2.Rows[n].Cells[1].Value = Convert.ToDecimal(item["入库数量"]).ToString("N0");
dataGridView2.Rows[n].Cells[2].Value = item["单位"].ToString();
dataGridView2.Rows[n].Cells[3].Value = Convert.ToDecimal(item["PCS"]).ToString("N0");
}
}
else if(query == query3)
{
DataTable dt = new DataTable();
dt = sql.getQuery(query);
foreach (DataRow item in dt.Rows)
{
textBox3.Text = Convert.ToString(item["产品名称"]);
textBox2.Text = Convert.ToString(item["订单量"]);
UnitOrder.Text = Convert.ToString(item["订单单位"]);
}
}
else if (query == query4)
{
DataTable dt = new DataTable();
dt = sql.getQuery(query);
foreach (DataRow item in dt.Rows)
{
int n = dataGridView3.Rows.Add();
dataGridView3.Rows[n].Cells[0].Value = Convert.ToString(item["制造单号"]);
dataGridView3.Rows[n].Cells[1].Value = Convert.ToString(item["产品名称"]);
dataGridView3.Rows[n].Cells[2].Value = Convert.ToDecimal(item["生产数量"]).ToString("N0");
dataGridView3.Rows[n].Cells[3].Value = Convert.ToString(item["单位"]);
dataGridView3.Rows[n].Cells[4].Value = Convert.ToDecimal(item["入库数量"]).ToString("N0");
dataGridView3.Rows[n].Cells[5].Value = Convert.ToString(item["单位"]);
dataGridView3.Rows[n].Cells[6].Value = Convert.ToString(item["订单数量"]);
}
}
else if(query == query5)
{
DataSet ds = new DataSet();
ds = sql.SqlCmdDS(query);
dgvDate.DataSource = ds.Tables[0];
dgvDate.Columns[5].HeaderText = "单位";
if(dgvDate.Rows.Count == 0)
{
MessageBox.Show("查无信息");
}
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PCSamensteller;
using PCSamensteller.Controllers;
using System.Web.Mvc;
namespace PCSamenstellerTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
HomeController controller = new HomeController();
ViewResult result = controller.Index() as ViewResult;
}
}
}
|
using UnityEngine;
using TMPro;
public class MoneyUI : MonoBehaviour
{
public static int Money;
public TextMeshPro moneyText;
void Start()
{
Money = PlayerPrefs.GetInt("moni");
moneyText = GetComponent<TextMeshPro>();
}
void Update()
{
moneyText.text = Money.ToString();
}
}
|
using Manager.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Manager.UI.Controllers
{
public class JobMonitorController : Controller
{
public ActionResult Index()
{
ViewBag.jobs = new Job().GetJobs("1", "10");
return View();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _509IT_Ccode
{
public partial class Form2 : Form
{
ContactDBconn mysqlConn;
public Form2()
{
InitializeComponent();
mysqlConn = new ContactDBconn();
mysqlConn.connect();
if (mysqlConn.connOpen() == true)
dataGridView1.DataSource = mysqlConn.qry("SELECT * FROM `contact`").Tables[0];
mysqlConn.connClose();
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (mysqlConn.connOpen() == true)
{
mysqlConn.insertContact(Firstname.Text, Lastname.Text, Phone.Text, Mail.Text, Address.Text, Postcode.Text, contType.Text);
dataGridView1.DataSource = mysqlConn.qry("SELECT * FROM `contact`").Tables[0];
}
mysqlConn.connClose();
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
ID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Firstname.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
Lastname.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
Phone.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
Mail.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
Address.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
Postcode.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
contType.Text = dataGridView1.SelectedRows[0].Cells[7].Value.ToString();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (mysqlConn.connOpen() == true)
{
mysqlConn.updateContact(ID.Text, Firstname.Text, Lastname.Text, Phone.Text, Mail.Text, Address.Text, Postcode.Text, contType.Text);
dataGridView1.DataSource = mysqlConn.qry("SELECT * FROM `contact`").Tables[0];
}
mysqlConn.connClose();
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (DialogResult.Yes == MessageBox.Show("Are you sure you want to delete this record ?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
{
if (mysqlConn.connOpen() == true)
{
mysqlConn.deleteContact(ID.Text);
dataGridView1.DataSource = mysqlConn.qry("SELECT * FROM `contact`").Tables[0];
}
mysqlConn.connClose();
}
}
private void btnMainMenu_Click(object sender, EventArgs e)
{
Close();
new MainForm().Show();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
|
using System;
using Microsoft.Extensions.Logging;
// ReSharper disable once CheckNamespace
namespace NSubstitute
{
public class TraceWriter : FluentAssertions.Equivalency.Tracing.ITraceWriter
{
private readonly ILogger _logger;
public TraceWriter(ILogger logger) => _logger = logger;
public void AddSingle(string trace) => _logger.LogInformation(trace);
public IDisposable AddBlock(string trace) => _logger.BeginScope(trace);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CRM.Model
{
public enum UserType
{
[Display(Name = "Yönetici")]
Admin = 1,
[Display(Name = "Personel")]
Personal = 2
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Globalization;
using System.Web.Helpers;
using System.Web.UI;
using DotNetNuke.Common;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Framework.JavaScriptLibraries;
using DotNetNuke.UI.Utilities;
using DotNetNuke.Web.Client.ClientResourceManagement;
namespace DotNetNuke.Framework
{
internal class ServicesFrameworkImpl : IServicesFramework, IServiceFrameworkInternals
{
private const string AntiForgeryKey = "dnnAntiForgeryRequested";
private const string ScriptKey = "dnnSFAjaxScriptRequested";
public void RequestAjaxAntiForgerySupport()
{
RequestAjaxScriptSupport();
SetKey(AntiForgeryKey);
}
public bool IsAjaxAntiForgerySupportRequired
{
get { return CheckKey(AntiForgeryKey); }
}
public void RegisterAjaxAntiForgery(Page page)
{
var ctl = page.FindControl("ClientResourcesFormBottom");
if(ctl != null)
{
ctl.Controls.Add(new LiteralControl(AntiForgery.GetHtml().ToHtmlString()));
}
}
public bool IsAjaxScriptSupportRequired
{
get{ return CheckKey(ScriptKey); }
}
public void RequestAjaxScriptSupport()
{
JavaScript.RequestRegistration(CommonJs.jQuery);
SetKey(ScriptKey);
}
public void RegisterAjaxScript(Page page)
{
var path = ServicesFramework.GetServiceFrameworkRoot();
if (String.IsNullOrEmpty(path))
{
return;
}
JavaScript.RegisterClientReference(page, ClientAPI.ClientNamespaceReferences.dnn);
ClientAPI.RegisterClientVariable(page, "sf_siteRoot", path, /*overwrite*/ true);
ClientAPI.RegisterClientVariable(page, "sf_tabId", PortalSettings.Current.ActiveTab.TabID.ToString(CultureInfo.InvariantCulture), /*overwrite*/ true);
string scriptPath;
if(HttpContextSource.Current.IsDebuggingEnabled)
{
scriptPath = "~/js/Debug/dnn.servicesframework.js";
}
else
{
scriptPath = "~/js/dnn.servicesframework.js";
}
ClientResourceManager.RegisterScript(page, scriptPath);
}
private static void SetKey(string key)
{
HttpContextSource.Current.Items[key] = true;
}
private static bool CheckKey(string antiForgeryKey)
{
return HttpContextSource.Current.Items.Contains(antiForgeryKey);
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Whale.DAL.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Achivements",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Label = table.Column<string>(nullable: true),
Rarity = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Achivements", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Meetings",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Settings = table.Column<string>(nullable: true),
StartTime = table.Column<DateTimeOffset>(nullable: false),
AnonymousCount = table.Column<int>(nullable: false),
IsScheduled = table.Column<bool>(nullable: false),
IsRecurrent = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Meetings", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PollResults",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
PollId = table.Column<Guid>(nullable: false),
Title = table.Column<string>(nullable: true),
IsAnonymous = table.Column<bool>(nullable: false),
TotalVoted = table.Column<int>(nullable: false),
VoteCount = table.Column<int>(nullable: false),
MeetingId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PollResults", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
FirstName = table.Column<string>(nullable: true),
SecondName = table.Column<string>(nullable: true),
RegistrationDate = table.Column<DateTimeOffset>(nullable: false),
AvatarUrl = table.Column<string>(nullable: true),
LinkType = table.Column<int>(nullable: false),
Email = table.Column<string>(nullable: true),
Phone = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Records",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
MeetingId = table.Column<Guid>(nullable: false),
Source = table.Column<string>(nullable: true),
Type = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Records", x => x.Id);
table.ForeignKey(
name: "FK_Records_Meetings_MeetingId",
column: x => x.MeetingId,
principalTable: "Meetings",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "OptionResults",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
PollResultId = table.Column<Guid>(nullable: false),
Option = table.Column<string>(nullable: true),
VoteCount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OptionResults", x => x.Id);
table.ForeignKey(
name: "FK_OptionResults_PollResults_PollResultId",
column: x => x.PollResultId,
principalTable: "PollResults",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ContactSettings",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
UserId = table.Column<Guid>(nullable: false),
IsBloked = table.Column<bool>(nullable: false),
IsMuted = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactSettings", x => x.Id);
table.ForeignKey(
name: "FK_ContactSettings_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Participants",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Role = table.Column<int>(nullable: false),
UserId = table.Column<Guid>(nullable: false),
MeetingId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Participants", x => x.Id);
table.ForeignKey(
name: "FK_Participants_Meetings_MeetingId",
column: x => x.MeetingId,
principalTable: "Meetings",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Participants_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Settings",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
UserId = table.Column<Guid>(nullable: false),
Values = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Settings", x => x.Id);
table.ForeignKey(
name: "FK_Settings_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "UserAchivements",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Progress = table.Column<int>(nullable: false),
AchivementId = table.Column<Guid>(nullable: false),
UserId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserAchivements", x => x.Id);
table.ForeignKey(
name: "FK_UserAchivements_Achivements_AchivementId",
column: x => x.AchivementId,
principalTable: "Achivements",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UserAchivements_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Voters",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
OptionResultId = table.Column<Guid>(nullable: false),
Email = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Voters", x => x.Id);
table.ForeignKey(
name: "FK_Voters_OptionResults_OptionResultId",
column: x => x.OptionResultId,
principalTable: "OptionResults",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "DirectMessages",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ContactId = table.Column<Guid>(nullable: false),
AuthorId = table.Column<Guid>(nullable: false),
CreatedAt = table.Column<DateTimeOffset>(nullable: false),
Message = table.Column<string>(nullable: false),
Attachment = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DirectMessages", x => x.Id);
table.ForeignKey(
name: "FK_DirectMessages_Users_AuthorId",
column: x => x.AuthorId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Contacts",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
FirstMemberId = table.Column<Guid>(nullable: false),
SecondMemberId = table.Column<Guid>(nullable: false),
PinnedMessageId = table.Column<Guid>(nullable: true),
FirstMemberSettingsId = table.Column<Guid>(nullable: true),
SecondMemberSettingsId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Contacts", x => x.Id);
table.ForeignKey(
name: "FK_Contacts_Users_FirstMemberId",
column: x => x.FirstMemberId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Contacts_ContactSettings_FirstMemberSettingsId",
column: x => x.FirstMemberSettingsId,
principalTable: "ContactSettings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Contacts_DirectMessages_PinnedMessageId",
column: x => x.PinnedMessageId,
principalTable: "DirectMessages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Contacts_Users_SecondMemberId",
column: x => x.SecondMemberId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Contacts_ContactSettings_SecondMemberSettingsId",
column: x => x.SecondMemberSettingsId,
principalTable: "ContactSettings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "GroupMessages",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ContactId = table.Column<Guid>(nullable: false),
Message = table.Column<string>(nullable: false),
Attachment = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_GroupMessages", x => x.Id);
table.ForeignKey(
name: "FK_GroupMessages_Contacts_ContactId",
column: x => x.ContactId,
principalTable: "Contacts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Groups",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Label = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
PinnedMessageId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Groups", x => x.Id);
table.ForeignKey(
name: "FK_Groups_GroupMessages_PinnedMessageId",
column: x => x.PinnedMessageId,
principalTable: "GroupMessages",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "GroupUsers",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
UserId = table.Column<Guid>(nullable: false),
GroupId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_GroupUsers", x => x.Id);
table.ForeignKey(
name: "FK_GroupUsers_Groups_GroupId",
column: x => x.GroupId,
principalTable: "Groups",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_GroupUsers_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Contacts_FirstMemberId",
table: "Contacts",
column: "FirstMemberId");
migrationBuilder.CreateIndex(
name: "IX_Contacts_FirstMemberSettingsId",
table: "Contacts",
column: "FirstMemberSettingsId");
migrationBuilder.CreateIndex(
name: "IX_Contacts_PinnedMessageId",
table: "Contacts",
column: "PinnedMessageId");
migrationBuilder.CreateIndex(
name: "IX_Contacts_SecondMemberId",
table: "Contacts",
column: "SecondMemberId");
migrationBuilder.CreateIndex(
name: "IX_Contacts_SecondMemberSettingsId",
table: "Contacts",
column: "SecondMemberSettingsId");
migrationBuilder.CreateIndex(
name: "IX_ContactSettings_UserId",
table: "ContactSettings",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_DirectMessages_AuthorId",
table: "DirectMessages",
column: "AuthorId");
migrationBuilder.CreateIndex(
name: "IX_DirectMessages_ContactId",
table: "DirectMessages",
column: "ContactId");
migrationBuilder.CreateIndex(
name: "IX_GroupMessages_ContactId",
table: "GroupMessages",
column: "ContactId");
migrationBuilder.CreateIndex(
name: "IX_Groups_PinnedMessageId",
table: "Groups",
column: "PinnedMessageId");
migrationBuilder.CreateIndex(
name: "IX_GroupUsers_GroupId",
table: "GroupUsers",
column: "GroupId");
migrationBuilder.CreateIndex(
name: "IX_GroupUsers_UserId",
table: "GroupUsers",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_OptionResults_PollResultId",
table: "OptionResults",
column: "PollResultId");
migrationBuilder.CreateIndex(
name: "IX_Participants_MeetingId",
table: "Participants",
column: "MeetingId");
migrationBuilder.CreateIndex(
name: "IX_Participants_UserId",
table: "Participants",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Records_MeetingId",
table: "Records",
column: "MeetingId");
migrationBuilder.CreateIndex(
name: "IX_Settings_UserId",
table: "Settings",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_UserAchivements_AchivementId",
table: "UserAchivements",
column: "AchivementId");
migrationBuilder.CreateIndex(
name: "IX_UserAchivements_UserId",
table: "UserAchivements",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Voters_OptionResultId",
table: "Voters",
column: "OptionResultId");
migrationBuilder.AddForeignKey(
name: "FK_DirectMessages_Contacts_ContactId",
table: "DirectMessages",
column: "ContactId",
principalTable: "Contacts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Contacts_Users_FirstMemberId",
table: "Contacts");
migrationBuilder.DropForeignKey(
name: "FK_Contacts_Users_SecondMemberId",
table: "Contacts");
migrationBuilder.DropForeignKey(
name: "FK_ContactSettings_Users_UserId",
table: "ContactSettings");
migrationBuilder.DropForeignKey(
name: "FK_DirectMessages_Users_AuthorId",
table: "DirectMessages");
migrationBuilder.DropForeignKey(
name: "FK_Contacts_ContactSettings_FirstMemberSettingsId",
table: "Contacts");
migrationBuilder.DropForeignKey(
name: "FK_Contacts_ContactSettings_SecondMemberSettingsId",
table: "Contacts");
migrationBuilder.DropForeignKey(
name: "FK_Contacts_DirectMessages_PinnedMessageId",
table: "Contacts");
migrationBuilder.DropTable(
name: "GroupUsers");
migrationBuilder.DropTable(
name: "Participants");
migrationBuilder.DropTable(
name: "Records");
migrationBuilder.DropTable(
name: "Settings");
migrationBuilder.DropTable(
name: "UserAchivements");
migrationBuilder.DropTable(
name: "Voters");
migrationBuilder.DropTable(
name: "Groups");
migrationBuilder.DropTable(
name: "Meetings");
migrationBuilder.DropTable(
name: "Achivements");
migrationBuilder.DropTable(
name: "OptionResults");
migrationBuilder.DropTable(
name: "GroupMessages");
migrationBuilder.DropTable(
name: "PollResults");
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.DropTable(
name: "ContactSettings");
migrationBuilder.DropTable(
name: "DirectMessages");
migrationBuilder.DropTable(
name: "Contacts");
}
}
}
|
using Logging.Core.DataAccess;
using Logging.DataAccess.Abstract;
using Logging.DataAccess.Concrete.Context;
using Logging.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace Logging.DataAccess.Concrete
{
public class ExamQuestionDal : EntityRepositoryBase<ExamQuestion, OnlineExaminationSystemContext>, IExamQuestionDal
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "AIData", menuName = "ScriptableObjects/AIScriptableObject", order = 1)]
public class AgentProperties : ScriptableObject
{
#region HealthStatus
[Range (0,100)]
public int MaxHealth = 75;
[Range(0, 100)]
public int MaxStamina = 100;
#endregion HealthStatus
#region Attack
[Range(0, 50)]
public int Damage = 10;
[Range(0, 20)]
public float AttackRange;
#endregion Attack
#region Movement
[Header("Agent Speed")]
[Range(1, 20)]
public float Speed = 5;
[Range(1, 50)]
public float RunSpeed = 10;
[Range(1, 1440)]
public float AngularSpeed;
[Range(.5f, 20f)]
public float Acceleration;
[Range(.5f, 20f)]
public float Deceleration;
[Range(1, 1440)]
public float RunAngularSpeed;
[Range(1, 20)]
public float RunAcceleration;
#endregion Movement
#region Sightline
[Range(1, 30)]
public int VisionRadius = 10;
[Range(0, 360)]
public int VisionAngle = 25;
#endregion Sightline
#region Behaviour
[Range(0, 100)]
public int WanderChance = 10;
[Range(0, 10)]
public int PatrolWait = 2;
#endregion Behaviour
#region RegenerationRate
[Range(0.1f, 3)]
public float StaminaRegenerationRate;
#endregion RegenerationRate
} |
using System;
using System.Reflection.Metadata.Ecma335;
namespace RockPaperScissors.sln
{
class Program
{
static void Main(string[] args)
{
while(true)
{
string[] gameChoice = new string[] { "Rock", "Paper", "Scissors" };
Random rnd = new Random();
Console.Write("Hello, how many rounds of Rock Paper Scissors would you like to play? (Minimum: 1; Maximum: 10) ");
int numberOfRounds = Convert.ToInt32(Console.ReadLine());
if (numberOfRounds < 1 || numberOfRounds > 10)
{
Console.WriteLine("Error: Number of rounds is outside range.");
}
else
{
int tieNumber = 0;
int userWinNumber = 0;
int computerWinNumber = 0;
int roundNumber = 1;
while (roundNumber <= numberOfRounds)
{
Console.Write("Choose: (1 = Rock, 2 = Paper, 3 = Scissors) ");
int userIndex = Convert.ToInt32(Console.ReadLine()) - 1;
int cIndex = rnd.Next(gameChoice.Length);
bool userWin = (userIndex == 0 && cIndex == 2) || (userIndex == 1 && cIndex == 0) || (userIndex == 2 && cIndex == 1);
bool computerWin = (userIndex == 0 && cIndex == 1) || (userIndex == 1 && cIndex == 2) || (userIndex == 2 && cIndex == 0);
Console.WriteLine($"You chose {gameChoice[userIndex]} and the computer chose {gameChoice[cIndex]}");
if (userIndex == cIndex)
{
Console.WriteLine("This round is a tie");
tieNumber++;
roundNumber++;
}
else if (userWin)
{
Console.WriteLine("You win this round!");
userWinNumber++;
roundNumber++;
}
else if (computerWin)
{
Console.WriteLine("Computer Wins this round.");
computerWinNumber++;
roundNumber++;
}
}
Console.WriteLine($"Number of Rounds You Won: {userWinNumber} \nNumber of Rounds Computer Won: {computerWinNumber} rounds \nNumber of ties: {tieNumber}");
if (userWinNumber > computerWinNumber)
{
Console.WriteLine("Congrats are the winner!");
}
else if (computerWinNumber > userWinNumber)
{
Console.WriteLine("The computer is the winner!");
}
else
{
Console.WriteLine("This game was a tie");
}
Console.Write("Would you like to play again? (y/n) ");
string playAgain = Console.ReadLine();
if (playAgain.ToLower().Equals("y"))
{
continue;
}
else
{
Console.WriteLine("Thanks for playing!");
break;
}
}
}
}
}
}
|
using MongoDB.Bson.Serialization.Attributes;
using Newtonsoft.Json;
using Serilog.Ui.Core;
using System;
using System.Collections.Generic;
using System.Dynamic;
namespace Serilog.Ui.MongoDbProvider
{
[BsonIgnoreExtraElements]
public class MongoDbLogModel
{
[BsonIgnore]
public int Id { get; set; }
public string Level { get; set; }
public string RenderedMessage { get; set; }
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime? Timestamp { get; set; }
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime UtcTimeStamp { get; set; }
public dynamic Exception { get; set; }
public object Properties { get; set; }
internal LogModel ToLogModel()
{
return new LogModel
{
RowNo = Id,
Level = Level,
Message = RenderedMessage,
Timestamp = Timestamp ?? UtcTimeStamp,
Exception = GetException(Exception),
Properties = Newtonsoft.Json.JsonConvert.SerializeObject(Properties),
PropertyType = "json"
};
}
private object GetException(dynamic exception)
{
if (exception == null || IsPropertyExist(Exception, "_csharpnull"))
return null;
if (exception is string)
return exception;
return Newtonsoft.Json.JsonConvert.SerializeObject(Exception, Formatting.Indented);
}
private bool IsPropertyExist(dynamic obj, string name)
{
if (obj is ExpandoObject)
return ((IDictionary<string, object>)obj).ContainsKey(name);
return obj?.GetType()?.GetProperty(name) != null;
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CyberPunkRPG
{
class BarbedWire : GameObject
{
Rectangle position;
public Rectangle hitBox;
public float slowMultiplier;
public BarbedWire(Vector2 pos, Rectangle position) : base(pos)
{
this.position = position;
hitBox = position;
slowMultiplier = 50;
}
public override void Draw(SpriteBatch sb)
{
sb.Draw(AssetManager.wireTex, position, Color.White);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BooksDestination.Data;
using BooksDestination.Model;
namespace BooksDestination.Services
{
public class SqlBookData : IBookData
{
private BooksDestinationDbContext _context;
public SqlBookData(BooksDestinationDbContext context)
{
_context = context;
}
public BookRepo AddBook(BookRepo book)
{
_context.BookRepo.Add(book);
_context.SaveChanges();
return book;
}
public IEnumerable<BookRepo> GetAll()
{
return _context.BookRepo.OrderBy(b => b.BookId);
}
public BookRepo GetBookById(int id)
{
return _context.BookRepo.FirstOrDefault(b => b.BookId == id);
}
}
}
|
using Microsoft.Office.Tools.Ribbon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FHLVoiceSearch
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
MessageBox.Show("Hi there! :)");
Globals.ThisAddIn.Application.ActiveExplorer().Search("from:Raj", Microsoft.Office.Interop.Outlook.OlSearchScope.olSearchScopeAllFolders);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SelfAction : MonoBehaviour {
private GameObject camera1, mainCamera;
public GameObject storyThing,magic02;
public AudioClip ac;
public IUnityEvent reward;
private bool isAction;
private bool isGot=false;
public GameObject water;
private void Start()
{
camera1 = GameObject.Find("/Cameras/Camera1");
mainCamera = Camera.main.gameObject;
camera1.SetActive(false);
}
private void Update()
{
if (isAction)
{
storyThing.transform.position = Vector3.Lerp(storyThing.transform.position, storyThing.transform.position+ new Vector3(0, 1, 0), Time.deltaTime);
if (storyThing.transform.localPosition.y >= 10.8)
{
water.layer = 9;
water.GetComponent<MeshCollider>().isTrigger = true;
Invoke("Action2", 3.5f);
isAction = false;
}
}
}
public void Action()
{
magic02.transform.GetChild(0).gameObject.SetActive(false);
camera1.gameObject.SetActive(true);
camera1.GetComponent<Camera>().enabled = true;
mainCamera.GetComponent<Camera>().enabled = false;
isAction = true;
MusicManager.Instance.PlayMusic(ac);
}
private void Action2()
{
mainCamera.GetComponent<Camera>().enabled = true;
mainCamera.gameObject.SetActive(true);
camera1.gameObject.SetActive(false);
camera1.GetComponent<Camera>().enabled = false;
reward.Invoke(1);
if (!isGot)
{
PlayerMes.getInstance().Snum++;
isGot = true;
}
}
}
|
using PNPUCore.Database;
using PNPUCore.Process;
using PNPUTools;
using System;
using System.Collections.Generic;
namespace PNPUCore
{
/// <summary>
/// Cette classe permet de gérer le lancement des process.
/// </summary>
public class Launcher
{
void LaunchProcess(IProcess process)
{
process.ExecuteMainProcess();
String json = process.FormatReport();
process.SaveReportInBDD(json, process);
Console.WriteLine(json);
}
/// <summary>
/// Lancement d'une process pour un client.
/// </summary>
/// <param name="clientName">Client pour lequel on lance le preocess.</param>
/// <param name="processName">Nom du process à lancer.</param>
public void Launch(String listclientId, int workflowId, int processId)
{
IProcess process = CreateProcess(processId, workflowId, listclientId);
LaunchProcess(process);
}
IProcess CreateProcess(int process, int workflowId, String client)
{
switch (process)
{
case ParamAppli.ProcessControlePacks:
return ProcessControlePacks.CreateProcess(workflowId, client);
case ParamAppli.ProcessAnalyseImpact:
return ProcessAnalyseImpact.CreateProcess(workflowId, client);
case ParamAppli.ProcessInit:
return ProcessInit.CreateProcess(workflowId, client);
case ParamAppli.ProcessGestionDependance:
return ProcessGestionDependance.CreateProcess(workflowId, client);
case ParamAppli.ProcessIntegration:
return ProcessIntegration.CreateProcess(workflowId, client);
case ParamAppli.ProcessProcessusCritique:
return ProcessProcessusCritique.CreateProcess(workflowId, client);
case ParamAppli.ProcessTNR:
return ProcessTNR.CreateProcess(workflowId, client);
case ParamAppli.ProcessLivraison:
return ProcessLivraison.CreateProcess(workflowId, client);
default:
return ProcessMock.CreateProcess(workflowId, client);
}
}
}
}
|
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
namespace NopSolutions.NopCommerce.DataAccess.Payment
{
/// <summary>
/// Acts as a base class for deriving custom credit card type provider
/// </summary>
[DBProviderSectionName("nopDataProviders/CreditCardTypeProvider")]
public abstract partial class DBCreditCardTypeProvider : BaseDBProvider
{
#region Methods
/// <summary>
/// Gets a credit card type
/// </summary>
/// <param name="CreditCardTypeID">Credit card type identifier</param>
/// <returns>Credit card type</returns>
public abstract DBCreditCardType GetCreditCardTypeByID(int CreditCardTypeID);
/// <summary>
/// Gets all credit card types
/// </summary>
/// <returns>Credit card type collection</returns>
public abstract DBCreditCardTypeCollection GetAllCreditCardTypes();
/// <summary>
/// Inserts a credit card type
/// </summary>
/// <param name="Name">The name</param>
/// <param name="SystemKeyword">The system keyword</param>
/// <param name="DisplayOrder">The display order</param>
/// <param name="Deleted">A value indicating whether the entity has been deleted</param>
/// <returns>A credit card type</returns>
public abstract DBCreditCardType InsertCreditCardType(string Name, string SystemKeyword, int DisplayOrder, bool Deleted);
/// <summary>
/// Updates the credit card type
/// </summary>
/// <param name="CreditCardTypeID">Credit card type identifier</param>
/// <param name="Name">The name</param>
/// <param name="SystemKeyword">The system keyword</param>
/// <param name="DisplayOrder">The display order</param>
/// <param name="Deleted">A value indicating whether the entity has been deleted</param>
/// <returns>A credit card type</returns>
public abstract DBCreditCardType UpdateCreditCardType(int CreditCardTypeID, string Name, string SystemKeyword,
int DisplayOrder, bool Deleted);
#endregion
}
}
|
namespace _3.GroupNumbers
{
using System;
using System.Linq;
public class Startup
{
public static void Main(string[] args)
{
var numbers = Console.ReadLine()
.Split(new string[] {", "}, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
var zero = numbers.Where(n => Math.Abs(n) % 3 == 0).ToArray();
var one = numbers.Where(n => Math.Abs(n) % 3 == 1).ToArray();
var two = numbers.Where(n => Math.Abs(n) % 3 == 2).ToArray();
Console.WriteLine(string.Join(" ", zero));
Console.WriteLine(string.Join(" ", one));
Console.WriteLine(string.Join(" ", two));
}
}
}
|
using System;
namespace api.Models.Request
{
public class FuncionarioRequest
{
public string funcionario { get; set; }
public string cargo { get; set; }
public DateTime nascimento { get; set; }
public string cpf { get; set; }
public string endereco { get; set; }
public string cep { get; set; }
public string complemento { get; set; }
public string telefone { get; set; }
public string email { get; set; }
public string foto { get; set; }
public string curriculo { get; set; }
public string usuario { get; set; }
public string senha { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace prjSellor.Models
{
public class DefaultSchedule
{
[Key]
public string day { get; set; }
public int timeSlace { get; set; }
public DateTime startTime { get; set; }
public DateTime endTime { get; set; }
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using WebApplication.Data.DataModels.Laptops;
using WebApplication.Data.Repositories.Laptops;
using WebApplication.Services.DtoModels;
namespace WebApplication.Services.Services.ShoppingBasket
{
public class ShoppingBasketService : IShoppingBasketService
{
private readonly IMapper _mapper;
private readonly IBasketRepository _basketRepository;
private readonly ILaptopRepository _laptopRepository;
public ShoppingBasketService(IMapper mapper, IBasketRepository basketRepository, ILaptopRepository laptopRepository)
{
_mapper = mapper;
_basketRepository = basketRepository;
_laptopRepository = laptopRepository;
}
public async Task<BasketDtoModel> AddLaptop(int model)
{
var data = await _basketRepository.FindByCondition(x => x.LaptopId == model).FirstOrDefaultAsync();
if (data != null) return null;
var laptop = await _laptopRepository.FindByCondition(x => x.Id == model).FirstOrDefaultAsync();
if (laptop == null) return null;
var basket = new Basket
{
LaptopId = laptop.Id
};
await _basketRepository.AddAsync(basket);
await _basketRepository.SaveAsync();
return _mapper.Map<BasketDtoModel>(basket);
}
public async Task<List<BasketDtoModel>> GetLaptopList()
{
var data = await _basketRepository
.GetAll()
.ToListAsync();
return _mapper.Map<List<BasketDtoModel>>(data);
}
public async Task RemoveLaptopList()
{
var data = await _basketRepository.GetAll().ToListAsync();
data.ForEach(item => { _basketRepository.Delete(item); });
await _basketRepository.SaveAsync();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using liteCMS.Web.Controller;
using liteCMS.Logic;
using liteCMS.Entity.Ventas;
using System.Data;
using System.IO;
using System.Data.OleDb;
namespace liteCMS.Web.Admin.Ventas
{
public partial class Ventas : AdmNavigation
{
lAdministrador cAdministrador = new lAdministrador();
lVentas cVentas = new lVentas();
string OrderBy = string.Empty;
const string CMD_Listar = "Listar";
const string CMD_Administrar = "Administrar";
short IdVentas;
protected void Page_Load(object sender, EventArgs e)
{
IdVentas = (Request["fID"] != null) ? Convert.ToInt16(Request["fID"]) : Convert.ToByte(0);
if (!Page.IsCallback && !Page.IsPostBack)
{
if (!SetPage(ModuloID)) return;
if (!validateUserAction(ModuloID, CMD_Listar)) return;
pnlForm.Attributes.Add("style", "display:none");
pnlImport.Attributes.Add("style", "display:none");
BindListado();
btnAddNew.Enabled = validateUserAction(ModuloID, CMD_Administrar);
}
}
private void BindListado()
{
lblError.Text = string.Empty;
List<eVenta> lVenta = lVentas.Venta_listar(txtSearch.Text);
grvListado.DataSource = !OrderBy.Equals("") ? lVentas.Venta_Sort(lVenta, OrderBy) : lVenta;
grvListado.DataBind();
}
private void FillDetalle(int ventaID)
{
eVenta oVenta = lVentas.Venta_item(ventaID);
if (oVenta != null)
{
txtCodigoCliente.Text = oVenta.codigoCliente;
txtProducto.Text = oVenta.producto;
txtAno2015.Text = oVenta.ano2015;
txtAno2016.Text = oVenta.ano2016;
txtAno2017.Text = oVenta.ano2017;
txtAno2018.Text = oVenta.ano2018;
txtAno2019.Text = oVenta.ano2019;
txtAno2020.Text = oVenta.ano2020;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (!validateUserAction(ModuloID, CMD_Administrar)) return;
eVenta oVenta = new eVenta();
bool success = false;
if (txtCodigoCliente.Text != "")
{
oVenta.codigoCliente = txtCodigoCliente.Text;
oVenta.producto = txtProducto.Text;
oVenta.ano2015 = txtAno2015.Text;
oVenta.ano2016 = txtAno2016.Text;
oVenta.ano2017 = txtAno2017.Text;
oVenta.ano2018 = txtAno2018.Text;
oVenta.ano2019 = txtAno2019.Text;
oVenta.ano2020 = txtAno2020.Text;
if (grvListado.SelectedIndex >= 0)
{
oVenta.codigoVenta = int.Parse(grvListado.SelectedDataKey.Value.ToString());
success = lVentas.Venta_edit(oVenta);
RegistrarLog(ModuloID, CMD_Administrar, "Se ha actualizado la Venta: " + oVenta.codigoVenta.ToString());
}
else
{
RegistrarLog(ModuloID, CMD_Administrar, "Se ha insertado una Nueva Venta: " + oVenta.codigoVenta.ToString());
success = lVentas.Venta_add(oVenta);
}
}
if (success)
{
modDetalle.Hide();
BindListado();
}
else
{
lblFormError.Text = lVentas.getErrorMessage();
}
}
private void ClearFormDetalle()
{
lblFormError.Text = string.Empty;
txtCodigoCliente.Text = string.Empty;
txtProducto.Text = string.Empty;
txtAno2015.Text = string.Empty;
txtAno2016.Text = string.Empty;
txtAno2017.Text = string.Empty;
txtAno2018.Text = string.Empty;
txtAno2019.Text = string.Empty;
txtAno2020.Text = string.Empty;
}
protected void grvListado_SelectedIndexChanged(object sender, EventArgs e)
{
if (!validateUserAction(ModuloID, CMD_Listar)) return;
//txtCodigoCliente.Enabled = false;
lblSubtitulo.Text = "Detalle de la Venta";
int ventaID = int.Parse(grvListado.SelectedDataKey.Value.ToString());
ClearFormDetalle();
FillDetalle(ventaID);
modDetalle.Show();
}
protected void grvListado_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewHelper grwHelper = new GridViewHelper(grvListado);
string SortType = (ViewState["SortType"] != null) ? ViewState["SortType"].ToString() : "";
ViewState["SortType"] = grwHelper.SetGridView_Sorting(SortType, e.SortExpression);
OrderBy = e.SortExpression + " " + ViewState["SortType"];
BindListado();
}
protected void grvListado_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (!validateUserAction(ModuloID, CMD_Administrar)) return;
int ventaID = int.Parse(grvListado.DataKeys[e.RowIndex].Value.ToString());
if (lVentas.Venta_delete(ventaID))
{
RegistrarLog(ModuloID, CMD_Administrar, "Se ha eliminado la Venta: " + ventaID.ToString());
BindListado();
}
else
lblError.Text = lVentas.getErrorMessage();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindListado();
}
protected void grvListado_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grvListado.PageIndex = e.NewPageIndex;
BindListado();
}
protected void btnExportar_Click(object sender, EventArgs e)
{
//grvListado.Columns[0].Visible = false;
DataTable dtFormularios = lVentas.Venta_listar_Export(txtSearch.Text);
grvListado_Export.DataSource = dtFormularios;
grvListado_Export.DataBind();
GridViewHelper grwHelper = new GridViewHelper(grvListado_Export);
string htmExcel = grwHelper.RenderGridView_Export();
string fileName = "Venta" + IdVentas.ToString() + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
ResponseHeaderDocument(fileName, htmExcel);
}
protected void grvListado_RowDataBound(object sender, GridViewRowEventArgs e)
{
eVenta oVenta = (eVenta)e.Row.DataItem;
if (oVenta != null)
{
//e.Row.Font.Bold = true;
try { e.Row.Cells[4].Text = (Decimal.Parse(oVenta.ano2015) / 1000).ToString("N0"); }
catch { }
try { e.Row.Cells[5].Text = (Decimal.Parse(oVenta.ano2016) / 1000).ToString("N0"); }
catch { }
try { e.Row.Cells[6].Text = (Decimal.Parse(oVenta.ano2017) / 1000).ToString("N0"); }
catch { }
try { e.Row.Cells[7].Text = (Decimal.Parse(oVenta.ano2018) / 1000).ToString("N0"); }
catch { }
try { e.Row.Cells[8].Text = (Decimal.Parse(oVenta.ano2019) / 1000).ToString("N0"); }
catch { }
try { e.Row.Cells[9].Text = (Decimal.Parse(oVenta.ano2020) / 1000).ToString("N0"); }
catch { }
}
}
protected void btnAddNew_Click(object sender, EventArgs e)
{
if (!validateUserAction(ModuloID, CMD_Administrar)) return;
//txtCodigoCliente.Enabled = true;
lblSubtitulo.Text = "Nueva Venta";
grvListado.SelectedIndex = -1;
ClearFormDetalle();
modDetalle.Show();
}
protected void btnImportar_Click(object sender, EventArgs e)
{
if (!validateUserAction(ModuloID, CMD_Administrar)) return;
grvListado.SelectedIndex = -1;
modImport.Show();
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string FolderPath = ClientScriptHelper.getURLRoot() + "Upload/tmp/";
string FileName, Extension, FilePath;
DataTable dt;
if (fupImport1.HasFile)
{
//Elimina todos los registros de la tabla.
lVentas.Venta_Clean();
try
{
//FileName = Path.GetFileName(fupImport1.PostedFile.FileName);
FileName = Guid.NewGuid().ToString();
Extension = Path.GetExtension(fupImport1.PostedFile.FileName);
FilePath = Server.MapPath(FolderPath + FileName + Extension);
fupImport1.SaveAs(FilePath);
dt = Util.ExcelReader.LoadExcelData(FilePath, Extension, true);
Import_FromClient(dt);
lVentas.Update_FechaImport();
}
catch (Exception ex)
{
//lblErrorImport.Text = ex.Message;
ClientScript.RegisterClientScriptBlock(this.GetType(), "import", "alert('Ocurrió un error al importar el documento. " + ex.Message + "');", true);
return;
}
}
modImport.Hide();
BindListado();
}
private int Import_FromClient(DataTable dt)
{
int inserts = 0;
int fails = 0;
foreach (DataRow dr in dt.Rows)
{
if (dr[0].ToString().Trim() == string.Empty || dr[1].ToString().Trim() == string.Empty) continue;
eVenta oVenta = new eVenta();
oVenta.codigoCliente = dr[0].ToString();
oVenta.producto = dr[1].ToString();
try { oVenta.ano2015 = dr[2].ToString(); }
catch { }
try { oVenta.ano2016 = dr[3].ToString(); }
catch { }
try { oVenta.ano2017 = dr[4].ToString(); }
catch { }
try { oVenta.ano2018 = dr[5].ToString(); }
catch { }
try { oVenta.ano2019 = dr[6].ToString(); }
catch { }
try { oVenta.ano2020 = dr[7].ToString(); }
catch { }
if (lVentas.Venta_add(oVenta))
inserts++;
else
fails++;
}
ClientScript.RegisterClientScriptBlock(this.GetType(), "import", "alert('Se han importado " + inserts + " registros, y " + fails + " fallidos.');", true);
return inserts;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace Core.Domain
{
public class Campaign
{
[Key]
public string Code { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Campaign(string code , string name, string description)
{
this.Code = code;
this.Name = name;
this.Description = description;
}
public Campaign(string code)
{
this.Code = code;
}
public Campaign()
{
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
public class WeightedAIPlayer : AIPlayer
{
/// <summary>
/// Weighting values.
/// Larger spread will make the AI more difficult in general.
/// </summary>
private int attackWeight;
private int safeWeight;
private int wayWeight;
private int neutralWeight;
private int badWeight;
public enum Difficulty { Easy, Normal, Hard }
public Difficulty difficulty;
/// <summary>
/// The bad moves.
/// </summary>
public List<WeightedMove> BadMoves;
/// <summary>
/// The neutral moves.
/// </summary>
public List<WeightedMove> NeutralMoves;
/// <summary>
/// The way moves.
/// </summary>
public List<WeightedMove> WayMoves;
/// <summary>
/// The safe moves.
/// </summary>
public List<WeightedMove> SafeMoves;
/// <summary>
/// The attack moves.
/// </summary>
public List<WeightedMove> AttackMoves;
/// <summary>
/// Default constructor.
/// </summary>
public WeightedAIPlayer()
{
BadMoves = new List<WeightedMove>();
NeutralMoves = new List<WeightedMove>();
WayMoves = new List<WeightedMove>();
SafeMoves = new List<WeightedMove>();
AttackMoves = new List<WeightedMove>();
moves = new Dictionary<PieceTower, HashSet<TileNode>>();
}
/// <summary>
/// Constructor that changes the weights based on difficulty.
/// </summary>
/// <param name="difficulty">The difficulty of the AI</param>
public WeightedAIPlayer(Difficulty difficulty)
{
BadMoves = new List<WeightedMove>();
NeutralMoves = new List<WeightedMove>();
WayMoves = new List<WeightedMove>();
SafeMoves = new List<WeightedMove>();
AttackMoves = new List<WeightedMove>();
moves = new Dictionary<PieceTower, HashSet<TileNode>>();
this.difficulty = difficulty;
WeightDifficulty(difficulty);
}
/// <summary>
/// Sets the weights based on the difficulty of the AI.
/// </summary>
/// <param name="difficulty">The difficulty of the AI</param>
public void WeightDifficulty(Difficulty difficulty)
{
switch (difficulty)
{
case Difficulty.Easy:
attackWeight = 250;
safeWeight = 25;
wayWeight = 75;
neutralWeight = 150;
badWeight = 500;
break;
case Difficulty.Normal:
attackWeight = 400;
safeWeight = 100;
wayWeight = 100;
neutralWeight = 250;
badWeight = 150;
break;
case Difficulty.Hard:
attackWeight = 800;
safeWeight = 125;
wayWeight = 60;
neutralWeight = 10;
badWeight = 5;
break;
}
}
/// <summary>
/// Weights the moves.
/// Takes all available moves and
/// puts them in the lists / categories
/// intialized in the contructor
/// </summary>
/// <param name="moves">Moves.</param>
public void WeightMoves(Dictionary<PieceTower, HashSet<TileNode>> moves)
{
List<PieceTower> towers = new List<PieceTower>(moves.Keys);
foreach (PieceTower pieceTower in towers)
{
// Indicates if this tower can be attacked by another tower
bool srcThreatened = CheckThreat(pieceTower.GetNode());
foreach (TileNode tile in moves[pieceTower])
{
// Indicates if this tile can be reached by another tower
bool destThreatened = CheckThreat(tile);
// Check for attacking
if (tile.tower != null && tile.tower.owningColour != colour)
{
int attackValue = WeightAttackValue(tile.tower);
AttackMoves.Add(new WeightedMove(pieceTower, tile, attackWeight, attackValue));
}
// Check if this tile can be reached by an opponent, and the target tile cannot
else if (srcThreatened && !destThreatened)
{
SafeMoves.Add(new WeightedMove(pieceTower, tile, safeWeight));
}
// Getting off the way
else if ((pieceTower.GetNode().type == TileNode.Type.Way || pieceTower.GetNode().type == TileNode.Type.WayCross)
&& (tile.type != TileNode.Type.Way && tile.type != TileNode.Type.WayCross))
{
SafeMoves.Add(new WeightedMove(pieceTower, tile, safeWeight));
}
//If it's a way move
else if (tile.type == TileNode.Type.Way || tile.type == TileNode.Type.WayCross)
{
WayMoves.Add(new WeightedMove(pieceTower, tile, wayWeight));
}
// Check if it's a move that gets onto the way
else if ((tile.type == TileNode.Type.Way || tile.type == TileNode.Type.WayCross) && tile.tower == null)
{
WayMoves.Add(new WeightedMove(pieceTower, tile, wayWeight));
}
//If tile can be attacked by another player
else if (destThreatened)
{
BadMoves.Add(new WeightedMove(pieceTower, tile, badWeight));
}
// All other moves fall into this category
else
{
NeutralMoves.Add(new WeightedMove(pieceTower, tile, neutralWeight));
}
}
}
}
/// <summary>
/// Checks the value of each move by
/// determining each tower's size
/// and if they have a hook tile or not
/// </summary>
/// <returns> attackValue, the nurmerical value of the attac. </returns>
/// <param name="piece">Piece of who's value we are determining. </param>
public int WeightAttackValue (PieceTower piece)
{
int attackValue = 0;
foreach (PieceData pieceValue in piece.pieces)
{
if (pieceValue.isHook())
{
attackValue += 2;
}
else
{
attackValue += 1;
}
}
return attackValue;
}
/// <summary>
/// Checks all enemy moves and if one of those
/// moves is the input tile threat returns true
/// otherwise there is not threat to said tile
/// </summary>
/// <returns><c>true</c>, if threat was checked on tile input, <c>false</c> otherwise.</returns>
/// <param name="tile">Tile, the current tile of a tower</param>
public Boolean CheckThreat(TileNode tile)
{
foreach (Player enemy in TurnHandler.players)
{
if (!enemy.colour.Equals(colour))
{
foreach (PieceTower enemyTower in Towers)
{
HashSet<TileNode> moves = enemyTower.GetMoves().Destinations;
foreach (TileNode move in moves)
{
if (move.Equals(tile))
{
return true;
}
}
}
}
}
// No threat
return false;
}
/// <summary>
/// Returns the piece to be moved and the destination
/// </summary>
/// <param name="piece">Piece.</param>
/// <param name="dest">Destination.</param>
public WeightedMove Move(PieceTower piece, TileNode dest)
{
return new WeightedMove(piece, dest, 1);
}
public override WeightedMove ForcedWay(PieceTower tower, HashSet<TileNode> moves)
{
// Check if anything is attackable
foreach (TileNode tile in moves)
{
if (tile.tower != null && tile.tower.owningColour != colour)
{
return new WeightedMove(tower, tile, 1);
}
}
// Random move
return base.ForcedWay(tower, moves);
}
/// <summary>
/// Picks attack moves from the pool of attack moves based on difficulty.
/// Easy and Normal not yet implimented.
/// Hard picks the strongest moves available and discards all others.
/// </summary>
/// <param name="AttackMoves">The pool of attack moves to choose from</param>
public void PickAttackMoves(List<WeightedMove> AttackMoves)
{
switch (difficulty)
{
case Difficulty.Easy:
break;
case Difficulty.Normal:
break;
case Difficulty.Hard:
int curTowerSize = 6;
List<WeightedMove> newAttackMoves = new List<WeightedMove>();
AttackMoves.Sort((x, y) => x.attackValue.CompareTo(y.attackValue));
while (curTowerSize > 0)
{
foreach (WeightedMove move in AttackMoves)
{
if (move.attackValue >= curTowerSize)
{
newAttackMoves.Add(move);
}
}
if (newAttackMoves.Count > 0)
{
AttackMoves = newAttackMoves;
newAttackMoves.Clear();
curTowerSize = -1;
}
else
{
newAttackMoves.Clear();
curTowerSize--;
}
}
break;
}
}
/// <summary>
/// Ties the WeightedAI together, gets the
/// moves, picks one and executes
/// </summary>
/// <returns>The turn.</returns>
public override WeightedMove DoTurn()
{
moves = GetAllAvailableMoves();
WeightMoves(moves);
WeightedMove pickedMove = null;
//Attempts before defaulting to random move
int Attempts = 10;
while (Attempts > 0)
{
int maxRoll = 999;
int roll = new System.Random().Next(maxRoll + 1);
if (roll > maxRoll - attackWeight && AttackMoves.Count > 0)
{
PickAttackMoves(AttackMoves);
pickedMove = AttackMoves[new System.Random().Next(0, AttackMoves.Count)];
UnityEngine.Debug.Log(pickedMove.attackValue);
UnityEngine.Debug.Log("Attack move picked");
}
else if (roll > maxRoll - attackWeight - safeWeight && SafeMoves.Count > 0)
{
pickedMove = SafeMoves[new System.Random().Next(0, SafeMoves.Count)];
UnityEngine.Debug.Log("Safe move picked");
}
else if (roll > maxRoll - attackWeight - safeWeight - wayWeight && WayMoves.Count > 0)
{
pickedMove = WayMoves[new System.Random().Next(0, WayMoves.Count)];
UnityEngine.Debug.Log("Way move picked");
}
else if (roll > maxRoll - attackWeight - safeWeight - wayWeight - neutralWeight && NeutralMoves.Count > 0)
{
pickedMove = NeutralMoves[new System.Random().Next(0, NeutralMoves.Count)];
UnityEngine.Debug.Log("Way move picked");
}
else if (BadMoves.Count > 0)
{
pickedMove = BadMoves[new System.Random().Next(0, BadMoves.Count)];
UnityEngine.Debug.Log("Bad move picked");
}
if (pickedMove != null)
{
break;
}
Attempts--;
}
//Empty out all saved moves
BadMoves.Clear();
WayMoves.Clear();
SafeMoves.Clear();
AttackMoves.Clear();
//No valid moves, or failed to choose
if (Attempts == 0)
{
UnityEngine.Debug.Log("WeightedAI could not decide. Random Move.");
return RandomMove();
}
else
{
UnityEngine.Debug.Log("WeightedAI moved.");
return pickedMove;
}
}
/// <summary>
/// called when this player's turn starts
/// </summary>
public override void TurnStart()
{
DisplayTurnDisplay();
}
/// <summary>
/// Called when this player's turn starts
/// </summary>
public override void TurnEnd()
{
}
/// <summary>
/// called when this player's turn was skipped
/// </summary>
public override void TurnSkipped()
{
}
}
|
using UnityEngine;
using UnityEngine.UI;
namespace UI.StorageModal
{
class DataRow : MonoBehaviour
{
public Text Name = null;
public Text Value = null;
public void Set(string name, string value)
{
Name.text = name;
Value.text = value;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Web;
using URISUtil.DataAccess;
using URISUtil.Logging;
using URISUtil.Response;
using WallCommentMicroService.Models;
namespace WallCommentMicroService.DataAccess
{
public class CommentDB
{
private static Comment ReadRow(SqlDataReader reader)
{
Comment retVal = new Comment
{
Id = (Guid)reader["id"],
TextComment = reader["textComment"] as string,
UserId = (Guid)reader["user_id"] ,
PostId = (Guid)reader["post_id"] ,
Active = (bool)reader["active"]
};
return retVal;
}
private static void ReadId(SqlDataReader reader, Comment comment)
{
comment.Id = (Guid)reader["id"];
}
private static string AllColumnSelect
{
get
{
return @"
[Comment].[id],
[Comment].[textComment],
[Comment].[user_id],
[Comment].[post_id],
[Comment].[active]
";
}
}
private static void FillData(SqlCommand command, Comment comment)
{
command.AddParameter("@Id", SqlDbType.UniqueIdentifier, comment.Id);
command.AddParameter("@TextComment", SqlDbType.NVarChar, comment.TextComment);
command.AddParameter("@UserId", SqlDbType.UniqueIdentifier, comment.UserId);
command.AddParameter("@PostId", SqlDbType.UniqueIdentifier, comment.PostId);
command.AddParameter("@Active", SqlDbType.Bit, comment.Active);
}
public static List<Comment> GetCommentsByPostId(ActiveStatusEnum active, string id)
{
try
{
List<Comment> retVal = new List<Comment>();
using (SqlConnection connection = new SqlConnection(DBFunctions.ConnectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = String.Format(@"
SELECT {0}
FROM [comment].[Comment]
WHERE ([comment].[Comment].post_id = @Id)
AND ([comment].[Comment].active = @Active)
", AllColumnSelect);
command.AddParameter("@Id", SqlDbType.NVarChar, id);
command.Parameters.Add("@Active", SqlDbType.Bit);
switch (active)
{
case ActiveStatusEnum.Active:
command.Parameters["@Active"].Value = true;
break;
case ActiveStatusEnum.Inactive:
command.Parameters["@Active"].Value = false;
break;
case ActiveStatusEnum.All:
command.Parameters["@Active"].Value = DBNull.Value;
break;
}
System.Diagnostics.Debug.WriteLine(command.CommandText);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
retVal.Add(ReadRow(reader));
}
}
}
return retVal;
}
catch(Exception ex)
{
Logger.WriteLog(ex);
return null;
throw ErrorResponse.ErrorMessage(HttpStatusCode.BadRequest, ex);
}
}
public static Comment GetComment(Guid id)
{
try
{
Comment retVal = new Comment();
using(SqlConnection connection = new SqlConnection(DBFunctions.ConnectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = String.Format(@"
SELECT {0} FROM [comment].[Comment]
WHERE [comment].[Comment].Id = @Id;
", AllColumnSelect);
command.AddParameter("@Id", SqlDbType.UniqueIdentifier, id);
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
retVal = ReadRow(reader);
}
else
{
return null;
}
}
}
return retVal;
}
catch(Exception ex)
{
Logger.WriteLog(ex);
throw ErrorResponse.ErrorMessage(HttpStatusCode.BadRequest, ex);
}
}
public static Comment InsertComment(Comment comment)
{
try
{
using(SqlConnection connection = new SqlConnection(DBFunctions.ConnectionString))
{
SqlCommand command = connection.CreateCommand();
Guid id = Guid.NewGuid();
comment.Id = id;
command.CommandText = String.Format(@"
INSERT INTO [comment].[Comment]
(
[id],
[textComment],
[post_id],
[user_id],
[active]
)
VALUES
(
@Id,
@TextComment,
@PostId,
@UserId,
@Active
)
");
FillData(command, comment);
if(comment.TextComment == null || comment.TextComment == "")
{
return null;
}
connection.Open();
command.ExecuteNonQuery();
return GetComment(comment.Id);
}
}
catch(Exception ex)
{
Logger.WriteLog(ex);
return null;
throw ErrorResponse.ErrorMessage(HttpStatusCode.BadRequest, ex);
}
}
public static Comment UpdateComment(Comment comment, Guid id)
{
try
{
using(SqlConnection connection = new SqlConnection(DBFunctions.ConnectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = String.Format(@"
UPDATE [comment].[Comment]
SET
[textComment] = @TextComment
WHERE
[id] = @Id
");
command.AddParameter("@Id", SqlDbType.UniqueIdentifier, id);
command.AddParameter("@TextComment", SqlDbType.NVarChar, comment.TextComment);
if(comment.TextComment == null || comment.TextComment == "")
{
return null;
}
connection.Open();
command.ExecuteNonQuery();
return GetComment(id);
}
}
catch(Exception ex)
{
Logger.WriteLog(ex);
throw ErrorResponse.ErrorMessage(HttpStatusCode.BadRequest, ex);
}
}
public static void DeleteComment(Guid id)
{
try
{
using (SqlConnection connection = new SqlConnection(DBFunctions.ConnectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = String.Format(@"
UPDATE
[comment].[Comment]
SET
[Active] = 0
WHERE
[Id] = @Id
");
command.AddParameter("@Id", SqlDbType.UniqueIdentifier, id);
connection.Open();
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Logger.WriteLog(ex);
throw ErrorResponse.ErrorMessage(HttpStatusCode.BadRequest, ex);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class turret_c : MonoBehaviour {
public float step = 10f;
void Update () {
if (Input.GetKeyDown("left"))
{
transform.Rotate(new Vector3(0f, 0f, step));
}
if (Input.GetKeyDown("right"))
{
transform.Rotate(new Vector3(0f, 0f, -step));
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
using Tiny.AspNetCore.Mvc.Extensions;
namespace Tiny.ProductService
{
/// <summary>
///
/// </summary>
public class Startup
{
/// <summary>
///
/// </summary>
/// <param name="configuration"></param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
///
/// </summary>
public IConfiguration Configuration { get; }
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
string serviceName = Configuration["Service:Name"];
// IdentityServer
services.AddAuthentication(Configuration["IdentityService:DefaultScheme"])
//.AddIdentityServerAuthentication(options =>
//{
// options.Authority = Configuration["IdentityService:Uri"];
// options.RequireHttpsMetadata = Convert.ToBoolean(Configuration["IdentityService:UseHttps"]);
// options.ApiName = serviceName;
//})
.AddJwtBearer(Configuration["IdentityService:DefaultScheme"], options =>
{
options.Authority = Configuration["IdentityService:Uri"];
options.RequireHttpsMetadata = Convert.ToBoolean(Configuration["IdentityService:UseHttps"]);
options.Audience = serviceName;
options.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(1);//验证token超时时间频率
options.TokenValidationParameters.RequireExpirationTime = true;
});
services.AddMvc(option =>
{
// 添加路由前缀
option.UseCentralRoutePrefix(new RouteAttribute($"api/{serviceName}"));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// Swagger
services.AddSwaggerGen(s =>
{
s.SwaggerDoc(Configuration["Service:DocName"], new Info
{
Title = Configuration["Service:Title"],
Version = Configuration["Service:Version"],
Description = Configuration["Service:Description"],
//作者信息
Contact = new Contact
{
Name = Configuration["Service:Contact:Name"],
Email = Configuration["Service:Contact:Email"],
Url = Configuration["Service:Contact:Url"]
},
//服务条款
//TermsOfService = Configuration["Service:TermsOfService"],
//许可证
License = new License
{
Name = Configuration["Service:License:Name"],
Url = Configuration["Service:License:Url"]
}
});
s.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description =
"JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
s.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{"Bearer", Enumerable.Empty<string>()}
});
string basePath = PlatformServices.Default.Application.ApplicationBasePath;
string xmlPath = Path.Combine(basePath, Configuration["Service:XmlFile"]);
s.IncludeXmlComments(xmlPath);
});
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="applicationLifetime"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime)
{
string serviceName = Configuration["Service:Name"];
string serviceId = serviceName + Guid.NewGuid();
string ip = Configuration["Service:IP"];
int port = Convert.ToInt32(Configuration["Service:Port"]);
Action<ConsulClientConfiguration> ConsulConfig = (config) =>
{
config.Address = new Uri($"http://{Configuration["Consul:IP"]}:{Configuration["Consul:Port"]}"); //服务注册的地址,集群中任意一个地址
config.Datacenter = "dc1";
};
using (ConsulClient consulClient = new ConsulClient())
{
AgentServiceRegistration asr = new AgentServiceRegistration
{
ID = serviceId,
Name = serviceName,
Address = ip,
Port = port,
//设置轮询,定期健康检查
Check = new AgentServiceCheck
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
HTTP = $"http://{ip}:{port}/api/{serviceName}/Health",//健康检查访问的地址
Interval = TimeSpan.FromSeconds(10), //健康检查的间隔时间
Timeout = TimeSpan.FromSeconds(5), //多久代表超时
}
};
consulClient.Agent.ServiceRegister(asr).Wait();
}
//注销Consul
applicationLifetime.ApplicationStopped.Register(() =>
{
using (ConsulClient consulClient = new ConsulClient(ConsulConfig))
{
consulClient.Agent.ServiceDeregister(serviceId).Wait(); //从consul集群中移除服务
}
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//// authentication
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc();
// swagger
app.UseSwagger(c =>
{
c.RouteTemplate = "doc/{documentName}/swagger.json";
});
app.UseSwaggerUI(s =>
{
s.InjectJavascript("/swagger/zh_CN.js"); // 加载中文包
//s.RoutePrefix = "apis/{*assetPath}"; //设置路由前缀
s.SwaggerEndpoint($"/doc/{Configuration["Service:DocName"]}/swagger.json",
$"{serviceName} {Configuration["Service:Version"]}");
});
}
}
}
|
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using Npgsql;
using NpgsqlTypes;
using CGCN.Framework;
using CGCN.DataAccess;
namespace QTHT.DataAccess
{
/// <summary>
/// Mô tả thông tin cho bảng nhom
/// Cung cấp các hàm xử lý, thao tác với bảng nhom
/// Người tạo (C): tuanva
/// Ngày khởi tạo: 17/10/2014
/// </summary>
public class nhom
{
#region Private Variables
private string stridnhom;
private string strtennhom;
private string strmota;
#endregion
#region Public Constructor Functions
public nhom()
{
stridnhom = string.Empty;
strtennhom = string.Empty;
strmota = string.Empty;
}
public nhom(string stridnhom, string strtennhom, string strmota)
{
this.stridnhom = stridnhom;
this.strtennhom = strtennhom;
this.strmota = strmota;
}
#endregion
#region Properties
public string idnhom
{
get
{
return stridnhom;
}
set
{
stridnhom = value;
}
}
public string tennhom
{
get
{
return strtennhom;
}
set
{
strtennhom = value;
}
}
public string mota
{
get
{
return strmota;
}
set
{
strmota = value;
}
}
#endregion
#region Public Method
private readonly DataAccessLayerBaseClass mDataAccess = new DataAccessLayerBaseClass(Data.ConnectionString);
/// <summary>
/// Lấy toàn bộ dữ liệu từ bảng nhom
/// </summary>
/// <returns>DataTable</returns>
public DataTable GetAll()
{
string strFun = "fn_nhom_getall";
try
{
DataSet dsnhom = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure);
return dsnhom.Tables[0];
}
catch
{
return null;
}
}
/// <summary>
/// Hàm lấy nhom theo mã
/// </summary>
/// <returns>Trả về objnhom </returns>
public nhom GetByID(string stridnhom)
{
nhom objnhom = new nhom();
string strFun = "fn_nhom_getobjbyid";
try
{
NpgsqlParameter[] prmArr = new NpgsqlParameter[1];
prmArr[0] = new NpgsqlParameter("idnhom", NpgsqlDbType.Varchar);
prmArr[0].Value = stridnhom;
DataSet dsnhom = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr);
if ((dsnhom != null) && (dsnhom.Tables.Count > 0))
{
if (dsnhom.Tables[0].Rows.Count > 0)
{
DataRow dr = dsnhom.Tables[0].Rows[0];
objnhom.idnhom = dr["idnhom"].ToString();
objnhom.tennhom = dr["tennhom"].ToString();
objnhom.mota = dr["mota"].ToString();
return objnhom;
}
return null;
}
return null;
}
catch
{
return null;
}
}
/// <summary>
/// Hàm kiểm tra trùng tên nhóm
/// </summary>
/// <param name="strtennhom">Tên nhóm kiểu string</param>
/// <param name="stridnhom">Mã nhóm kiểu string</param>
/// <param name="itrangthai">Trạng thái: 1-Thêm mới;2-Sửa</param>
/// <returns>bool: True-Trùng;False-Không trùng</returns>
public bool CheckExit(string strtennhom, string stridnhom, int itrangthai)
{
nhom objnhom = new nhom();
string strFun = "fn_nhom_checkexit";
try
{
NpgsqlParameter[] prmArr = new NpgsqlParameter[3];
prmArr[0] = new NpgsqlParameter("itennhom", NpgsqlDbType.Varchar);
prmArr[0].Value = strtennhom;
prmArr[1] = new NpgsqlParameter("iidnhom", NpgsqlDbType.Varchar);
prmArr[1].Value = stridnhom;
prmArr[2] = new NpgsqlParameter("itrangthai", NpgsqlDbType.Integer);
prmArr[2].Value = itrangthai;
DataSet dsnhom = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr);
if ((dsnhom != null) && (dsnhom.Tables.Count > 0))
{
if (dsnhom.Tables[0].Rows.Count > 0)
{
return true;
}
return false;
}
return false;
}
catch
{
return true;
}
}
/// <summary>
/// Thêm mới dữ liệu vào bảng: nhom
/// </summary>
/// <param name="obj">objnhom</param>
/// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns>
public string Insert(nhom objnhom)
{
string strProc = "fn_nhom_insert";
try
{
NpgsqlParameter[] prmArr = new NpgsqlParameter[4];
prmArr[0] = new NpgsqlParameter("idnhom", NpgsqlDbType.Varchar);
prmArr[0].Value = objnhom.stridnhom;
prmArr[1] = new NpgsqlParameter("tennhom", NpgsqlDbType.Varchar);
prmArr[1].Value = objnhom.strtennhom;
prmArr[2] = new NpgsqlParameter("mota", NpgsqlDbType.Varchar);
prmArr[2].Value = objnhom.strmota;
prmArr[3] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text);
prmArr[3].Direction = ParameterDirection.Output;
mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr);
string sKQ = prmArr[3].Value.ToString().Trim();
if (sKQ.ToUpper().Equals("Add".ToUpper()) == true) return "";
return "Thêm mới dữ liệu không thành công"; }
catch(Exception ex)
{
return "Thêm mới dữ liệu không thành công. Chi Tiết: " + ex.Message;
}
}
/// <summary>
/// Cập nhật dữ liệu vào bảng: nhom
/// </summary>
/// <param name="obj">objnhom</param>
/// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns>
public string Update(nhom objnhom)
{
string strProc = "fn_nhom_Update";
try
{
NpgsqlParameter[] prmArr = new NpgsqlParameter[4];
prmArr[0] = new NpgsqlParameter("idnhom", NpgsqlDbType.Varchar);
prmArr[0].Value = objnhom.stridnhom;
prmArr[1] = new NpgsqlParameter("tennhom", NpgsqlDbType.Varchar);
prmArr[1].Value = objnhom.strtennhom;
prmArr[2] = new NpgsqlParameter("mota", NpgsqlDbType.Varchar);
prmArr[2].Value = objnhom.strmota;
prmArr[3] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text);
prmArr[3].Direction = ParameterDirection.Output;
mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr);
string sKQ = prmArr[3 ].Value.ToString().Trim();
if (sKQ.ToUpper().Equals("Update".ToUpper()) == true) return "";
return "Cập nhật dữ liệu không thành công";
}
catch(Exception ex)
{
return "Cập nhật dữ liệu không thành công. Chi Tiết: " + ex.Message;
}
}
/// <summary>
/// Xóa dữ liệu từ bảng nhom
/// </summary>
/// <returns>Trả về trắng: xóa thành công; Trả về khác trắng: xóa không thành công</returns>
public string Delete(string stridnhom)
{
string strProc = "fn_nhom_delete";
try
{
NpgsqlParameter[] prmArr = new NpgsqlParameter[2];
prmArr[0] = new NpgsqlParameter("idnhom", NpgsqlDbType.Varchar);
prmArr[0].Value = stridnhom;
prmArr[1] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text);
prmArr[1].Direction = ParameterDirection.Output;
mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr);
string KQ = prmArr[1].Value.ToString().Trim();
if (KQ.ToUpper().Equals("Del".ToUpper()) == true) return "";
return "Xóa dữ liệu không thành công";
}
catch(Exception ex)
{
return "Xóa dữ liệu không thành công. Chi Tiết: " + ex.Message;
}
}
/// <summary>
/// Hàm kiểm tra trùng tên nhóm người dùng
/// </summary>
/// <param name="sid">Mã nhóm người dùng</param>
/// <param name="sten">Tên nhóm người dùng</param>
/// <returns>bool: False-Không tồn tại;True-Có tồn tại</returns>
public bool CheckExit(string sidnhom, string stennhom)
{
string strProc = "fn_nhom_checkexit";
try
{
NpgsqlParameter[] prmArr = new NpgsqlParameter[3];
prmArr[0] = new NpgsqlParameter("iidnhom", NpgsqlDbType.Varchar);
prmArr[0].Value = sidnhom;
prmArr[1] = new NpgsqlParameter("itennhom", NpgsqlDbType.Varchar);
prmArr[1].Value = stennhom;
prmArr[2] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text);
prmArr[2].Direction = ParameterDirection.Output;
mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr);
string sKQ = prmArr[2].Value.ToString().Trim();
if (sKQ.ToUpper().Equals("0".ToUpper()) == true) return false;
else if (sKQ.ToUpper().Equals("1".ToUpper()) == true) return true;
}
catch
{
return false;
}
return true;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using EWF.Application.Web.Controllers;
using EWF.Entity;
using EWF.IServices;
using EWF.Util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace EWF.Application.Web.Areas.SysManage.Controllers
{
[Authorize]
public class UnitController : EWFBaseController
{
private ISYS_UNITService service;
private ISYS_DEPARTMENTService dservice;
public UnitController(ISYS_UNITService _unitService,ISYS_DEPARTMENTService _dservice)
{
service = _unitService;
dservice = _dservice;
}
public IActionResult Index()
{
return View();
}
/// <summary>
/// 获取单位列表信息
/// </summary>
/// <param name="page"></param>
/// <param name="rows"></param>
/// <param name="username"></param>
/// <returns></returns>
public IActionResult GetUnitData(int page, int rows,string UCode, string UnitName)
{
var pageObj = service.GetUnitData(page, rows,UCode,UnitName);
var data = new
{
total = pageObj.TotalItems,
rows = pageObj.Items
};
return Content(data.ToJson());
}
/// <summary>
///获取机构单位信息
/// </summary>
/// <param name="UCode"></param>
/// <param name="UnitName"></param>
/// <returns></returns>
public IActionResult GetUnitList(string UCode, string UnitName)
{
DataTable dt = service.getUnitList(UCode,UnitName);
var result = "{\"rows\":" + dt.ToJson() + ",\"total\":" + dt.Rows.Count + "}";
return Content(result);
}
public string AddUnitInfo()
{
SYS_UNIT unit = new SYS_UNIT()
{
UNITID = Guid.NewGuid().ToString(),
PARENTID = Guid.Empty.ToString(),
CATEGORY = "",
UCODE = Request.Form["UCODE"],
FULLNAME = Request.Form["FULLNAME"],
SHORTNAME = Request.Form["SHORTNAME"],
MANAGER = Request.Form["MANAGER"],
CONTACT = Request.Form["CONTACT"],
PHONE = Request.Form["PHONE"],
FAX = Request.Form["FAX"],
EMAIL = Request.Form["EMAIL"],
PROVINCEID = "",
CITYID = "",
COUNTYID = "",
ADDRESS = Request.Form["ADDRESS"],
POSTALCODE = Request.Form["POSTALCODE"],
WEB = "",
REMARK = Request.Form["REMARK"],
ISENABLED = Request.Form["ISENABLED"].ToInt(),
SORTCODE = Request.Form["SORTCODE"].ToInt(),
DELETEMARK = 0,
CREATEDATE = DateTime.Now,
CREATEUSERID = "",
CREATEUSERNAME = "",
MODIFYDATE = DateTime.Now,
MODIFYUSERID = "",
MODIFYUSERNAME =""
};
string result = service.Insert(unit);
return result;
}
public string AddZUnitInfo()
{
var Id = Request.Form["UNITID"];
SYS_UNIT unit = new SYS_UNIT()
{
UNITID = Guid.NewGuid().ToString(),
PARENTID = Id.ToString(),
CATEGORY = "",
UCODE = Request.Form["UCODE"],
FULLNAME = Request.Form["FULLNAME"],
SHORTNAME = Request.Form["SHORTNAME"],
MANAGER = Request.Form["MANAGER"],
CONTACT = Request.Form["CONTACT"],
PHONE = Request.Form["PHONE"],
FAX = Request.Form["FAX"],
EMAIL = Request.Form["EMAIL"],
PROVINCEID = "",
CITYID = "",
COUNTYID = "",
ADDRESS = Request.Form["ADDRESS"],
POSTALCODE = Request.Form["POSTALCODE"],
WEB = "",
REMARK = Request.Form["REMARK"],
ISENABLED = Request.Form["ISENABLED"].ToInt(),
SORTCODE = Request.Form["SORTCODE"].ToInt(),
DELETEMARK = 0,
CREATEDATE = DateTime.Now,
CREATEUSERID = "",
CREATEUSERNAME = "",
MODIFYDATE = DateTime.Now,
MODIFYUSERID = "",
MODIFYUSERNAME = ""
};
string result = service.Insert(unit);
return result;
}
public string AddDepartmentInfo()
{
var Id = Request.Form["DUNITID"];
SYS_DEPARTMENT Depart = new SYS_DEPARTMENT()
{
UNITID = Id.ToString(),
DEPARTMENTID =Guid.NewGuid().ToString(),
PARENTID = "",
DCODE = Request.Form["DDCODE"],
FULLNAME = Request.Form["DFULLNAME"],
SHORTNAME = Request.Form["DSHORTNAME"],
MANAGER = Request.Form["DMANAGER"],
PHONE = Request.Form["DPHONE"],
FAX = Request.Form["DFAX"],
EMAIL = Request.Form["DEMAIL"],
NATURE = "",
REMARK = Request.Form["DREMARK"],
ISENABLED = Request.Form["DISENABLED"].ToInt(),
SORTCODE = Request.Form["DSORTCODE"].ToInt(),
DELETEMARK = 0,
CREATEDATE = DateTime.Now,
CREATEUSERID = "",
CREATEUSERNAME = "",
MODIFYDATE = DateTime.Now,
MODIFYUSERID = "",
MODIFYUSERNAME = ""
};
string result = dservice.Insert(Depart);
return result;
}
public string EditUnitInfo()
{
var Id = Request.Form["UNITID"];
SYS_UNIT Unit = service.GetUnitByID(Id);
Unit.UCODE = Request.Form["UCODE"];
Unit.FULLNAME = Request.Form["FULLNAME"];
Unit.SHORTNAME = Request.Form["SHORTNAME"];
Unit.MANAGER = Request.Form["MANAGER"];
Unit.CONTACT = Request.Form["CONTACT"];
Unit.PHONE = Request.Form["PHONE"];
Unit.FAX = Request.Form["FAX"];
Unit.EMAIL = Request.Form["EMAIL"];;
Unit.ADDRESS = Request.Form["ADDRESS"];
Unit.POSTALCODE = Request.Form["POSTALCODE"];
Unit.REMARK = Request.Form["REMARK"];
Unit.ISENABLED = Request.Form["ISENABLED"].ToInt();
Unit.SORTCODE = Request.Form["SORTCODE"].ToInt();
Unit.MODIFYDATE = DateTime.Now;
string result = service.Update(Unit);
return result;
}
public string DeleteUnitInfo(string Id)
{
string result = service.Delete(Id);
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LaReglaDeTres
{
public partial class Ingreso : Form
{
public Ingreso()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtContrasenia.Text == "samircito21")
{
Form1 principal = new Form1();
this.Hide();
principal.Show();
}
else
{
MessageBox.Show("Contraseña incorrecta", "Contraseña", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
namespace waimai.BingdingClass
{
public class SpecificNRest
{
public List<string> itemName { set; get; }//eg 热销榜
public List<string> itemDescription { set; get; }//eg 大家喜欢吃,才叫真好吃
// public List<nFood> allfoods { set; get; }//
}
public class nFood
{
public string foodName { set; get; }
public string foodActivity { set; get; }
public string foodAttributes1 { set; get; }
public string foodAttributes2 { set; get; }
public string rateStar { set; get; }
public string Evaluate { set; get; }
public string monthSale { set; get; }
public string foodPrice { set; get; }
public BitmapImage foodImage { set; get; }
public string foodLimitation { set; get; }
public string foodDescription { set; get; }
}
public class topItem
{
public string itemName { set; get; }
public int count { set; get; }
public Grid itemGrid { set; get; }
}
public class topDescription
{
public string itemDescription { set; get; }
}
}
|
using UnityEngine;
using System.Collections;
public class SpawnTile : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void Upgrade()
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.EventSystems;
public class CharacterMover2 : MonoBehaviour
{
// Use this for initialization
NavMeshAgent agent;
NavMeshHit there;
public GameObject selectedTarget;
public bool gotTarget = false;
//var thing = new Interactable();
void Start ()
{
agent = GetComponent<NavMeshAgent> ();
}
// Update is called once per frame
void Update ()
{
//Only search if clicked
if (Input.GetMouseButtonDown (0)) {
//Shoot ray from mouse position
if(!EventSystem.current.IsPointerOverGameObject())
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit[] hits = Physics.RaycastAll (ray);
foreach (RaycastHit hit in hits) { //Loop through all the hits
if (hit.transform.gameObject.layer == 8) { //Make a new layer for targets
print ("targetted: " + hit.transform + " at " + hit.transform.position);
NavMesh.SamplePosition(hit.transform.gameObject.transform.position, out there, 15, NavMesh.AllAreas);
Vector3 boxpos = hit.transform.position;
Vector3 characterpos = agent.transform.position;
Vector3 spot = boxpos + (characterpos - boxpos) * 3f / (characterpos - boxpos).sqrMagnitude;
NavMesh.SamplePosition(spot, out there, 5, NavMesh.AllAreas);
agent.destination = there.position;
//You hit a target!
//DeselectTarget(); //Deselect the old target
selectedTarget = hit.transform.gameObject;
//Debug.Log(hit.transform.gameObject.GetComponentInParent<Interactable>());
//SelectTarget(); //Select the new target
gotTarget = true; //Set that we hit something
break; //Break out because we don't need to check anymore
}
else
{
selectedTarget = null;
gotTarget = false;
}
{
}
}
if (!gotTarget) {
RaycastHit hit;
if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit, 100)) {
print("normal ray hit");
agent.destination = hit.point;
}
}//DeselectTarget(); //If we missed everything, deselect
}
}
if(gotTarget)
{
if(Vector3.Distance(this.gameObject.transform.position, selectedTarget.transform.position) < 4)
{
agent.ResetPath();
selectedTarget.GetComponent<IInteractable>().Interact();
selectedTarget = null;
gotTarget = false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Labrat
{
class televisio
{
public bool Päällä { get; set; }
public int Kanava { get; set; }
public int Volume { get; set; }
public televisio()
{
}
public televisio(bool päällä)
{
this.Päällä = päällä;
}
public televisio(int kanava,int volume)
{
this.Kanava = kanava;
this.Volume = volume;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pudge;
using Pudge.Player;
using System.Timers;
namespace PudgeClient
{
public class GraphUpdater
{
private Graph graph;
public GraphUpdater(Graph graph)
{
this.graph = graph;
var timer = new Timer(PudgeRules.Current.RuneRespawnTime * 1000);
timer.AutoReset = true;
timer.Start();
timer.Elapsed += ((sender, args) => UpdateRunes());
}
public void UpdateRunes()
{
foreach (var rune in graph.runes)
rune.visited = false;
}
public void Update(PudgeSensorsData data)
{
var Location = new Location(data.SelfLocation);
/*foreach (var rune in data.Map.Runes)
{
var curRune = new Rune(rune.Location.X, rune.Location.Y);
if (!graph.edges.ContainsKey(curRune))
{
graph.edges.Add(curRune, curRune.Edges);
graph.runes.Add(curRune);
graph.AddEdges(curRune, true);
}
}*/
var runesAround = graph.runes
.Where(x => x.GetDistance(Location) <= PudgeRules.Current.VisibilityRadius - 1);
var seeRunes = data.Map.Runes.Select(x => new Rune(x.Location.X, x.Location.Y));
var runesVisited = runesAround
.Where(x => !seeRunes.Contains(x));
foreach (var rune in runesVisited)
rune.visited = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace transGraph
{
public partial class ConstantD : Form
{
dbFacade db = new dbFacade();
string id;
string t;
public ConstantD(string id, string t)
{
this.id = id;
this.t = t;
InitializeComponent();
DataTable data = db.FetchAllSql("SELECT km0,note0 FROM constD WHERE id = '" + this.id + "' AND reg = '" + this.t + "'");
try
{
this.textBox1.Text = data.Rows[0][0].ToString();
this.textBox2.Text = data.Rows[0][1].ToString();
}
catch (Exception) { }
// Вид ТС
DataTable dataС = db.FetchAllSql("SELECT id,title FROM cartypes");
foreach (DataRow rr in dataС.Rows)
{
comboBox1.Items.Add(rr[1]);
}
data = db.FetchAllSql("SELECT `type` FROM riders WHERE id = '" + this.id + "'");
try
{
string cartypesid = Convert.ToString(data.Rows[0][0]);
string cartypesidT = "";
try
{
DataTable dataB = db.FetchAllSql("SELECT title FROM cartypes WHERE id = '" + cartypesid + "'");
cartypesidT = dataB.Rows[0][0].ToString();
}
catch (Exception) { }
this.comboBox1.SelectedItem = cartypesidT;
}
catch (Exception) { }
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
string type = "";
try
{
DataTable data = db.FetchAllSql("SELECT id FROM `cartypes` WHERE title = '" + comboBox1.SelectedItem + "'");
type = Convert.ToString(data.Rows[0][0]);
db.FetchAllSql("UPDATE `riders` SET `type` = '" + type + "' WHERE id = '" + this.id + "'");
}
catch (Exception) { }
// Логи
try
{
DataTable dt = db.FetchAllSql("SELECT name FROM riders WHERE id = '" + id + "'");
db.FetchAllSql("INSERT INTO `logs` (`text`) VALUES ('Изменение константы [Водителя] значения [км: " + this.textBox1.Text + " , точка: " + this.textBox2.Text + " ] у [" + dt.Rows[0][0].ToString() + "]')");
}
catch (Exception) { }
// Логи
try
{
db.FetchAllSql("REPLACE INTO `constD` (`id`,`reg`,`km0`,`note0`) VALUES ('" + id + "','" + t + "','" + this.textBox1.Text + "','" + this.textBox2.Text + "')");
this.Close();
}
catch (Exception)
{
MessageBox.Show("Ошибка при записи БД! Неверные значения!");
}
}
}
}
|
using MarsQA_1.Helpers;
using MarsQA_1.Pages;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
namespace MarsQA_1.Feature
{
[Binding]
class LoginSD
{
private SignIn LoginObj;
//Created constructor for dependency injection
public LoginSD(IWebDriver driver)
{
LoginObj = new SignIn(driver);
}
[Given(@"I navigate to the application portal")]
public void GivenINavigateToTheApplicationPortal()
{
LoginObj.NavigateUrl();
}
[When(@"I login using valid credentials")]
public void WhenILoginUsingValidCredentials()
{
LoginObj.SigninStep();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using restauranter.Models;
using System.Linq;
namespace restauranter.Controllers
{
public class HomeController : Controller
{
private RestContext _context;
public HomeController(RestContext context)
{
_context = context;
}
// GET: /Home/
[HttpGet]
[Route("")]
public IActionResult Index()
{
return View();
}
[HttpGet]
[Route("result")]
public IActionResult Result()
{
List<Reviews> ReturnedValues = _context.Review.ToList();
ViewBag.reviews = ReturnedValues;
return View();
}
[HttpPost]
[Route("create")]
public IActionResult Create(Reviews review)
{
if(ModelState.IsValid)
{
_context.Add(review);
_context.SaveChanges();
return RedirectToAction("Result");
}
else
{
return View("Index");
}
}
}
}
|
using FluentValidation;
namespace Indexer
{
public class IndexingArgsValidator : AbstractValidator<ProgramArgs>
{
public IndexingArgsValidator()
{
RuleFor(c => c.ParsedDirectories).SetCollectionValidator(new DirectoryValidator()).WithName("Directory");
RuleFor(c => c.ExcludeWildcards).SetCollectionValidator(new ExclusionValidator()).WithName("Exclusion wildcard");
}
}
} |
/*--------------------------------------------------------------------------
Reactor.Web
The MIT License (MIT)
Copyright (c) 2015 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
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.Collections.Generic;
namespace Reactor.Web.Templates
{
/// <summary>
/// Document lexer
/// </summary>
internal static class Lexer
{
#region Utility
private static int Max (Token token)
{
return token.BodyStart + token.BodyLength;
}
private static int Advance (Token token, int index)
{
for (var i = index; i < Max(token); i++)
{
var code = token.Content[i];
if ((code >= 48 && code <= 57) ||
(code >= 65 && code <= 122) ||
code == 123 ||
code == 125 ||
code == 64 ||
code == 40 ||
code == 41 ||
code == 34 ||
code == 39)
{
return i;
}
}
return Max(token);
}
private static int AdvanceTo (Token token, int index, int code)
{
for (var i = index; i < Max(token); i++)
{
var _code = token.Content[i];
if(_code == code) {
return i;
}
}
return Max(token);
}
private static string Read (Token token, int start, int length)
{
if (start >= Max(token))
{
return string.Empty;
}
if ((start + length) > Max(token))
{
var overflow = (start + length) - Max(token);
length = length - overflow;
}
return token.Content.Substring(start, length);
}
#endregion
#region Scanners
private static int ScanSection (Token token, int index)
{
var name = "";
var start = index;
var length = 0;
var bodystart = 0;
var bodylength = 0;
var cursor = (index + 8);
// ensure there is a space between
// @section and its name. otherwise return.
if(token.Content[cursor] != 32)
{
return index;
}
// ensure that the next character is not a
// opening brace, as @sections require names.
// if this is the case, return.
cursor = Advance(token, cursor);
if (token.Content[cursor] == '{')
{
return index;
}
// scan ahead to obtain the section name.
// once found, update the cursor. terminate
// return the index if we reach the end
// of the scope first.
for (int i = cursor; i < Max(token); i++)
{
var code = token.Content[i];
if (i == (Max(token) - 1))
{
return index;
}
if((code < 48 || code > 57) && (code < 65 || code > 122)) {
name = Read(token, cursor, i - cursor);
cursor = i;
break;
}
}
// if the next char is 'not' a open body token, we
// treat this as a bodyless section declartion.
// we add the section and return with the end
// compoents set to the cursor.
var peek = Advance(token, cursor);
if (token.Content[peek] != '{')
{
var section = new SectionToken(token.Content, name, start, (cursor - index), 0, 0);
section = Lexer.Scan(section);
token.Tokens.Add(section);
return cursor;
}
// scan ahead looking for the body content. keep
// a count of the opening and closing braces, and
// only completing when the braces return to 0.
var count = 0;
for (var i = cursor; i < Max(token); i++)
{
var ch = token.Content[i];
if(ch == '{') {
if(count == 0) {
bodystart = i + 1;
}
count += 1;
}
if(ch == '}') {
count -= 1;
if(count == 0) {
bodylength = (i - bodystart);
length = (i - index) + 1;
break;
}
}
}
var _section = new SectionToken(token.Content, name, start, length, bodystart, bodylength);
_section = Lexer.Scan(_section);
token.Tokens.Add(_section);
return index + _section.Length;
}
private static int ScanImport (Token token, int index)
{
var filename = "";
var start = index;
var length = 0;
var cursor = (index + 7);
cursor = Advance(token, cursor);
var quote_flag = 0;
// ensure that the next character after
// @import is either a single or double
// qoute. if detected, then set the quote
// flag to be that value, otherwise return.
var code = token.Content[cursor];
if(code == 39 || code == 34) {
quote_flag = code;
}
else {
return (index);
}
// advance one and scan through the @import
// filename and gather the content. if we recieve
// a newline or other invalid character along the
// way, then terminate and return the index starting
// location.
cursor += 1;
for (var i = cursor; i < Max(token); i++)
{
code = token.Content[i];
if(code == 10 || code == 13) {
return index;
}
if(code == quote_flag) {
filename = Read(token, cursor, i - cursor);
length = (i - index) + 1;
break;
}
}
var import = new ImportToken(token.Content, filename, start, length);
token.Tokens.Add(import);
return index + import.Length;
}
private static int ScanRender (Token token, int index)
{
var filename = "";
var start = index;
var length = 0;
var cursor = (index + 7);
cursor = Advance(token, cursor);
var quote_flag = 0;
// ensure that the next character after
// @render is either a single or double
// qoute. if detected, then set the quote
// flag to be that value, otherwise return.
var code = token.Content[cursor];
if(code == 39 || code == 34) {
quote_flag = code;
}
else {
return (index);
}
// advance one and scan through the @render
// filename and gather the content. if we recieve
// a newline or other invalid character along the
// way, then terminate and return the index starting
// location.
cursor += 1;
for (var i = cursor; i < Max(token); i++)
{
code = token.Content[i];
if(code == 10 || code == 13) {
return index;
}
if(code == quote_flag) {
filename = Read(token, cursor, i - cursor);
length = (i - index) + 1;
break;
}
}
var render = new RenderToken(token.Content, filename, start, length);
token.Tokens.Add(render);
return index + render.Length;
}
private static int ScanComment (Token token, int index)
{
var comment = "";
var start = index;
var length = 0;
var cursor = index + 2;
// scan through the content reading the body
// of the comment. we are checking for the
// pattern *@, indicating the end of the
// comment.
for (var i = cursor; i < Max(token); i++)
{
var code = token.Content[i];
if (code == 42) // *
{
if (token.Content[i + 1] == 64) // @
{
i = i + 1;
comment = Read(token, index, (i - cursor) + 2);
length = (i - index) + 1;
break;
}
}
}
var declaration = new CommentToken(token.Content, start, length);
token.Tokens.Add(declaration);
return index + declaration.Length;
}
private static int ScanContent (Token token, int index)
{
// here we scan to the next @. however, we
// skip +1 from the index to prevent getting
// stuck on subsequent calls. in the string "123@123"
// this will match "123" on first pass and "@123" on
// the subsequent pass.
var cursor = AdvanceTo(token, index + 1, 64);
var declaration = new ContentToken(token.Content, index, cursor - index);
if (declaration.Length > 0)
{
token.Tokens.Add(declaration);
}
return (index + declaration.Length);
}
public static T Scan<T>(T token) where T : Token
{
var index = token.BodyStart;
do
{
//---------------------------------------------
// scan section
//---------------------------------------------
if (Read(token, index, 8) == "@section")
{
var next = ScanSection(token, index);
if(next > index)
{
index = next;
continue;
}
}
//---------------------------------------------
// scan import
//---------------------------------------------
if (Read(token, index, 7) == "@import")
{
var next = ScanImport(token, index);
if(next > index)
{
index = next;
continue;
}
}
//---------------------------------------------
// scan render
//---------------------------------------------
if (Read(token, index, 7) == "@render")
{
var next = ScanRender(token, index);
if(next > index)
{
index = next;
continue;
}
}
//---------------------------------------------
// scan comment
//---------------------------------------------
if (Read(token, index, 2) == "@*")
{
var next = ScanComment(token, index);
if(next > index)
{
index = next;
continue;
}
}
//---------------------------------------------
// scan content
//---------------------------------------------
index = ScanContent(token, index);
} while (index < Max(token));
return token;
}
#endregion
}
}
|
using System;
namespace RO.Config
{
public static class PropID
{
public const int Hp = 1;
public const int Mp = 2;
public const int PhyAtk = 3;
public const int MagAtk = 4;
public const int PhyDef = 5;
public const int MagDef = 6;
public const int MoveSpeed = 7;
public const int AtkRange = 33;
public const int AtkRangeFactor = 34;
public const int AtkCD = 34;
public const int AtkCDFactor = 35;
public const int BeginSearchRadius = 36;
public const int BeginSearchDis = 37;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ENTITY;
using OpenMiracle.DAL;
using System.Data;
using System.Windows.Forms;
namespace OpenMiracle.BLL
{
public class PaymentVoucherBll
{
PaymentDetailsInfo InfoPaymentDetails = new PaymentDetailsInfo();
PaymentDetailsSP SPPaymentDetails = new PaymentDetailsSP();
PaymentMasterInfo InfoPaymentMaster = new PaymentMasterInfo();
PaymentMasterSP SPPaymentMaster = new PaymentMasterSP();
/// <summary>
///
/// </summary>
/// <param name="paymentdetailsinfo"></param>
/// <returns></returns>
public decimal PaymentDetailsAdd(PaymentDetailsInfo paymentdetailsinfo)
{
decimal decCompanyId = 0;
try
{
decCompanyId = SPPaymentDetails.PaymentDetailsAdd(paymentdetailsinfo);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:1" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decCompanyId;
}
/// <summary>
///
/// </summary>
/// <param name="PaymentDetailsId"></param>
public void PaymentDetailsDelete(decimal PaymentDetailsId)
{
try
{
SPPaymentDetails.PaymentDetailsDelete(PaymentDetailsId);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:2" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
///
/// </summary>
/// <param name="paymentdetailsinfo"></param>
/// <returns></returns>
public decimal PaymentDetailsEdit(PaymentDetailsInfo paymentdetailsinfo)
{
decimal decCompanyId = 0;
try
{
decCompanyId = SPPaymentDetails.PaymentDetailsEdit(paymentdetailsinfo);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:3" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decCompanyId;
}
/// <summary>
///
/// </summary>
/// <param name="paymentMastertId"></param>
/// <returns></returns>
public List<DataTable> PaymentDetailsViewByMasterId(decimal paymentMastertId)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SPPaymentDetails.PaymentDetailsViewByMasterId(paymentMastertId);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:4" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
/// <summary>
///
/// </summary>
/// <param name="decVoucherTypeId"></param>
/// <returns></returns>
public int PaymentMasterMax(decimal decVoucherTypeId)
{
int inCount = 0;
try
{
inCount = SPPaymentMaster.PaymentMasterMax(decVoucherTypeId);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:5" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return inCount;
}
/// <summary>
///
/// </summary>
/// <param name="decPaymentMasterId"></param>
/// <param name="decCompanyId"></param>
/// <returns></returns>
public DataSet PaymentVoucherPrinting(decimal decPaymentMasterId, decimal decCompanyId)
{
DataSet ds = new DataSet();
try
{
ds = SPPaymentMaster.PaymentVoucherPrinting(decPaymentMasterId, decCompanyId);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:6" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return ds;
}
/// <summary>
///
/// </summary>
/// <param name="strvoucherNo"></param>
/// <param name="decvoucherTypeId"></param>
/// <param name="decMasterId"></param>
/// <returns></returns>
public bool PaymentVoucherCheckExistence(string strvoucherNo, decimal decvoucherTypeId, decimal decMasterId)
{
bool isResult = false;
try
{
isResult = SPPaymentMaster.PaymentVoucherCheckExistence(strvoucherNo, decvoucherTypeId, decMasterId);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:7" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return isResult;
}
/// <summary>
///
/// </summary>
/// <param name="paymentmasterinfo"></param>
/// <returns></returns>
public decimal PaymentMasterAdd(PaymentMasterInfo paymentmasterinfo)
{
decimal decCompanyId = 0;
try
{
decCompanyId = SPPaymentMaster.PaymentMasterAdd(paymentmasterinfo);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:8" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decCompanyId;
}
/// <summary>
///
/// </summary>
/// <param name="paymentmasterinfo"></param>
/// <returns></returns>
public decimal PaymentMasterEdit(PaymentMasterInfo paymentmasterinfo)
{
decimal decCompanyId = 0;
try
{
decCompanyId = SPPaymentMaster.PaymentMasterEdit(paymentmasterinfo);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:9" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decCompanyId;
}
/// <summary>
///
/// </summary>
/// <param name="decPaymentMasterId"></param>
/// <param name="decVoucherTypeId"></param>
/// <param name="strVoucherNo"></param>
public void PaymentVoucherDelete(decimal decPaymentMasterId, decimal decVoucherTypeId, string strVoucherNo)
{
try
{
SPPaymentMaster.PaymentVoucherDelete(decPaymentMasterId, decVoucherTypeId, strVoucherNo);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:10" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
///
/// </summary>
/// <param name="paymentMastertId"></param>
/// <returns></returns>
public PaymentMasterInfo PaymentMasterViewByMasterId(decimal paymentMastertId)
{
try
{
InfoPaymentMaster = SPPaymentMaster.PaymentMasterViewByMasterId(paymentMastertId);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:11" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return InfoPaymentMaster;
}
/// <summary>
///
/// </summary>
/// <param name="dtpFromDate"></param>
/// <param name="dtpToDate"></param>
/// <param name="decledgerId"></param>
/// <param name="strvoucherNo"></param>
/// <returns></returns>
public List<DataTable> PaymentMasterSearch(DateTime dtpFromDate, DateTime dtpToDate, decimal decledgerId, string strvoucherNo)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SPPaymentMaster.PaymentMasterSearch(dtpFromDate, dtpToDate, decledgerId, strvoucherNo);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:12" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
/// <summary>
///
/// </summary>
/// <param name="dtpFromDate"></param>
/// <param name="dtpToDate"></param>
/// <param name="decLedgerId"></param>
/// <param name="decVoucherTypeId"></param>
/// <param name="decCashOrBankId"></param>
/// <param name="decCompanyId"></param>
/// <returns></returns>
public DataSet PaymentReportPrinting(DateTime dtpFromDate, DateTime dtpToDate, decimal decLedgerId, decimal decVoucherTypeId, decimal decCashOrBankId, decimal decCompanyId)
{
DataSet ds = new DataSet();
try
{
ds = SPPaymentMaster.PaymentReportPrinting(dtpFromDate, dtpToDate, decLedgerId, decVoucherTypeId, decCashOrBankId, decCompanyId);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:13" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return ds;
}
/// <summary>
///
/// </summary>
/// <param name="dtpFromDate"></param>
/// <param name="dtpToDate"></param>
/// <param name="decLedgerId"></param>
/// <param name="decVoucherTypeId"></param>
/// <param name="decCashOrBankId"></param>
/// <returns></returns>
public List<DataTable> PaymentReportSearch(DateTime dtpFromDate, DateTime dtpToDate, decimal decLedgerId, decimal decVoucherTypeId, decimal decCashOrBankId)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SPPaymentMaster.PaymentReportSearch(dtpFromDate, dtpToDate, decLedgerId, decVoucherTypeId, decCashOrBankId);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:14" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
/// <summary>
///
/// </summary>
/// <param name="decVouchertypeid"></param>
/// <param name="strVoucherNo"></param>
/// <returns></returns>
public decimal paymentMasterIdView(decimal decVouchertypeid, string strVoucherNo)
{
decimal decCompanyId = 0;
try
{
decCompanyId = SPPaymentMaster.paymentMasterIdView(decVouchertypeid, strVoucherNo);
}
catch (Exception ex)
{
MessageBox.Show("PVBLL:15" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decCompanyId;
}
}
}
|
// GIMP# - A C# wrapper around the GIMP Library
// Copyright (C) 2004-2010 Maurits Rijk
//
// Pixel.cs
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
using System;
using System.Runtime.InteropServices;
using GLib;
namespace Gimp
{
public class Pixel
{
static Random _random = new Random();
PixelRgn _rgn;
readonly int _bpp;
readonly int _bppWithoutAlpha;
readonly int[] _rgb;
public Pixel(int bpp)
{
_bpp = bpp;
_bppWithoutAlpha = (HasAlpha) ? _bpp - 1 : _bpp;
_rgb = new int[_bpp];
}
public Pixel(byte[] rgb) : this(rgb.Length)
{
Bytes = rgb;
}
public Pixel(int r, int g, int b) : this(3)
{
_rgb[0] = r;
_rgb[1] = g;
_rgb[2] = b;
}
public Pixel(int r, int g, int b, int a) : this(4)
{
_rgb[0] = r;
_rgb[1] = g;
_rgb[2] = b;
_rgb[3] = a;
}
internal Pixel(Pixel p) : this(p._bpp)
{
Array.Copy(p._rgb, _rgb, Bpp);
}
internal Pixel(PixelRgn rgn, byte[] rgb) : this(rgb)
{
_rgn = rgn;
}
public int Bpp
{
get {return _bpp;}
}
public void Fill(Func<int> func)
{
for (int i = 0; i < _bppWithoutAlpha; i++)
{
_rgb[i] = func();
}
}
public void Fill(Func<int, int> func)
{
for (int i = 0; i < _bppWithoutAlpha; i++)
{
_rgb[i] = func(_rgb[i]);
}
}
public void FillSame(Func<int> func)
{
int val = func();
for (int i = 0; i < _bppWithoutAlpha; i++)
{
_rgb[i] = val;
}
}
public void Set(Pixel pixel)
{
_rgn[Y, X] = pixel;
}
public bool IsSameColor(Pixel pixel)
{
for (int i = 0; i < pixel._bpp; i++)
{
if (_rgb[i] != pixel._rgb[i])
{
return false;
}
}
return true;
}
public RGB Color
{
get
{
return new RGB((byte) Red, (byte) Green, (byte) Blue);
}
set
{
byte r, g, b;
value.GetUchar(out r, out g, out b);
_rgb[0] = r;
_rgb[1] = g;
_rgb[2] = b;
}
}
public byte[] Bytes
{
set
{
Array.Copy(value, _rgb, _bpp);
}
get
{
return Array.ConvertAll(_rgb,
new Converter<int, byte>(ConvertToByte));
}
}
static byte ConvertToByte(int value)
{
return (byte) value;
}
public void CopyTo(byte[] dest, long index)
{
for (int i = 0; i < _bpp; i++)
{
dest[index + i] = (byte) _rgb[i];
}
}
public void CopyFrom(byte[] src, long index)
{
Array.Copy(src, index, _rgb, 0, _bpp);
}
public int X {get; set;}
public int Y {get; set;}
public int this[int index]
{
get {return _rgb[index];}
set {_rgb[index] = value;}
}
public int Red
{
get {return _rgb[0];}
set {_rgb[0] = value;}
}
public int Green
{
get {return _rgb[1];}
set {_rgb[1] = value;}
}
public int Blue
{
get {return _rgb[2];}
set {_rgb[2] = value;}
}
public int Alpha
{
get {return _rgb[(_bpp == 2) ? 1 : 3];}
set {_rgb[(_bpp == 2) ? 1 : 3] = value;}
}
public bool HasAlpha
{
get {return _bpp == 2 || _bpp == 4;}
}
public void Clamp0255()
{
for (int i = 0; i < _bpp; i++)
{
_rgb[i] = Clamp(_rgb[i]);
}
}
int Clamp(int rgb)
{
return (rgb < 0) ? 0 : ((rgb > 255) ? 255 : rgb);
}
public void AddNoise(int noise)
{
for (int i = 0; i < _bppWithoutAlpha; i++)
{
_rgb[i] = Clamp(_rgb[i] + _random.Next(-noise, noise));
}
}
public Pixel Add(Pixel p)
{
for (int i = 0; i < _bpp; i++)
{
_rgb[i] += p._rgb[i];
}
return this;
}
public Pixel Add(int v)
{
for (int i = 0; i < _bpp; i++)
{
_rgb[i] += v;
}
return this;
}
public Pixel Substract(Pixel p)
{
for (int i = 0; i < _bpp; i++)
{
_rgb[i] -= p._rgb[i];
}
return this;
}
public Pixel Divide(int v)
{
for (int i = 0; i < _bpp; i++)
{
_rgb[i] /= v;
}
return this;
}
public static Pixel operator / (Pixel p, int v)
{
return (new Pixel(p)).Divide(v);
}
public static Pixel operator + (Pixel p1, Pixel p2)
{
return (new Pixel(p1)).Add(p2);
}
public static Pixel operator - (Pixel p1, Pixel p2)
{
return (new Pixel(p1)).Substract(p2);
}
public static Pixel operator + (Pixel p, int v)
{
return (new Pixel(p)).Add(v);
}
public override string ToString()
{
return string.Format("({0} {1} {2})", _rgb[0], _rgb[1], _rgb[2]);
}
static internal Pixel[,] ConvertToPixelArray(IntPtr src,
Dimensions dimensions,
int bpp)
{
int width = dimensions.Width;
int height = dimensions.Height;
var dest = new byte[width * height * bpp];
Marshal.Copy(src, dest, 0, width * height * bpp);
var thumbnail = new Pixel[height, width];
int index = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
var pixel = new Pixel(bpp);
pixel.CopyFrom(dest, index);
index += bpp;
thumbnail[y, x] = pixel;
}
}
return thumbnail;
}
}
}
|
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Threading;
using BukkitServiceAPI;
using BukkitServiceAPI.Authentication;
using ConnorsNetworkingSuite;
using System.Linq;
namespace BukkitService.Interactions {
internal static class NewClientHandler {
private static X509Certificate cert;
private static X509Certificate Certificate {
get {
return cert ?? (cert = new X509Certificate2(
Main.config["certificate-path"],
Main.config["certificate-pass"],
X509KeyStorageFlags.MachineKeySet));
}
}
internal static readonly Config Userconf = new Config(
Path.Combine(
Util.StorageDir, "basicuserstore.conf"));
internal static void HandleClient(NetStream stream, IPEndPoint ip) {
try {
var ssl = new SslStream(stream);
ssl.AuthenticateAsServer(Certificate);
stream = ssl;
} catch (Exception e) {
stream.Write("ERR_SSL\r\n");
stream.Write(e.ToString());
return;
}
stream.Encoding = Encoding.ASCII;
var encdodingstring = stream.Read();
int codepage;
if (int.TryParse(encdodingstring, out codepage)) {
try {
var cpenc = Encoding.GetEncoding(codepage);
stream.Encoding = cpenc;
stream.Write("success");
} catch {
stream.Write("ERR_ENCODING_NOT_FOUND");
stream.Close();
return;
}
} else {
try {
var encoding = Encoding.GetEncoding(encdodingstring);
stream.Encoding = encoding;
stream.Write("success");
} catch {
stream.Write("ERR_ENCODING_NOT_FOUND");
stream.Close();
return;
}
}
try {
var cred = Authenticate(stream);
if (!cred.Successful) {
stream.Close();
return;
}
stream.Write("LOGIN_SUCCESS");
ClientLoop.BeginClient(new Client(stream, cred.Username, cred.SecurityLevel, ip));
} catch (Exception ex) {
stream.Write("ERR\r\n");
stream.Write(ex.ToString());
}
}
internal static void HandleClientPlaintext(NetStream stream, IPEndPoint ip) {
stream.Encoding = Encoding.ASCII;
var encdodingstring = stream.Read();
int codepage;
if (int.TryParse(encdodingstring, out codepage)) {
try {
var cpenc = Encoding.GetEncoding(codepage);
stream.Encoding = cpenc;
stream.Write("success");
} catch {
stream.Write("ERR_ENCODING_NOT_FOUND");
stream.Close();
return;
}
} else {
try {
var encoding = Encoding.GetEncoding(encdodingstring);
stream.Encoding = encoding;
stream.Write("success");
} catch {
stream.Write("ERR_ENCODING_NOT_FOUND");
stream.Close();
return;
}
}
try {
var cred = Authenticate(stream);
if (!cred.Successful) {
stream.Close();
return;
}
stream.Write("LOGIN_SUCCESS");
ClientLoop.BeginClient(new Client(stream, cred.Username, cred.SecurityLevel, ip));
} catch (Exception ex) {
stream.Write("ERR\r\n");
stream.Write(ex.ToString());
}
}
private static NewClientCredentials Authenticate(NetStream stream) {
var ncc = CustomAuthentication.CustomAuth(stream);
return ncc ?? ConfigAuth(stream);
}
private static NewClientCredentials ConfigAuth(NetStream stream) {
var ncc = new NewClientCredentials { Successful = false, SecurityLevel = -1, Username = null };
var userpass = stream.Read();
var ups = userpass.Split(new[] { ':' }, 2);
if (ups.Length < 2) {
stream.Write("ERR_AUTH_INVALID_USER_FORMAT");
stream.Close();
return ncc;
}
if (Userconf["user." + ups[0] + ".enabled"] != "true") {
stream.Write("ERR_AUTH_INVALID_CREDENTIALS");
return ncc;
}
var validhash = Userconf["user." + ups[0] + ".hash"];
var thishash = Hash(ups[1]);
if (validhash != thishash) {
stream.Write("ERR_AUTH_INVALID_CREDENTIALS");
return ncc;
}
var seclvlstr = Userconf["user." + ups[0] + ".sec"];
int sec;
if (!int.TryParse(seclvlstr, out sec)) {
stream.Write("ERR_ACCOUNT_NOT_AUTHORIZED");
return ncc;
}
ncc.Username = ups[0];
ncc.SecurityLevel = sec;
ncc.Successful = true;
Thread.CurrentThread.Name = ncc.Username;
return ncc;
}
internal static bool CheckUserPass(string user, string pass) {
var thishash = Hash(pass);
var validhash = Userconf["user." + user + ".hash"];
return thishash.Equals(validhash, StringComparison.InvariantCultureIgnoreCase);
}
public static string Hash(string input) {
var sha = new System.Security.Cryptography.SHA512CryptoServiceProvider();
var bytes = Encoding.Unicode.GetBytes(input);
bytes = bytes.Where(b => b != 0).ToArray();
bytes = sha.ComputeHash(bytes);
Array.Reverse(bytes);
bytes = sha.ComputeHash(bytes);
Array.Reverse(bytes);
bytes = sha.ComputeHash(bytes);
Array.Reverse(bytes);
bytes = sha.ComputeHash(bytes);
Array.Reverse(bytes);
bytes = sha.ComputeHash(bytes);
return Convert.ToBase64String(bytes, Base64FormattingOptions.None);
}
}
} |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
namespace WebApi
{
public class Program
{
public static Task Main(string[] args)
{
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder.UseStartup<Startup>();
})
.Build();
return host.RunAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Ip2LocationApp
{
public class Utils
{
public static IP2Location.Component IP2Location = new IP2Location.Component
{
IPLicensePath = @"C:\Users\Administrator\Desktop\Ip2locAp\IpToLocationApp\Ip2LocationApp\wwwroot\license.key",
IPDatabasePath = @"C:\Users\Administrator\Desktop\Ip2locAp\IpToLocationApp\Ip2LocationApp\wwwroot\IP2LOCATION-LITE-DB11.BIN"
};
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sun : MonoBehaviour
{
public GameObject explosion;
Rigidbody2D rb;
Vector3 initialScale;
Vector3 newScale;
private float initialColliderRadius;
PointEffector2D pe;
// Start is called before the first frame update
void Start()
{
pe = GetComponent<PointEffector2D>();
initialScale = transform.localScale;
newScale = initialScale;
}
// Update is called once per frame
void Update()
{
transform.localScale = Vector3.Lerp(transform.localScale, newScale, 1f * Time.deltaTime);
}
private void OnCollisionEnter2D(Collision2D other)
{
GameObject currentExplosion = Instantiate(explosion, other.gameObject.transform.position, Quaternion.identity);
SoundController.playSunSound();
if(!other.gameObject.CompareTag("Earth"))
{
Destroy(other.gameObject);
} else
{
currentExplosion.GetComponent<PointEffector2D>().enabled = false;
}
if(other.gameObject.CompareTag("EarthPiece"))
{
currentExplosion.GetComponent<PointEffector2D>().enabled = false;
newScale *= 1.01f;
pe.forceMagnitude *= 1.01f;
} else
{
newScale *= 1.1f;
pe.forceMagnitude *= 1.3f;
}
Destroy(currentExplosion, currentExplosion.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).length);
}
}
|
using Entities.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BertoniProyectoRUWeb
{
public partial class AlbumWeb : System.Web.UI.Page
{
private string currentAlbumIDSelected;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
GetAlbums();
}
}
private void GetAlbums()
{
WebRequest request = WebRequest.Create("https://jsonplaceholder.typicode.com/albums");
request.Method = "GET";
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseFromReaderStr = reader.ReadToEnd();
reader.Close();
responseStream.Close();
List<Album> albums = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Album>>(responseFromReaderStr);
if(albums.Any())
{
ddlAlbums.DataSource = albums;
ddlAlbums.DataValueField = "id";
ddlAlbums.DataTextField = "title";
ddlAlbums.DataBind();
ddlAlbums.SelectedIndex = 0;
}
}
protected void btnSeeAlbumDetail_Click(object sender, EventArgs e)
{
Response.Redirect("~/PhotoWeb.aspx?ai=" + ddlAlbums.SelectedValue);
}
}
} |
using CallCenter.Common.Entities;
using NHibernate;
namespace CallCenter.Client.SqlStorage.Controllers
{
public class CampaignController : EntityControllerBase<ICampaign>
{
public CampaignController(ISessionFactory sessionFactory) : base(sessionFactory)
{
}
protected override string ColumnNameToSearch
{
get
{
return "Name";
}
}
}
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.CodeAnalysis.Sarif
{
public interface IAnalysisContext : IDisposable
{
Uri TargetUri { get; set; }
string MimeType { get; set; }
HashData Hashes { get; set; }
Exception TargetLoadException { get; set; }
bool IsValidAnalysisTarget { get; }
ReportingDescriptor Rule { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
PropertiesDictionary Policy { get; set; }
IAnalysisLogger Logger { get; set; }
RuntimeConditions RuntimeErrors { get; set; }
bool AnalysisComplete { get; set; }
DefaultTraces Traces { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditorInternal;
using UnityEngine;
public class WithinFortyDist : Task
{
public WithinFortyDist(Blackboard bb) : base(bb){}
public override bool execute()
{
GameObject aObj = this.bb.GetGameObject("Agent");
GameObject mObj = this.bb.GetGameObject("Marked");
// If no marked target, fail
if (aObj == null)
{
return false;
}
Boid agent = aObj.GetComponent<Boid>();
if (mObj == null) {
return false;
}
Boid marked = mObj.GetComponent<Boid>();
Vector3 diff = marked.transform.position - agent.transform.position;
return diff.magnitude < 40;
}
}
|
using System;
namespace WeatherWeb.Models
{
public class AppSettings
{
public string EventHubConnectionString { get; set; }
}
} |
using System;
using System.IO;
namespace file_handling
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Let's see file handling:");
FileStream fs = new FileStream("C:\\Users\\vaishnavi.vinjam\\source\\repos\\file_handling\\file.txt",FileMode.OpenOrCreate);
StreamReader sr = new StreamReader(fs);
Console.WriteLine("let's read and display from file");
string str = sr.ReadLine();
while(str!=null)
{
Console.WriteLine(str);
str = sr.ReadLine();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.