context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Text;
using System.Collections.ObjectModel;
using System.Management.Automation;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// A command that adds the parent and child parts of a path together
/// with the appropriate path separator.
/// </summary>
[Cmdlet("Join", "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113347")]
[OutputType(typeof(string))]
public class JoinPathCommand : CoreCommandWithCredentialsBase
{
#region Parameters
/// <summary>
/// Gets or sets the path parameter to the command
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[Alias("PSPath")]
public string[] Path { get; set; }
/// <summary>
/// Gets or sets the childPath parameter to the command
/// </summary>
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)]
[AllowNull]
[AllowEmptyString]
public string ChildPath { get; set; }
/// <summary>
/// Gets or sets additional childPaths to the command.
/// </summary>
[Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromRemainingArguments = true)]
[AllowNull]
[AllowEmptyString]
[AllowEmptyCollection]
public string[] AdditionalChildPath { get; set; } = Utils.EmptyArray<string>();
/// <summary>
/// Determines if the path should be resolved after being joined
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter Resolve { get; set; }
#endregion Parameters
#region Command code
/// <summary>
/// Parses the specified path and returns the portion determined by the
/// boolean parameters.
/// </summary>
protected override void ProcessRecord()
{
Dbg.Diagnostics.Assert(
Path != null,
"Since Path is a mandatory parameter, paths should never be null");
string combinedChildPath = ChildPath;
// join the ChildPath elements
if (AdditionalChildPath != null)
{
foreach (string childPath in AdditionalChildPath)
{
combinedChildPath = SessionState.Path.Combine(combinedChildPath, childPath, CmdletProviderContext);
}
}
foreach (string path in Path)
{
// First join the path elements
string joinedPath = null;
try
{
joinedPath =
SessionState.Path.Combine(path, combinedChildPath, CmdletProviderContext);
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
if (Resolve)
{
// Resolve the paths. The default API (GetResolvedPSPathFromPSPath)
// does not allow non-existing paths.
Collection<PathInfo> resolvedPaths = null;
try
{
resolvedPaths =
SessionState.Path.GetResolvedPSPathFromPSPath(joinedPath, CmdletProviderContext);
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
for (int index = 0; index < resolvedPaths.Count; ++index)
{
try
{
if (resolvedPaths[index] != null)
{
WriteObject(resolvedPaths[index].Path);
}
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
} // for each path
}
else
{
if (joinedPath != null)
{
WriteObject(joinedPath);
}
}
}
} // ProcessRecord
#endregion Command code
} // JoinPathCommand
} // namespace Microsoft.PowerShell.Commands
| |
//-----------------------------------------------------------------------------
//
// <copyright file="PrivateUnsafeNativeMethods.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// This is partial class declaration of the InternalSafeNativeMethods
// specifically the private sub class PrivateUnsafeNativeMethods with the PInvoke declarations
//
// History:
// 06/13/2005: IgorBel: Initial implementation.
//
//-----------------------------------------------------------------------------
#define PRESENTATION_HOST_DLL
// We use this #ifdef to control the usage of the intermediate unmanaged
// DLL that is used to satisfy requirement of the DRM DK SP1 Lock box.
// SP1 Lock box requires that certain functions (DRMGetBoundLicenseObject,
// DRMInitEnvironment, ...) be called from the signed unmanaged DLL. We use
// PresentationHostDll for that purpose. In future we expect that such
// requirement might go away and we wouldn't need it. It is also a convenient
// debugging tool to use MSDRM.dll directly with the DRM SDK shipped msdrm-lcp.dll
// (This one intended to serve as a proxy to the real msdrm.dll in order to enable
// debugging of the client applications)
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Security;
using MS.Win32;
namespace MS.Internal.Security.RightsManagement
{
/// <SecurityNote>
/// Critical: This class server as a wrapper on top of private class PrivateUnsafeNativeMethods.
/// PrivateUnsafeNativeMethods has suppress unamanged code attribute set.
/// It is up to this class to ensure that the only calls that can go through must beeither done in Full Trust
/// or with RightsManagementPermission. This class exposes DRMFoo functions that perform demand on the
/// RightsManagementPermission and then call through to the matching member of the Private Static class PrivateUnsafeNativeMethods
/// </SecurityNote>
/// The partial class only needs to be marked security critical in one of the parts [SecurityCritical]
/// Adding [SecurityCritical] note here adds to a compiler error "Duplicate 'SecurityCritical' attribute"
internal static partial class SafeNativeMethods
{
/// <SecurityNote>
/// Critical: Suppressing unmanaged code. Note all code that calls this must be critical
/// The only code that can access this class is in the SafeNativeMethods (as the class
/// is declared as private within SafeNativeMethods)
/// SafeNativeMethods is responsible for performing appropriate Asserts prior to calling
/// PrivateUnsafeNativeMethods which in turn is marked with SuppressUnmanagedCodeSecurity
/// </SecurityNote>
[SecurityCritical(SecurityCriticalScope.Everything)]
[SuppressUnmanagedCodeSecurity] // Blessed
private static class UnsafeNativeMethods
{
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMCreateClientSession(
[In, MarshalAs(UnmanagedType.FunctionPtr)]CallbackDelegate pfnCallback,
[In, MarshalAs(UnmanagedType.U4)] uint uCallbackVersion,
[In, MarshalAs(UnmanagedType.LPWStr)] string GroupIDProviderType,
[In, MarshalAs(UnmanagedType.LPWStr)] string GroupID,
[Out] out SafeRightsManagementSessionHandle phSession);
// we can not use safe handle in the DrmClose... function
// as the SafeHandle implementation marks this instance as an invalid by the time
// ReleaseHandle is called. After that marshalling code doesn't let the current instance
// of the Safe*Handle sub-class to cross managed/unmanaged boundary.
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMCloseSession(
[In, MarshalAs(UnmanagedType.U4)] uint sessionHandle);
// we can not use safe handle in the DrmClose... function
// as the SafeHandle implementation marks this instance as an invalid by the time
// ReleaseHandle is called. After that marshalling code doesn't let the current instance
// of the Safe*Handle sub-class to cross managed/unmanaged boundary.
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#endif
internal static extern int DRMCloseHandle(
[In, MarshalAs(UnmanagedType.U4)] uint handle);
// we can not use safe handle in the DrmClose... function
// as the SafeHandle implementation marks this instance as an invalid by the time
// ReleaseHandle is called. After that marshalling code doesn't let the current instance
// of the Safe*Handle sub-class to cross managed/unmanaged boundary.
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMCloseQueryHandle(
[In, MarshalAs(UnmanagedType.U4)] uint queryHandle);
// we can not use safe handle in the DrmClose... function
// as the SafeHandle implementation marks this instance as an invalid by the time
// ReleaseHandle is called. After that marshalling code doesn't let the current instance
// of the Safe*Handle sub-class to cross managed/unmanaged boundary.
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMCloseEnvironmentHandle(
[In, MarshalAs(UnmanagedType.U4)] uint envHandle);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMInitEnvironment(
[In, MarshalAs(UnmanagedType.U4)] uint eSecurityProviderType,
[In, MarshalAs(UnmanagedType.U4)] uint eSpecification,
[In, MarshalAs(UnmanagedType.LPWStr)] string securityProvider,
[In, MarshalAs(UnmanagedType.LPWStr)] string manifestCredentials,
[In, MarshalAs(UnmanagedType.LPWStr)] string machineCredentials,
[Out] out SafeRightsManagementEnvironmentHandle environmentHandle,
[Out] out SafeRightsManagementHandle defaultLibrary);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMIsActivated(
[In] SafeRightsManagementSessionHandle hSession,
[In, MarshalAs(UnmanagedType.U4)] uint uFlags,
[In, MarshalAs(UnmanagedType.LPStruct)] ActivationServerInfo activationServerInfo);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMActivate(
[In] SafeRightsManagementSessionHandle hSession,
[In, MarshalAs(UnmanagedType.U4)] uint uFlags,
[In, MarshalAs(UnmanagedType.U4)]uint uLangID,
[In, MarshalAs(UnmanagedType.LPStruct)] ActivationServerInfo activationServerInfo,
IntPtr context, // this is a void* in the unmanaged SDK so IntPtr is the right (platform dependent declaration)
IntPtr parentWindowHandle); // this a HWND in the unmanaged SDK so IntPtr is the right (platform dependent declaration)
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMCreateLicenseStorageSession(
[In] SafeRightsManagementEnvironmentHandle envHandle,
[In] SafeRightsManagementHandle hDefLib,
[In] SafeRightsManagementSessionHandle hClientSession,
[In, MarshalAs(UnmanagedType.U4)] uint uFlags,
[In, MarshalAs(UnmanagedType.LPWStr)] string IssuanceLicense,
[Out] out SafeRightsManagementSessionHandle phLicenseStorageSession);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMAcquireLicense(
[In] SafeRightsManagementSessionHandle hSession,
[In, MarshalAs(UnmanagedType.U4)] uint uFlags,
[In, MarshalAs(UnmanagedType.LPWStr)] string GroupIdentityCredential,
[In, MarshalAs(UnmanagedType.LPWStr)] string RequestedRights,
[In, MarshalAs(UnmanagedType.LPWStr)] string CustomData,
[In, MarshalAs(UnmanagedType.LPWStr)] string url,
IntPtr context); // this is a void* in the unmanaged SDK so IntPtr is the right (platform dependent declaration)
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMEnumerateLicense(
[In] SafeRightsManagementSessionHandle hSession,
[In, MarshalAs(UnmanagedType.U4)] uint uFlags,
[In, MarshalAs(UnmanagedType.U4)] uint uIndex,
[In, Out, MarshalAs(UnmanagedType.Bool)] ref bool pfSharedFlag,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint puCertDataLen,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder wszCertificateData);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMGetServiceLocation(
[In] SafeRightsManagementSessionHandle clientSessionHandle,
[In, MarshalAs(UnmanagedType.U4)] uint serviceType,
[In, MarshalAs(UnmanagedType.U4)] uint serviceLocation,
[In, MarshalAs(UnmanagedType.LPWStr)] string issuanceLicense,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint serviceUrlLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder serviceUrl);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMDeconstructCertificateChain(
[In, MarshalAs(UnmanagedType.LPWStr)] string chain,
[In, MarshalAs(UnmanagedType.U4)] uint index,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint certificateLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder certificate);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMParseUnboundLicense(
[In, MarshalAs(UnmanagedType.LPWStr)] string certificate,
[Out] out SafeRightsManagementQueryHandle queryRootHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetUnboundLicenseObjectCount(
[In] SafeRightsManagementQueryHandle queryRootHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] string subObjectType,
[Out, MarshalAs(UnmanagedType.U4)] out uint objectCount);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMGetBoundLicenseObject(
[In] SafeRightsManagementHandle queryRootHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] string subObjectType,
[In, MarshalAs(UnmanagedType.U4)] uint index,
[Out] out SafeRightsManagementHandle subQueryHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetUnboundLicenseObject(
[In] SafeRightsManagementQueryHandle queryRootHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] string subObjectType,
[In, MarshalAs(UnmanagedType.U4)] uint index,
[Out] out SafeRightsManagementQueryHandle subQueryHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetUnboundLicenseAttribute(
[In] SafeRightsManagementQueryHandle queryRootHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] string attributeType,
[In, MarshalAs(UnmanagedType.U4)] uint index,
[Out, MarshalAs(UnmanagedType.U4)] out uint encodingType,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint bufferSize,
byte[] buffer);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMGetBoundLicenseAttribute(
[In] SafeRightsManagementHandle queryRootHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] string attributeType,
[In, MarshalAs(UnmanagedType.U4)] uint index,
[Out, MarshalAs(UnmanagedType.U4)] out uint encodingType,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint bufferSize,
byte[] buffer);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMCreateIssuanceLicense(
[In, MarshalAs(UnmanagedType.LPStruct)] SystemTime timeFrom,
[In, MarshalAs(UnmanagedType.LPStruct)] SystemTime timeUntil,
[In, MarshalAs(UnmanagedType.LPWStr)] string referralInfoName,
[In, MarshalAs(UnmanagedType.LPWStr)] string referralInfoUrl,
[In] SafeRightsManagementPubHandle ownerUserHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] string issuanceLicense,
[In] SafeRightsManagementHandle boundLicenseHandle,
[Out] out SafeRightsManagementPubHandle issuanceLicenseHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMCreateUser(
[In, MarshalAs(UnmanagedType.LPWStr)] string userName,
[In, MarshalAs(UnmanagedType.LPWStr)] string userId,
[In, MarshalAs(UnmanagedType.LPWStr)] string userIdType,
[Out] out SafeRightsManagementPubHandle userHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetUsers(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, MarshalAs(UnmanagedType.U4)] uint index,
[Out] out SafeRightsManagementPubHandle userHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetUserRights(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In] SafeRightsManagementPubHandle userHandle,
[In, MarshalAs(UnmanagedType.U4)] uint index,
[Out] out SafeRightsManagementPubHandle rightHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetUserInfo(
[In] SafeRightsManagementPubHandle userHandle,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint userNameLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder userName,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint userIdLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder userId,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint userIdTypeLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder userIdType);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetRightInfo(
[In] SafeRightsManagementPubHandle rightHandle,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint rightNameLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder rightName,
[MarshalAs(UnmanagedType.LPStruct)] SystemTime timeFrom,
[MarshalAs(UnmanagedType.LPStruct)] SystemTime timeUntil);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMCreateRight(
[In, MarshalAs(UnmanagedType.LPWStr)] string rightName,
[In, MarshalAs(UnmanagedType.LPStruct)] SystemTime timeFrom,
[In, MarshalAs(UnmanagedType.LPStruct)] SystemTime timeUntil,
[In, MarshalAs(UnmanagedType.U4)] uint countExtendedInfo,
[In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] string[] extendedInfoNames,
[In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] string[] extendedInfoValues,
[Out] out SafeRightsManagementPubHandle rightHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetIssuanceLicenseTemplate(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint issuanceLicenseTemplateLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder issuanceLicenseTemplate);
// we can not use safe handle in the DrmClose... function
// as the SafeHandle implementation marks this instance as an invalid by the time
// ReleaseHandle is called. After that marshalling code doesn't let the current instance
// of the Safe*Handle sub-class to cross managed/unmanaged boundary.
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMClosePubHandle(
[In, MarshalAs(UnmanagedType.U4)] uint pubHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMAddRightWithUser(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In] SafeRightsManagementPubHandle rightHandle,
[In] SafeRightsManagementPubHandle userHandle);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMSetMetaData(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] string contentId,
[In, MarshalAs(UnmanagedType.LPWStr)] string contentIdType,
[In, MarshalAs(UnmanagedType.LPWStr)] string SkuId,
[In, MarshalAs(UnmanagedType.LPWStr)] string SkuIdType,
[In, MarshalAs(UnmanagedType.LPWStr)] string contentType,
[In, MarshalAs(UnmanagedType.LPWStr)] string contentName);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetIssuanceLicenseInfo(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[MarshalAs(UnmanagedType.LPStruct)] SystemTime timeFrom,
[MarshalAs(UnmanagedType.LPStruct)] SystemTime timeUntil,
[In, MarshalAs(UnmanagedType.U4)] uint flags,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint distributionPointNameLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder DistributionPointName,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint distributionPointUriLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder DistributionPointUri,
[Out] out SafeRightsManagementPubHandle ownerHandle,
[Out, MarshalAs(UnmanagedType.Bool)] out bool officialFlag);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetSecurityProvider(
[In, MarshalAs(UnmanagedType.U4)] uint flags, // currently not used by the DRM SDK
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint typeLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder type,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint pathLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder path);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMDeleteLicense(
[In] SafeRightsManagementSessionHandle hSession,
[In, MarshalAs(UnmanagedType.LPWStr)] string wszLicenseId);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMSetNameAndDescription(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, MarshalAs(UnmanagedType.Bool)] bool flagDelete,
[In, MarshalAs(UnmanagedType.U4)] uint localeId,
[In, MarshalAs(UnmanagedType.LPWStr)] string name,
[In, MarshalAs(UnmanagedType.LPWStr)] string description);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetNameAndDescription(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, MarshalAs(UnmanagedType.U4)] uint uIndex,
[Out, MarshalAs(UnmanagedType.U4)] out uint localeId,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint nameLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder name,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint descriptionLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder description);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMGetSignedIssuanceLicense(
[In] SafeRightsManagementEnvironmentHandle environmentHandle,
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, MarshalAs(UnmanagedType.U4)] uint flags,
[In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] symmetricKey,
[In, MarshalAs(UnmanagedType.U4)] uint symmetricKeyByteCount,
[In, MarshalAs(UnmanagedType.LPWStr)] string symmetricKeyType,
[In, MarshalAs(UnmanagedType.LPWStr)] string clientLicensorCertificate,
[In, MarshalAs(UnmanagedType.FunctionPtr)]CallbackDelegate pfnCallback,
[In, MarshalAs(UnmanagedType.LPWStr)] string url,
[In, MarshalAs(UnmanagedType.U4)] uint context);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetOwnerLicense(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint ownerLicenseLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder ownerLicense);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMCreateBoundLicense(
[In] SafeRightsManagementEnvironmentHandle environmentHandle,
[In, MarshalAs(UnmanagedType.LPStruct)] BoundLicenseParams boundLicenseParams,
[In, MarshalAs(UnmanagedType.LPWStr)] string licenseChain,
[Out] out SafeRightsManagementHandle boundLicenseHandle,
[Out, MarshalAs(UnmanagedType.U4)] out uint errorLogHandle);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMCreateEnablingBitsDecryptor(
[In] SafeRightsManagementHandle boundLicenseHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] string right,
[In, MarshalAs(UnmanagedType.U4)] uint auxLibrary,
[In, MarshalAs(UnmanagedType.LPWStr)] string auxPlugin,
[Out] out SafeRightsManagementHandle decryptorHandle);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMCreateEnablingBitsEncryptor(
[In] SafeRightsManagementHandle boundLicenseHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] string right,
[In, MarshalAs(UnmanagedType.U4)] uint auxLibrary,
[In, MarshalAs(UnmanagedType.LPWStr)] string auxPlugin,
[Out] out SafeRightsManagementHandle encryptorHandle);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMDecrypt(
[In] SafeRightsManagementHandle cryptoProvHandle,
[In, MarshalAs(UnmanagedType.U4)] uint position,
[In, MarshalAs(UnmanagedType.U4)] uint inputByteCount,
byte[] inputBuffer,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint outputByteCount,
byte[] outputBuffer);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMEncrypt(
[In] SafeRightsManagementHandle cryptoProvHandle,
[In, MarshalAs(UnmanagedType.U4)] uint position,
[In, MarshalAs(UnmanagedType.U4)] uint inputByteCount,
byte[] inputBuffer,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint outputByteCount,
byte[] outputBuffer);
#if PRESENTATION_HOST_DLL
[DllImport(ExternDll.PresentationHostDll, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
#else
[DllImport(ExternDll.MsDrm,SetLastError=false,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
#endif
internal static extern int DRMGetInfo(
[In] SafeRightsManagementHandle handle,
[In, MarshalAs(UnmanagedType.LPWStr)] string attributeType,
[Out, MarshalAs(UnmanagedType.U4)] out uint encodingType,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint outputByteCount,
byte[] outputBuffer);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetApplicationSpecificData(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, MarshalAs(UnmanagedType.U4)] uint index,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint nameLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder name,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint valueLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder value);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMSetApplicationSpecificData(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, MarshalAs(UnmanagedType.Bool)] bool flagDelete,
[In, MarshalAs(UnmanagedType.LPWStr)] string name,
[In, MarshalAs(UnmanagedType.LPWStr)] string value);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetIntervalTime(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint days);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMSetIntervalTime(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, MarshalAs(UnmanagedType.U4)] uint days);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMGetRevocationPoint(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint idLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder id,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint idTypeLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder idType,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint urlLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder url,
[MarshalAs(UnmanagedType.LPStruct)] SystemTime frequency,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint nameLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder name,
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint publicKeyLength,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder publicKey);
[DllImport(ExternDll.MsDrm, SetLastError = false, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int DRMSetRevocationPoint(
[In] SafeRightsManagementPubHandle issuanceLicenseHandle,
[In, MarshalAs(UnmanagedType.Bool)] bool flagDelete,
[In, MarshalAs(UnmanagedType.LPWStr)] string id,
[In, MarshalAs(UnmanagedType.LPWStr)] string idType,
[In, MarshalAs(UnmanagedType.LPWStr)] string url,
[In, MarshalAs(UnmanagedType.LPStruct)] SystemTime frequency,
[In, MarshalAs(UnmanagedType.LPWStr)] string name,
[In, MarshalAs(UnmanagedType.LPWStr)] string publicKey);
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Threading.Atomics
{
/// <summary>
/// An <see cref="long"/> array wrapper with atomic operations
/// </summary>
[DebuggerDisplay("Count = {Count}")]
public class AtomicLongArray : IAtomicRefArray<long>,
ICollection<long>,
#if !NET40
IReadOnlyCollection<long>,
#endif
IStructuralComparable,
IStructuralEquatable
{
private readonly long[] _data;
private readonly MemoryOrder _order;
/// <summary>
/// Creates new instance of <see cref="AtomicLongArray"/>
/// </summary>
/// <param name="source">The array to copy elements from</param>
/// <param name="order">Affects the way store operation occur. Default is <see cref="MemoryOrder.AcqRel"/> semantics</param>
public AtomicLongArray(long[] source, MemoryOrder order = MemoryOrder.SeqCst)
{
if (source == null) throw new ArgumentNullException("source");
order.ThrowIfNotSupported();
_data = new long[source.Length];
_order = order;
source.CopyTo(_data, 0);
}
/// <summary>
/// Creates new instance of <see cref="AtomicLongArray"/>
/// </summary>
/// <param name="length">The length of the underlying array</param>
/// <param name="order">Affects the way store operation occur. Default is <see cref="MemoryOrder.AcqRel"/> semantics</param>
public AtomicLongArray(long length, MemoryOrder order = MemoryOrder.SeqCst)
{
if (length < 0) throw new ArgumentException("Length can't be negative");
order.ThrowIfNotSupported();
_data = new long[length];
_order = order;
}
/// <summary>
/// Sets an element at <paramref name="index"/> with provided <paramref name="order"/>
/// </summary>
/// <param name="index">The index of element at which to store</param>
/// <param name="value">The value to store</param>
/// <param name="order">The <see cref="MemoryOrder"/> to achieve</param>
/// <remarks>Providing <see cref="MemoryOrder.Relaxed"/> writes the value as <see cref="MemoryOrder.Acquire"/></remarks>
public void Store(int index, ref long value, MemoryOrder order)
{
switch (order)
{
case MemoryOrder.Relaxed:
this._data[index] = value;
break;
case MemoryOrder.Consume:
throw new NotSupportedException();
case MemoryOrder.Acquire:
throw new InvalidOperationException("Cannot set (store) value with Acquire semantics");
case MemoryOrder.Release:
case MemoryOrder.AcqRel:
#if ARM_CPU
Platform.MemoryBarrier();
this._data[index] = value;
#else
Volatile.Write(ref this._data[index], value);
#endif
break;
case MemoryOrder.SeqCst:
#if ARM_CPU
Platform.MemoryBarrier();
this._data[index] = value;
Platform.MemoryBarrier();
#else
Interlocked.Exchange(ref this._data[index], value);
#endif
break;
default:
throw new ArgumentOutOfRangeException("order");
}
}
/// <summary>
/// Gets or sets the element at specified <paramref name="index"/>
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public long this[int index]
{
get { return Load(index, _order); }
set { Store(index, ref value, _order); }
}
/// <summary>
/// Sets an element at <paramref name="index"/> with provided <paramref name="order"/>
/// </summary>
/// <param name="index">The index of element at which to store</param>
/// <param name="value">The value to store</param>
/// <param name="order">The <see cref="MemoryOrder"/> to achieve</param>
/// <remarks>Providing <see cref="MemoryOrder.Relaxed"/> writes the value as <see cref="MemoryOrder.Acquire"/></remarks>
public void Store(int index, long value, MemoryOrder order)
{
Store(index, ref value, order);
}
/// <summary>
/// Gets an element at <paramref name="index"/> with provided <paramref name="order"/>
/// </summary>
/// <param name="index">The index of element from which to load</param>
/// <param name="order">The <see cref="MemoryOrder"/> to achieve</param>
/// <returns>The underlying value with provided <paramref name="order"/></returns>
public long Load(int index, MemoryOrder order)
{
if (order == MemoryOrder.Consume)
throw new NotSupportedException();
if (order == MemoryOrder.Release)
throw new InvalidOperationException("Cannot get (load) value with Release semantics");
switch (order)
{
case MemoryOrder.Relaxed:
return this._data[index];
case MemoryOrder.Acquire:
case MemoryOrder.AcqRel:
case MemoryOrder.SeqCst:
#if ARM_CPU
var tmp = this._data[index];
Platform.MemoryBarrier();
return tmp;
#else
return Volatile.Read(ref this._data[index]);
#endif
default:
throw new ArgumentOutOfRangeException("order");
}
}
/// <summary>
/// Gets value whether the object is lock-free
/// </summary>
public bool IsLockFree
{
get { return true; }
}
/// <summary>
/// Atomically compares underlying element at specified <paramref name="index"/> with <paramref name="comparand"/> for equality and, if they are equal, replaces the first value.
/// </summary>
/// <param name="index">The index of element to compare and set</param>
/// <param name="value">The value that replaces the underlying value if the comparison results in equality</param>
/// <param name="comparand">The value that is compared to the underlying value.</param>
/// <returns>The original underlying value</returns>
public long CompareExchange(int index, long value, long comparand)
{
return Interlocked.CompareExchange(ref this._data[index], value, comparand);
}
public int Count
{
get { return _data.Length; }
}
public IEnumerator<long> GetEnumerator()
{
for (int i = 0; i < _data.Length; i++)
{
yield return Load(i, _order);
}
}
Collections.IEnumerator Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Increments an element at specified <paramref name="index"/> index by 1.
/// </summary>
/// <param name="index">The element's index.</param>
/// <returns>The incremented value of an element at specified <paramref name="index"/> index by 1.</returns>
public long IncrementAt(int index)
{
return Interlocked.Increment(ref _data[index]);
}
/// <summary>
/// Decrements an element at specified <paramref name="index"/> index by 1.
/// </summary>
/// <param name="index">The element's index.</param>
/// <returns>The decremented value of an element at specified <paramref name="index"/> index by 1.</returns>
public long DecrementAt(int index)
{
return Interlocked.Decrement(ref _data[index]);
}
void ICollection<long>.Add(long item)
{
throw new NotSupportedException("Collection is of a fixed size");
}
void ICollection<long>.Clear()
{
throw new NotSupportedException("Collection is of a fixed size");
}
public bool Contains(long item)
{
foreach (var i in _data)
{
if (i == item)
{
return true;
}
}
return false;
}
public void CopyTo(long[] array, int arrayIndex)
{
_data.CopyTo(array, arrayIndex);
}
bool ICollection<long>.IsReadOnly
{
get { return false; }
}
bool ICollection<long>.Remove(long item)
{
throw new NotSupportedException("Collection is of a fixed size");
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
return ((IStructuralComparable)_data).CompareTo(other, comparer);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
return ((IStructuralEquatable)_data).Equals(other, comparer);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)_data).GetHashCode(comparer);
}
}
}
| |
/*
* Copyright (C) 2007-2008, Jeff Thompson
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{
/// <summary>
/// An IndexedAnswers holds answers to a query based on the values of index arguments.
/// </summary>
public class IndexedAnswers : YP.IClause
{
private int _arity;
// addAnswer adds the answer here and indexes it later.
private List<object[]> _allAnswers = new List<object[]>();
// The key has the arity of answers with non-null values for each indexed arg. The value
// is a list of the matching answers. The signature is implicit in the pattern on non-null index args.
private Dictionary<HashedList, List<object[]>> _indexedAnswers =
new Dictionary<HashedList, List<object[]>>();
// Keeps track of whether we have started adding entries to _indexedAnswers for the signature.
private Dictionary<int, object> _gotAnswersForSignature = new Dictionary<int, object>();
private const int MAX_INDEX_ARGS = 31;
public IndexedAnswers(int arity)
{
_arity = arity;
}
/// <summary>
/// Append the answer to the list and update the indexes, if any.
/// Elements of answer must be ground, since arguments with unbound variables make this
/// into a dynamic rule which we don't index.
/// </summary>
/// <param name="answer"></param>
public void addAnswer(object[] answer)
{
addOrPrependAnswer(answer, false);
}
/// <summary>
/// Prepend the answer to the list and clear the indexes so that they must be re-computed
/// on the next call to match. (Only addAnswer will maintain the indexes while adding answers.)
/// Elements of answer must be ground, since arguments with unbound variables make this
/// into a dynamic rule which we don't index.
/// </summary>
/// <param name="answer"></param>
public void prependAnswer(object[] answer)
{
addOrPrependAnswer(answer, true);
}
/// <summary>
/// Do the work of addAnswer or prependAnswer.
/// </summary>
/// <param name="answer"></param>
private void addOrPrependAnswer(object[] answer, bool prepend)
{
if (answer.Length != _arity)
return;
// Store a copy of the answer array.
object[] answerCopy = new object[answer.Length];
Variable.CopyStore copyStore = new Variable.CopyStore();
for (int i = 0; i < answer.Length; ++i)
answerCopy[i] = YP.makeCopy(answer[i], copyStore);
if (copyStore.getNUniqueVariables() > 0)
throw new InvalidOperationException
("Elements of answer must be ground, but found " + copyStore.getNUniqueVariables() +
" unbound variables");
if (prepend)
{
_allAnswers.Insert(0, answerCopy);
clearIndexes();
}
else
{
_allAnswers.Add(answerCopy);
// If match has already indexed answers for a signature, we need to add
// this to the existing indexed answers.
foreach (int signature in _gotAnswersForSignature.Keys)
indexAnswerForSignature(answerCopy, signature);
}
}
private void indexAnswerForSignature(object[] answer, int signature)
{
// First find out which of the answer values can be used as an index.
object[] indexValues = new object[answer.Length];
for (int i = 0; i < answer.Length; ++i)
{
// We limit the number of indexed args in a 32-bit signature.
if (i >= MAX_INDEX_ARGS)
indexValues[i] = null;
else
indexValues[i] = getIndexValue(YP.getValue(answer[i]));
}
// We need an entry in indexArgs from indexValues for each 1 bit in signature.
HashedList indexArgs = new HashedList(indexValues.Length);
for (int i = 0; i < indexValues.Length; ++i)
{
if ((signature & (1 << i)) == 0)
indexArgs.Add(null);
else
{
if (indexValues[i] == null)
// The signature wants an index value here, but we don't have one so
// we can't add it as an answer for this signature.
return;
else
indexArgs.Add(indexValues[i]);
}
}
// Add the answer to the answers list for indexArgs, creating the entry if needed.
List<object[]> answers;
if (!_indexedAnswers.TryGetValue(indexArgs, out answers))
{
answers = new List<object[]>();
_indexedAnswers[indexArgs] = answers;
}
answers.Add(answer);
}
public IEnumerable<bool> match(object[] arguments)
{
if (arguments.Length != _arity)
yield break;
// Set up indexArgs, up to arg position MAX_INDEX_ARGS. The signature has a 1 bit for
// each non-null index arg.
HashedList indexArgs = new HashedList(arguments.Length);
bool gotAllIndexArgs = true;
int signature = 0;
for (int i = 0; i < arguments.Length; ++i)
{
object indexValue = null;
if (i < MAX_INDEX_ARGS)
{
// We limit the number of args in a 32-bit signature.
indexValue = getIndexValue(YP.getValue(arguments[i]));
if (indexValue != null)
signature += (1 << i);
}
if (indexValue == null)
gotAllIndexArgs = false;
indexArgs.Add(indexValue);
}
List<object[]> answers;
if (signature == 0)
// No index args, so we have to match from _allAnswers.
answers = _allAnswers;
else
{
if (!_gotAnswersForSignature.ContainsKey(signature))
{
// We need to create the entry in _indexedAnswers.
foreach (object[] answer in _allAnswers)
indexAnswerForSignature(answer, signature);
// Mark that we did this signature.
_gotAnswersForSignature[signature] = null;
}
if (!_indexedAnswers.TryGetValue(indexArgs, out answers))
yield break;
}
if (gotAllIndexArgs)
{
// All the arguments were already bound, so we don't need to do bindings.
yield return false;
yield break;
}
// Find matches in answers.
IEnumerator<bool>[] iterators = new IEnumerator<bool>[arguments.Length];
// Debug: If the caller asserts another answer into this same predicate during yield, the iterator
// over clauses will be corrupted. Should we take the time to copy answers?
foreach (object[] answer in answers)
{
bool gotMatch = true;
int nIterators = 0;
// Try to bind all the arguments.
for (int i = 0; i < arguments.Length; ++i)
{
if (indexArgs[i] != null)
// We already matched this argument by looking up _indexedAnswers.
continue;
IEnumerator<bool> iterator = YP.unify(arguments[i], answer[i]).GetEnumerator();
iterators[nIterators++] = iterator;
// MoveNext() is true if YP.unify succeeds.
if (!iterator.MoveNext())
{
gotMatch = false;
break;
}
}
int z = 0;
try
{
if (gotMatch)
yield return false;
}
finally
{
// Manually finalize all the iterators.
for (z = 0; z < nIterators; ++z)
iterators[z].Dispose();
}
}
}
public IEnumerable<bool> clause(object Head, object Body)
{
Head = YP.getValue(Head);
if (Head is Variable)
throw new PrologException("instantiation_error", "Head is an unbound variable");
object[] arguments = YP.getFunctorArgs(Head);
// We always match Head from _allAnswers, and the Body is Atom.a("true").
#pragma warning disable 0168, 0219
foreach (bool l1 in YP.unify(Body, Atom.a("true")))
{
// The caller can assert another answer into this same predicate during yield, so we have to
// make a copy of the answers.
foreach (object[] answer in _allAnswers.ToArray())
{
foreach (bool l2 in YP.unifyArrays(arguments, answer))
yield return false;
}
}
#pragma warning restore 0168, 0219
}
public IEnumerable<bool> retract(object Head, object Body)
{
Head = YP.getValue(Head);
if (Head is Variable)
throw new PrologException("instantiation_error", "Head is an unbound variable");
object[] arguments = YP.getFunctorArgs(Head);
// We always match Head from _allAnswers, and the Body is Atom.a("true").
#pragma warning disable 0168, 0219
foreach (bool l1 in YP.unify(Body, Atom.a("true")))
{
// The caller can assert another answer into this same predicate during yield, so we have to
// make a copy of the answers.
foreach (object[] answer in _allAnswers.ToArray())
{
foreach (bool l2 in YP.unifyArrays(arguments, answer))
{
_allAnswers.Remove(answer);
clearIndexes();
yield return false;
}
}
}
#pragma warning restore 0168, 0219
}
/// <summary>
/// After retracting or prepending an answer in _allAnswers, the indexes are invalid, so clear them.
/// </summary>
private void clearIndexes()
{
_indexedAnswers.Clear();
_gotAnswersForSignature.Clear();
}
/// <summary>
/// A HashedList extends an ArrayList with methods to get a hash and to check equality
/// based on the elements of the list.
/// </summary>
public class HashedList : ArrayList
{
private bool _gotHashCode = false;
private int _hashCode;
public HashedList()
: base()
{
}
public HashedList(int capacity)
: base(capacity)
{
}
public HashedList(ICollection c)
: base(c)
{
}
// Debug: Should override all the other methods that change this.
public override int Add(object value)
{
_gotHashCode = false;
return base.Add(value);
}
public override int GetHashCode()
{
if (!_gotHashCode)
{
int hashCode = 1;
foreach (object obj in this)
hashCode = 31 * hashCode + (obj == null ? 0 : obj.GetHashCode());
_hashCode = hashCode;
_gotHashCode = true;
}
return _hashCode;
}
public override bool Equals(object obj)
{
if (!(obj is ArrayList))
return false;
ArrayList objList = (ArrayList)obj;
if (objList.Count != Count)
return false;
for (int i = 0; i < Count; ++i)
{
object value = objList[i];
if (value == null)
{
if (this[i] != null)
return false;
}
else
{
if (!value.Equals(this[i]))
return false;
}
}
return true;
}
}
/// <summary>
/// If we keep an index on value, return the value, or null if we don't index it.
/// </summary>
/// <param name="value">the term to examine. Assume you already called YP.getValue(value)</param>
/// <returns></returns>
public static object getIndexValue(object value)
{
if (value is Atom || value is string || value is Int32 || value is DateTime)
return value;
else
return null;
}
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Net;
using System.Collections.Generic;
using System.Text;
namespace MSNPSharp.P2P
{
using MSNPSharp.Core;
public class DestinationAddressUpdatedEventArgs : EventArgs
{
private IPEndPoint[] ipEndPoints;
public IPEndPoint[] IPEndPoints
{
get
{
return ipEndPoints;
}
}
public DestinationAddressUpdatedEventArgs(IPEndPoint[] ipeps)
{
this.ipEndPoints = ipeps;
}
}
public class TCPv1Bridge : P2PBridge
{
public event EventHandler<DestinationAddressUpdatedEventArgs> DestinationAddressUpdated;
private P2PSession startupSession = null;
private P2PDirectProcessor directConnection = null;
public override bool IsOpen
{
get
{
return (directConnection != null &&
directConnection.DCState == DirectConnectionState.Established);
}
}
public override int MaxDataSize
{
get
{
return 1024;
}
}
private Contact remote = null;
private Guid remoteEpId = Guid.Empty;
public Guid RemoteEpId
{
get
{
return remoteEpId;
}
}
public override Contact Remote
{
get
{
if (remote != null)
return remote;
if (startupSession != null)
return startupSession.Remote;
foreach (P2PSession s in sendQueues.Keys)
{
return s.Remote;
}
return null;
}
}
public override bool SuitableFor(P2PSession session)
{
if (base.SuitableFor(session) && session.RemoteContactEndPointID == RemoteEpId)
{
return true;
}
return false;
}
public IPEndPoint RemoteEndPoint
{
get
{
if (directConnection != null)
return directConnection.RemoteEndPoint as IPEndPoint;
return null;
}
}
public IPEndPoint LocalEndPoint
{
get
{
if (directConnection != null)
return directConnection.LocalEndPoint as IPEndPoint;
return null;
}
}
public TCPv1Bridge(
ConnectivitySettings connectivitySettings,
P2PVersion p2pVersion,
Guid replyNonce, Guid remoteNonce, bool isNeedHash,
P2PSession p2pSession,
NSMessageHandler ns,
Contact remote, Guid remoteEpId)
: base(0, ns)
{
this.startupSession = p2pSession;
this.remote = remote;
this.remoteEpId = remoteEpId;
directConnection = new P2PDirectProcessor(connectivitySettings, p2pVersion, replyNonce, remoteNonce, isNeedHash, p2pSession, ns);
directConnection.HandshakeCompleted += new EventHandler<EventArgs>(directConnection_HandshakeCompleted);
directConnection.P2PMessageReceived += new EventHandler<P2PMessageEventArgs>(directConnection_P2PMessageReceived);
directConnection.SendCompleted += new EventHandler<MSNPSharp.Core.ObjectEventArgs>(directConnection_SendCompleted);
directConnection.DirectNegotiationTimedOut += new EventHandler<EventArgs>(directConnection_DirectNegotiationTimedOut);
directConnection.ConnectionClosed += new EventHandler<EventArgs>(directConnection_ConnectionClosed);
directConnection.ConnectingException += new EventHandler<ExceptionEventArgs>(directConnection_ConnectingException);
directConnection.ConnectionException += new EventHandler<ExceptionEventArgs>(directConnection_ConnectionException);
}
protected internal virtual void OnDestinationAddressUpdated(DestinationAddressUpdatedEventArgs e)
{
if (directConnection != null && directConnection.Connected && directConnection.RemoteEndPoint != null)
{
IPEndPoint remoteIpep = (IPEndPoint)directConnection.RemoteEndPoint;
bool trustedPeer = false;
foreach (IPEndPoint ipep in e.IPEndPoints)
{
if (ipep.Address.Equals(remoteIpep.Address) && ipep.Port == remoteIpep.Port)
{
trustedPeer = true;
break;
}
}
if (trustedPeer == false)
{
directConnection.Disconnect();
OnBridgeClosed(EventArgs.Empty);
}
}
if (DestinationAddressUpdated != null)
DestinationAddressUpdated(this, e);
}
private void directConnection_HandshakeCompleted(object sender, EventArgs e)
{
OnBridgeOpened(e);
}
private void directConnection_DirectNegotiationTimedOut(object sender, EventArgs e)
{
OnBridgeClosed(EventArgs.Empty);
}
private void directConnection_ConnectionException(object sender, ExceptionEventArgs e)
{
OnBridgeClosed(EventArgs.Empty);
}
private void directConnection_ConnectingException(object sender, ExceptionEventArgs e)
{
OnBridgeClosed(EventArgs.Empty);
}
private void directConnection_ConnectionClosed(object sender, EventArgs e)
{
OnBridgeClosed(EventArgs.Empty);
}
public void Listen(IPAddress address, int port)
{
directConnection.Listen(address, port);
}
public void Connect()
{
directConnection.Connect();
}
private void directConnection_P2PMessageReceived(object sender, P2PMessageEventArgs e)
{
ProcessP2PMessage(Remote, remoteEpId, e.P2PMessage);
}
protected override void SendOnePacket(P2PSession session, Contact remote, Guid remoteGuid, P2PMessage msg)
{
directConnection.SendMessage(msg, new P2PMessageSessionEventArgs(msg, session));
}
private void directConnection_SendCompleted(object sender, ObjectEventArgs e)
{
OnBridgeSent(e.Object as P2PMessageSessionEventArgs);
}
}
};
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SyntaxTreeExtensions
{
public static ISet<SyntaxKind> GetPrecedingModifiers(
this SyntaxTree syntaxTree,
int position,
SyntaxToken tokenOnLeftOfPosition,
CancellationToken cancellationToken)
=> syntaxTree.GetPrecedingModifiers(position, tokenOnLeftOfPosition, out var _);
public static ISet<SyntaxKind> GetPrecedingModifiers(
this SyntaxTree syntaxTree,
int position,
SyntaxToken tokenOnLeftOfPosition,
out int positionBeforeModifiers)
{
var token = tokenOnLeftOfPosition;
token = token.GetPreviousTokenIfTouchingWord(position);
var result = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer);
while (true)
{
switch (token.Kind())
{
case SyntaxKind.PublicKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.SealedKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.VirtualKeyword:
case SyntaxKind.ExternKeyword:
case SyntaxKind.NewKeyword:
case SyntaxKind.OverrideKeyword:
case SyntaxKind.ReadOnlyKeyword:
case SyntaxKind.VolatileKeyword:
case SyntaxKind.UnsafeKeyword:
case SyntaxKind.AsyncKeyword:
result.Add(token.Kind());
token = token.GetPreviousToken(includeSkipped: true);
continue;
case SyntaxKind.IdentifierToken:
if (token.HasMatchingText(SyntaxKind.AsyncKeyword))
{
result.Add(SyntaxKind.AsyncKeyword);
token = token.GetPreviousToken(includeSkipped: true);
continue;
}
break;
}
break;
}
positionBeforeModifiers = token.FullSpan.End;
return result;
}
public static TypeDeclarationSyntax GetContainingTypeDeclaration(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.GetContainingTypeDeclarations(position, cancellationToken).FirstOrDefault();
}
public static BaseTypeDeclarationSyntax GetContainingTypeOrEnumDeclaration(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.GetContainingTypeOrEnumDeclarations(position, cancellationToken).FirstOrDefault();
}
public static IEnumerable<TypeDeclarationSyntax> GetContainingTypeDeclarations(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
return token.GetAncestors<TypeDeclarationSyntax>().Where(t =>
{
return BaseTypeDeclarationContainsPosition(t, position);
});
}
private static bool BaseTypeDeclarationContainsPosition(BaseTypeDeclarationSyntax declaration, int position)
{
if (position <= declaration.OpenBraceToken.SpanStart)
{
return false;
}
if (declaration.CloseBraceToken.IsMissing)
{
return true;
}
return position <= declaration.CloseBraceToken.SpanStart;
}
public static IEnumerable<BaseTypeDeclarationSyntax> GetContainingTypeOrEnumDeclarations(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
return token.GetAncestors<BaseTypeDeclarationSyntax>().Where(t => BaseTypeDeclarationContainsPosition(t, position));
}
private static readonly Func<SyntaxKind, bool> s_isDotOrArrow = k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken;
private static readonly Func<SyntaxKind, bool> s_isDotOrArrowOrColonColon =
k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken || k == SyntaxKind.ColonColonToken;
public static bool IsRightOfDotOrArrowOrColonColon(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.IsRightOf(position, s_isDotOrArrowOrColonColon, cancellationToken);
}
public static bool IsRightOfDotOrArrow(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.IsRightOf(position, s_isDotOrArrow, cancellationToken);
}
private static bool IsRightOf(
this SyntaxTree syntaxTree, int position, Func<SyntaxKind, bool> predicate, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
if (token.Kind() == SyntaxKind.None)
{
return false;
}
return predicate(token.Kind());
}
public static bool IsRightOfNumericLiteral(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
return token.Kind() == SyntaxKind.NumericLiteralToken;
}
public static bool IsPrimaryFunctionExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
{
return
syntaxTree.IsTypeOfExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) ||
syntaxTree.IsDefaultExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) ||
syntaxTree.IsSizeOfExpressionContext(position, tokenOnLeftOfPosition, cancellationToken);
}
public static bool IsAfterKeyword(this SyntaxTree syntaxTree, int position, SyntaxKind kind, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
return token.Kind() == kind;
}
public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return
syntaxTree.IsEntirelyWithinNonUserCodeComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinConflictMarker(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken) ||
syntaxTree.IsInInactiveRegion(position, cancellationToken);
}
public static bool IsEntirelyWithinNonUserCodeComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var inNonUserSingleLineDocComment =
syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken) && !syntaxTree.IsEntirelyWithinCrefSyntax(position, cancellationToken);
return
syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) ||
inNonUserSingleLineDocComment;
}
public static bool IsEntirelyWithinComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return
syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken);
}
public static bool IsCrefContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true);
token = token.GetPreviousTokenIfTouchingWord(position);
if (token.Parent is XmlCrefAttributeSyntax attribute)
{
return token == attribute.StartQuoteToken;
}
return false;
}
public static bool IsEntirelyWithinCrefSyntax(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
if (syntaxTree.IsCrefContext(position, cancellationToken))
{
return true;
}
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true);
return token.GetAncestor<CrefSyntax>() != null;
}
public static bool IsEntirelyWithinSingleLineDocComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
var trivia = root.FindTrivia(position);
// If we ask right at the end of the file, we'll get back nothing.
// So move back in that case and ask again.
var eofPosition = root.FullWidth();
if (position == eofPosition)
{
var eof = root.EndOfFileToken;
if (eof.HasLeadingTrivia)
{
trivia = eof.LeadingTrivia.Last();
}
}
if (trivia.IsSingleLineDocComment())
{
var span = trivia.Span;
var fullSpan = trivia.FullSpan;
var endsWithNewLine = trivia.GetStructure().GetLastToken(includeSkipped: true).Kind() == SyntaxKind.XmlTextLiteralNewLineToken;
if (endsWithNewLine)
{
if (position > fullSpan.Start && position < fullSpan.End)
{
return true;
}
}
else
{
if (position > fullSpan.Start && position <= fullSpan.End)
{
return true;
}
}
}
return false;
}
public static bool IsEntirelyWithinMultiLineDocComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position);
if (trivia.IsMultiLineDocComment())
{
var span = trivia.FullSpan;
if (position > span.Start && position < span.End)
{
return true;
}
}
return false;
}
public static bool IsEntirelyWithinMultiLineComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken);
if (trivia.IsMultiLineComment())
{
var span = trivia.FullSpan;
return trivia.IsCompleteMultiLineComment()
? position > span.Start && position < span.End
: position > span.Start && position <= span.End;
}
return false;
}
public static bool IsEntirelyWithinConflictMarker(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken);
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
// Check if we're on the newline right at the end of a comment
trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken);
}
return trivia.Kind() == SyntaxKind.ConflictMarkerTrivia;
}
public static bool IsEntirelyWithinTopLevelSingleLineComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken);
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
// Check if we're on the newline right at the end of a comment
trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken);
}
if (trivia.IsSingleLineComment() || trivia.IsShebangDirective())
{
var span = trivia.FullSpan;
if (position > span.Start && position <= span.End)
{
return true;
}
}
return false;
}
public static bool IsEntirelyWithinPreProcessorSingleLineComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
// Search inside trivia for directives to ensure that we recognize
// single-line comments at the end of preprocessor directives.
var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken, findInsideTrivia: true);
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
// Check if we're on the newline right at the end of a comment
trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken, findInsideTrivia: true);
}
if (trivia.IsSingleLineComment())
{
var span = trivia.FullSpan;
if (position > span.Start && position <= span.End)
{
return true;
}
}
return false;
}
private static bool AtEndOfIncompleteStringOrCharLiteral(SyntaxToken token, int position, char lastChar)
{
if (!token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken))
{
throw new ArgumentException(CSharpWorkspaceResources.Expected_string_or_char_literal, nameof(token));
}
int startLength = 1;
if (token.IsVerbatimStringLiteral())
{
startLength = 2;
}
return position == token.Span.End &&
(token.Span.Length == startLength || (token.Span.Length > startLength && token.ToString().Cast<char>().LastOrDefault() != lastChar));
}
public static bool IsEntirelyWithinStringOrCharLiteral(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return
syntaxTree.IsEntirelyWithinStringLiteral(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinCharLiteral(position, cancellationToken);
}
public static bool IsEntirelyWithinStringLiteral(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true);
// If we ask right at the end of the file, we'll get back nothing. We handle that case
// specially for now, though SyntaxTree.FindToken should work at the end of a file.
if (token.IsKind(SyntaxKind.EndOfDirectiveToken, SyntaxKind.EndOfFileToken))
{
token = token.GetPreviousToken(includeSkipped: true, includeDirectives: true);
}
if (token.IsKind(SyntaxKind.StringLiteralToken))
{
var span = token.Span;
// cases:
// "|"
// "| (e.g. incomplete string literal)
return (position > span.Start && position < span.End)
|| AtEndOfIncompleteStringOrCharLiteral(token, position, '"');
}
if (token.IsKind(SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.InterpolatedStringEndToken))
{
return token.SpanStart < position && token.Span.End > position;
}
return false;
}
public static bool IsEntirelyWithinCharLiteral(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
var token = root.FindToken(position, findInsideTrivia: true);
// If we ask right at the end of the file, we'll get back nothing.
// We handle that case specially for now, though SyntaxTree.FindToken should
// work at the end of a file.
if (position == root.FullWidth())
{
token = root.EndOfFileToken.GetPreviousToken(includeSkipped: true, includeDirectives: true);
}
if (token.Kind() == SyntaxKind.CharacterLiteralToken)
{
var span = token.Span;
// cases:
// '|'
// '| (e.g. incomplete char literal)
return (position > span.Start && position < span.End)
|| AtEndOfIncompleteStringOrCharLiteral(token, position, '\'');
}
return false;
}
public static bool IsInInactiveRegion(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(syntaxTree);
// cases:
// $ is EOF
// #if false
// |
// #if false
// |$
// #if false
// |
// #if false
// |$
if (syntaxTree.IsPreProcessorKeywordContext(position, cancellationToken))
{
return false;
}
// The latter two are the hard cases we don't actually have an
// DisabledTextTrivia yet.
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
return true;
}
var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
if (token.Kind() == SyntaxKind.EndOfFileToken)
{
var triviaList = token.LeadingTrivia;
foreach (var triviaTok in triviaList.Reverse())
{
if (triviaTok.Span.Contains(position))
{
return false;
}
if (triviaTok.Span.End < position)
{
if (!triviaTok.HasStructure)
{
return false;
}
var structure = triviaTok.GetStructure();
if (structure is BranchingDirectiveTriviaSyntax branch)
{
return !branch.IsActive || !branch.BranchTaken;
}
}
}
}
return false;
}
public static ImmutableArray<MemberDeclarationSyntax> GetMembersInSpan(
this SyntaxNode root, TextSpan textSpan)
{
var token = root.FindToken(textSpan.Start);
var firstMember = token.GetAncestors<MemberDeclarationSyntax>().FirstOrDefault();
if (firstMember != null)
{
if (firstMember.Parent is TypeDeclarationSyntax containingType)
{
return GetMembersInSpan(textSpan, containingType, firstMember);
}
}
return ImmutableArray<MemberDeclarationSyntax>.Empty;
}
private static ImmutableArray<MemberDeclarationSyntax> GetMembersInSpan(
TextSpan textSpan,
TypeDeclarationSyntax containingType,
MemberDeclarationSyntax firstMember)
{
var selectedMembers = ArrayBuilder<MemberDeclarationSyntax>.GetInstance();
try
{
var members = containingType.Members;
var fieldIndex = members.IndexOf(firstMember);
if (fieldIndex < 0)
{
return ImmutableArray<MemberDeclarationSyntax>.Empty;
}
for (var i = fieldIndex; i < members.Count; i++)
{
var member = members[i];
if (textSpan.Contains(member.Span))
{
selectedMembers.Add(member);
}
else if (textSpan.OverlapsWith(member.Span))
{
return ImmutableArray<MemberDeclarationSyntax>.Empty;
}
else
{
break;
}
}
return selectedMembers.ToImmutable();
}
finally
{
selectedMembers.Free();
}
}
public static bool IsInPartiallyWrittenGeneric(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out var genericIdentifier, out var lessThanToken);
}
public static bool IsInPartiallyWrittenGeneric(
this SyntaxTree syntaxTree,
int position,
CancellationToken cancellationToken,
out SyntaxToken genericIdentifier)
{
return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out var lessThanToken);
}
public static bool IsInPartiallyWrittenGeneric(
this SyntaxTree syntaxTree,
int position,
CancellationToken cancellationToken,
out SyntaxToken genericIdentifier,
out SyntaxToken lessThanToken)
{
genericIdentifier = default(SyntaxToken);
lessThanToken = default(SyntaxToken);
int index = 0;
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
if (token.Kind() == SyntaxKind.None)
{
return false;
}
// check whether we are under type or member decl
if (token.GetAncestor<TypeParameterListSyntax>() != null)
{
return false;
}
int stack = 0;
while (true)
{
switch (token.Kind())
{
case SyntaxKind.LessThanToken:
if (stack == 0)
{
// got here so we read successfully up to a < now we have to read the
// name before that and we're done!
lessThanToken = token;
token = token.GetPreviousToken(includeSkipped: true);
if (token.Kind() == SyntaxKind.None)
{
return false;
}
// ok
// so we've read something like:
// ~~~~~~~~~<a,b,...
// but we need to know the simple name that precedes the <
// it could be
// ~~~~~~foo<a,b,...
if (token.Kind() == SyntaxKind.IdentifierToken)
{
// okay now check whether it is actually partially written
if (IsFullyWrittenGeneric(token, lessThanToken))
{
return false;
}
genericIdentifier = token;
return true;
}
return false;
}
else
{
stack--;
break;
}
case SyntaxKind.GreaterThanGreaterThanToken:
stack++;
goto case SyntaxKind.GreaterThanToken;
// fall through
case SyntaxKind.GreaterThanToken:
stack++;
break;
case SyntaxKind.AsteriskToken: // for int*
case SyntaxKind.QuestionToken: // for int?
case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :)
case SyntaxKind.ColonColonToken: // for global::
case SyntaxKind.CloseBracketToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.DotToken:
case SyntaxKind.IdentifierToken:
break;
case SyntaxKind.CommaToken:
if (stack == 0)
{
index++;
}
break;
default:
// user might have typed "in" on the way to typing "int"
// don't want to disregard this genericname because of that
if (SyntaxFacts.IsKeywordKind(token.Kind()))
{
break;
}
// anything else and we're sunk.
return false;
}
// look backward one token, include skipped tokens, because the parser frequently
// does skip them in cases like: "Func<A, B", which get parsed as: expression
// statement "Func<A" with missing semicolon, expression statement "B" with missing
// semicolon, and the "," is skipped.
token = token.GetPreviousToken(includeSkipped: true);
if (token.Kind() == SyntaxKind.None)
{
return false;
}
}
}
private static bool IsFullyWrittenGeneric(SyntaxToken token, SyntaxToken lessThanToken)
{
var genericName = token.Parent as GenericNameSyntax;
return genericName != null && genericName.TypeArgumentList != null &&
genericName.TypeArgumentList.LessThanToken == lessThanToken && !genericName.TypeArgumentList.GreaterThanToken.IsMissing;
}
}
}
| |
using System;
using System.Linq;
using System.Windows.Input;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.VisualTree;
namespace Avalonia.Controls
{
/// <summary>
/// Defines how a <see cref="Button"/> reacts to clicks.
/// </summary>
public enum ClickMode
{
/// <summary>
/// The <see cref="Button.Click"/> event is raised when the pointer is released.
/// </summary>
Release,
/// <summary>
/// The <see cref="Button.Click"/> event is raised when the pointer is pressed.
/// </summary>
Press,
}
/// <summary>
/// A button control.
/// </summary>
[PseudoClasses(":pressed")]
public class Button : ContentControl, ICommandSource
{
/// <summary>
/// Defines the <see cref="ClickMode"/> property.
/// </summary>
public static readonly StyledProperty<ClickMode> ClickModeProperty =
AvaloniaProperty.Register<Button, ClickMode>(nameof(ClickMode));
/// <summary>
/// Defines the <see cref="Command"/> property.
/// </summary>
public static readonly DirectProperty<Button, ICommand> CommandProperty =
AvaloniaProperty.RegisterDirect<Button, ICommand>(nameof(Command),
button => button.Command, (button, command) => button.Command = command, enableDataValidation: true);
/// <summary>
/// Defines the <see cref="HotKey"/> property.
/// </summary>
public static readonly StyledProperty<KeyGesture> HotKeyProperty =
HotKeyManager.HotKeyProperty.AddOwner<Button>();
/// <summary>
/// Defines the <see cref="CommandParameter"/> property.
/// </summary>
public static readonly StyledProperty<object> CommandParameterProperty =
AvaloniaProperty.Register<Button, object>(nameof(CommandParameter));
/// <summary>
/// Defines the <see cref="IsDefaultProperty"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsDefaultProperty =
AvaloniaProperty.Register<Button, bool>(nameof(IsDefault));
/// <summary>
/// Defines the <see cref="IsCancelProperty"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsCancelProperty =
AvaloniaProperty.Register<Button, bool>(nameof(IsCancel));
/// <summary>
/// Defines the <see cref="Click"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> ClickEvent =
RoutedEvent.Register<Button, RoutedEventArgs>(nameof(Click), RoutingStrategies.Bubble);
public static readonly StyledProperty<bool> IsPressedProperty =
AvaloniaProperty.Register<Button, bool>(nameof(IsPressed));
/// <summary>
/// Defines the <see cref="Flyout"/> property
/// </summary>
public static readonly StyledProperty<FlyoutBase> FlyoutProperty =
AvaloniaProperty.Register<Button, FlyoutBase>(nameof(Flyout));
private ICommand _command;
private bool _commandCanExecute = true;
private KeyGesture _hotkey;
/// <summary>
/// Initializes static members of the <see cref="Button"/> class.
/// </summary>
static Button()
{
FocusableProperty.OverrideDefaultValue(typeof(Button), true);
CommandProperty.Changed.Subscribe(CommandChanged);
CommandParameterProperty.Changed.Subscribe(CommandParameterChanged);
IsDefaultProperty.Changed.Subscribe(IsDefaultChanged);
IsCancelProperty.Changed.Subscribe(IsCancelChanged);
}
public Button()
{
UpdatePseudoClasses(IsPressed);
}
/// <summary>
/// Raised when the user clicks the button.
/// </summary>
public event EventHandler<RoutedEventArgs> Click
{
add { AddHandler(ClickEvent, value); }
remove { RemoveHandler(ClickEvent, value); }
}
/// <summary>
/// Gets or sets a value indicating how the <see cref="Button"/> should react to clicks.
/// </summary>
public ClickMode ClickMode
{
get { return GetValue(ClickModeProperty); }
set { SetValue(ClickModeProperty, value); }
}
/// <summary>
/// Gets or sets an <see cref="ICommand"/> to be invoked when the button is clicked.
/// </summary>
public ICommand Command
{
get { return _command; }
set { SetAndRaise(CommandProperty, ref _command, value); }
}
/// <summary>
/// Gets or sets an <see cref="KeyGesture"/> associated with this control
/// </summary>
public KeyGesture HotKey
{
get { return GetValue(HotKeyProperty); }
set { SetValue(HotKeyProperty, value); }
}
/// <summary>
/// Gets or sets a parameter to be passed to the <see cref="Command"/>.
/// </summary>
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the button is the default button for the
/// window.
/// </summary>
public bool IsDefault
{
get { return GetValue(IsDefaultProperty); }
set { SetValue(IsDefaultProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the button is the Cancel button for the
/// window.
/// </summary>
public bool IsCancel
{
get { return GetValue(IsCancelProperty); }
set { SetValue(IsCancelProperty, value); }
}
public bool IsPressed
{
get { return GetValue(IsPressedProperty); }
private set { SetValue(IsPressedProperty, value); }
}
/// <summary>
/// Gets or sets the Flyout that should be shown with this button
/// </summary>
public FlyoutBase Flyout
{
get => GetValue(FlyoutProperty);
set => SetValue(FlyoutProperty, value);
}
protected override bool IsEnabledCore => base.IsEnabledCore && _commandCanExecute;
/// <inheritdoc/>
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
if (IsDefault)
{
if (e.Root is IInputElement inputElement)
{
ListenForDefault(inputElement);
}
}
if (IsCancel)
{
if (e.Root is IInputElement inputElement)
{
ListenForCancel(inputElement);
}
}
}
/// <inheritdoc/>
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
if (IsDefault)
{
if (e.Root is IInputElement inputElement)
{
StopListeningForDefault(inputElement);
}
}
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
if (_hotkey != null) // Control attached again, set Hotkey to create a hotkey manager for this control
{
HotKey = _hotkey;
}
base.OnAttachedToLogicalTree(e);
if (Command != null)
{
Command.CanExecuteChanged += CanExecuteChanged;
CanExecuteChanged(this, EventArgs.Empty);
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
// This will cause the hotkey manager to dispose the observer and the reference to this control
if (HotKey != null)
{
_hotkey = HotKey;
HotKey = null;
}
base.OnDetachedFromLogicalTree(e);
if (Command != null)
{
Command.CanExecuteChanged -= CanExecuteChanged;
}
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
OnClick();
e.Handled = true;
}
else if (e.Key == Key.Space)
{
if (ClickMode == ClickMode.Press)
{
OnClick();
}
IsPressed = true;
e.Handled = true;
}
else if (e.Key == Key.Escape && Flyout != null)
{
// If Flyout doesn't have focusable content, close the flyout here
Flyout.Hide();
}
base.OnKeyDown(e);
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.Key == Key.Space)
{
if (ClickMode == ClickMode.Release)
{
OnClick();
}
IsPressed = false;
e.Handled = true;
}
}
/// <summary>
/// Invokes the <see cref="Click"/> event.
/// </summary>
protected virtual void OnClick()
{
OpenFlyout();
var e = new RoutedEventArgs(ClickEvent);
RaiseEvent(e);
if (!e.Handled && Command?.CanExecute(CommandParameter) == true)
{
Command.Execute(CommandParameter);
e.Handled = true;
}
}
protected virtual void OpenFlyout()
{
Flyout?.ShowAt(this);
}
/// <inheritdoc/>
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
{
IsPressed = true;
e.Handled = true;
if (ClickMode == ClickMode.Press)
{
OnClick();
}
}
}
/// <inheritdoc/>
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (IsPressed && e.InitialPressMouseButton == MouseButton.Left)
{
IsPressed = false;
e.Handled = true;
if (ClickMode == ClickMode.Release &&
this.GetVisualsAt(e.GetPosition(this)).Any(c => this == c || this.IsVisualAncestorOf(c)))
{
OnClick();
}
}
}
protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)
{
IsPressed = false;
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == IsPressedProperty)
{
UpdatePseudoClasses(change.NewValue.GetValueOrDefault<bool>());
}
else if (change.Property == FlyoutProperty)
{
// If flyout is changed while one is already open, make sure we
// close the old one first
if (change.OldValue.GetValueOrDefault() is FlyoutBase oldFlyout &&
oldFlyout.IsOpen)
{
oldFlyout.Hide();
}
}
}
protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value)
{
base.UpdateDataValidation(property, value);
if (property == CommandProperty)
{
if (value.Type == BindingValueType.BindingError)
{
if (_commandCanExecute)
{
_commandCanExecute = false;
UpdateIsEffectivelyEnabled();
}
}
}
}
/// <summary>
/// Called when the <see cref="Command"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void CommandChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is Button button)
{
if (((ILogical)button).IsAttachedToLogicalTree)
{
if (e.OldValue is ICommand oldCommand)
{
oldCommand.CanExecuteChanged -= button.CanExecuteChanged;
}
if (e.NewValue is ICommand newCommand)
{
newCommand.CanExecuteChanged += button.CanExecuteChanged;
}
}
button.CanExecuteChanged(button, EventArgs.Empty);
}
}
/// <summary>
/// Called when the <see cref="CommandParameter"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void CommandParameterChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is Button button)
{
button.CanExecuteChanged(button, EventArgs.Empty);
}
}
/// <summary>
/// Called when the <see cref="IsDefault"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void IsDefaultChanged(AvaloniaPropertyChangedEventArgs e)
{
var button = e.Sender as Button;
var isDefault = (bool)e.NewValue;
if (button?.VisualRoot is IInputElement inputRoot)
{
if (isDefault)
{
button.ListenForDefault(inputRoot);
}
else
{
button.StopListeningForDefault(inputRoot);
}
}
}
/// <summary>
/// Called when the <see cref="IsCancel"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void IsCancelChanged(AvaloniaPropertyChangedEventArgs e)
{
var button = e.Sender as Button;
var isCancel = (bool)e.NewValue;
if (button?.VisualRoot is IInputElement inputRoot)
{
if (isCancel)
{
button.ListenForCancel(inputRoot);
}
else
{
button.StopListeningForCancel(inputRoot);
}
}
}
/// <summary>
/// Called when the <see cref="ICommand.CanExecuteChanged"/> event fires.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void CanExecuteChanged(object sender, EventArgs e)
{
var canExecute = Command == null || Command.CanExecute(CommandParameter);
if (canExecute != _commandCanExecute)
{
_commandCanExecute = canExecute;
UpdateIsEffectivelyEnabled();
}
}
/// <summary>
/// Starts listening for the Enter key when the button <see cref="IsDefault"/>.
/// </summary>
/// <param name="root">The input root.</param>
private void ListenForDefault(IInputElement root)
{
root.AddHandler(KeyDownEvent, RootDefaultKeyDown);
}
/// <summary>
/// Starts listening for the Escape key when the button <see cref="IsCancel"/>.
/// </summary>
/// <param name="root">The input root.</param>
private void ListenForCancel(IInputElement root)
{
root.AddHandler(KeyDownEvent, RootCancelKeyDown);
}
/// <summary>
/// Stops listening for the Enter key when the button is no longer <see cref="IsDefault"/>.
/// </summary>
/// <param name="root">The input root.</param>
private void StopListeningForDefault(IInputElement root)
{
root.RemoveHandler(KeyDownEvent, RootDefaultKeyDown);
}
/// <summary>
/// Stops listening for the Escape key when the button is no longer <see cref="IsCancel"/>.
/// </summary>
/// <param name="root">The input root.</param>
private void StopListeningForCancel(IInputElement root)
{
root.RemoveHandler(KeyDownEvent, RootCancelKeyDown);
}
/// <summary>
/// Called when a key is pressed on the input root and the button <see cref="IsDefault"/>.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void RootDefaultKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && IsVisible && IsEnabled)
{
OnClick();
}
}
/// <summary>
/// Called when a key is pressed on the input root and the button <see cref="IsCancel"/>.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void RootCancelKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape && IsVisible && IsEnabled)
{
OnClick();
}
}
private void UpdatePseudoClasses(bool isPressed)
{
PseudoClasses.Set(":pressed", isPressed);
}
void ICommandSource.CanExecuteChanged(object sender, EventArgs e) => this.CanExecuteChanged(sender, e);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace TestAspNetSpa.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;
namespace Umbraco.Cms.Core.Services.Implement
{
public sealed class AuditService : RepositoryService, IAuditService
{
private readonly Lazy<bool> _isAvailable;
private readonly IAuditRepository _auditRepository;
private readonly IAuditEntryRepository _auditEntryRepository;
public AuditService(IScopeProvider provider, ILoggerFactory loggerFactory, IEventMessagesFactory eventMessagesFactory,
IAuditRepository auditRepository, IAuditEntryRepository auditEntryRepository)
: base(provider, loggerFactory, eventMessagesFactory)
{
_auditRepository = auditRepository;
_auditEntryRepository = auditEntryRepository;
_isAvailable = new Lazy<bool>(DetermineIsAvailable);
}
public void Add(AuditType type, int userId, int objectId, string entityType, string comment, string parameters = null)
{
using (var scope = ScopeProvider.CreateScope())
{
_auditRepository.Save(new AuditItem(objectId, type, userId, entityType, comment, parameters));
scope.Complete();
}
}
public IEnumerable<IAuditItem> GetLogs(int objectId)
{
using (var scope = ScopeProvider.CreateScope())
{
var result = _auditRepository.Get(Query<IAuditItem>().Where(x => x.Id == objectId));
scope.Complete();
return result;
}
}
public IEnumerable<IAuditItem> GetUserLogs(int userId, AuditType type, DateTime? sinceDate = null)
{
using (var scope = ScopeProvider.CreateScope())
{
var result = sinceDate.HasValue == false
? _auditRepository.Get(type, Query<IAuditItem>().Where(x => x.UserId == userId))
: _auditRepository.Get(type, Query<IAuditItem>().Where(x => x.UserId == userId && x.CreateDate >= sinceDate.Value));
scope.Complete();
return result;
}
}
public IEnumerable<IAuditItem> GetLogs(AuditType type, DateTime? sinceDate = null)
{
using (var scope = ScopeProvider.CreateScope())
{
var result = sinceDate.HasValue == false
? _auditRepository.Get(type, Query<IAuditItem>())
: _auditRepository.Get(type, Query<IAuditItem>().Where(x => x.CreateDate >= sinceDate.Value));
scope.Complete();
return result;
}
}
public void CleanLogs(int maximumAgeOfLogsInMinutes)
{
using (var scope = ScopeProvider.CreateScope())
{
_auditRepository.CleanLogs(maximumAgeOfLogsInMinutes);
scope.Complete();
}
}
/// <summary>
/// Returns paged items in the audit trail for a given entity
/// </summary>
/// <param name="entityId"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <param name="orderDirection">
/// By default this will always be ordered descending (newest first)
/// </param>
/// <param name="auditTypeFilter">
/// Since we currently do not have enum support with our expression parser, we cannot query on AuditType in the query or the custom filter
/// so we need to do that here
/// </param>
/// <param name="customFilter">
/// Optional filter to be applied
/// </param>
/// <returns></returns>
public IEnumerable<IAuditItem> GetPagedItemsByEntity(int entityId, long pageIndex, int pageSize, out long totalRecords,
Direction orderDirection = Direction.Descending,
AuditType[] auditTypeFilter = null,
IQuery<IAuditItem> customFilter = null)
{
if (pageIndex < 0) throw new ArgumentOutOfRangeException(nameof(pageIndex));
if (pageSize <= 0) throw new ArgumentOutOfRangeException(nameof(pageSize));
if (entityId == Cms.Core.Constants.System.Root || entityId <= 0)
{
totalRecords = 0;
return Enumerable.Empty<IAuditItem>();
}
using (ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IAuditItem>().Where(x => x.Id == entityId);
return _auditRepository.GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, orderDirection, auditTypeFilter, customFilter);
}
}
/// <summary>
/// Returns paged items in the audit trail for a given user
/// </summary>
/// <param name="userId"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <param name="orderDirection">
/// By default this will always be ordered descending (newest first)
/// </param>
/// <param name="auditTypeFilter">
/// Since we currently do not have enum support with our expression parser, we cannot query on AuditType in the query or the custom filter
/// so we need to do that here
/// </param>
/// <param name="customFilter">
/// Optional filter to be applied
/// </param>
/// <returns></returns>
public IEnumerable<IAuditItem> GetPagedItemsByUser(int userId, long pageIndex, int pageSize, out long totalRecords, Direction orderDirection = Direction.Descending, AuditType[] auditTypeFilter = null, IQuery<IAuditItem> customFilter = null)
{
if (pageIndex < 0) throw new ArgumentOutOfRangeException(nameof(pageIndex));
if (pageSize <= 0) throw new ArgumentOutOfRangeException(nameof(pageSize));
if (userId < Cms.Core.Constants.Security.SuperUserId)
{
totalRecords = 0;
return Enumerable.Empty<IAuditItem>();
}
using (ScopeProvider.CreateScope(autoComplete: true))
{
var query = Query<IAuditItem>().Where(x => x.UserId == userId);
return _auditRepository.GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, orderDirection, auditTypeFilter, customFilter);
}
}
/// <inheritdoc />
public IAuditEntry Write(int performingUserId, string perfomingDetails, string performingIp, DateTime eventDateUtc, int affectedUserId, string affectedDetails, string eventType, string eventDetails)
{
if (performingUserId < 0 && performingUserId != Cms.Core.Constants.Security.SuperUserId) throw new ArgumentOutOfRangeException(nameof(performingUserId));
if (string.IsNullOrWhiteSpace(perfomingDetails)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(perfomingDetails));
if (string.IsNullOrWhiteSpace(eventType)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(eventType));
if (string.IsNullOrWhiteSpace(eventDetails)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(eventDetails));
//we need to truncate the data else we'll get SQL errors
affectedDetails = affectedDetails?.Substring(0, Math.Min(affectedDetails.Length, AuditEntryDto.DetailsLength));
eventDetails = eventDetails.Substring(0, Math.Min(eventDetails.Length, AuditEntryDto.DetailsLength));
//validate the eventType - must contain a forward slash, no spaces, no special chars
var eventTypeParts = eventType.ToCharArray();
if (eventTypeParts.Contains('/') == false || eventTypeParts.All(c => char.IsLetterOrDigit(c) || c == '/' || c == '-') == false)
throw new ArgumentException(nameof(eventType) + " must contain only alphanumeric characters, hyphens and at least one '/' defining a category");
if (eventType.Length > AuditEntryDto.EventTypeLength)
throw new ArgumentException($"Must be max {AuditEntryDto.EventTypeLength} chars.", nameof(eventType));
if (performingIp != null && performingIp.Length > AuditEntryDto.IpLength)
throw new ArgumentException($"Must be max {AuditEntryDto.EventTypeLength} chars.", nameof(performingIp));
var entry = new AuditEntry
{
PerformingUserId = performingUserId,
PerformingDetails = perfomingDetails,
PerformingIp = performingIp,
EventDateUtc = eventDateUtc,
AffectedUserId = affectedUserId,
AffectedDetails = affectedDetails,
EventType = eventType,
EventDetails = eventDetails
};
if (_isAvailable.Value == false) return entry;
using (var scope = ScopeProvider.CreateScope())
{
_auditEntryRepository.Save(entry);
scope.Complete();
}
return entry;
}
// TODO: Currently used in testing only, not part of the interface, need to add queryable methods to the interface instead
internal IEnumerable<IAuditEntry> GetAll()
{
if (_isAvailable.Value == false) return Enumerable.Empty<IAuditEntry>();
using (ScopeProvider.CreateScope(autoComplete: true))
{
return _auditEntryRepository.GetMany();
}
}
// TODO: Currently used in testing only, not part of the interface, need to add queryable methods to the interface instead
internal IEnumerable<IAuditEntry> GetPage(long pageIndex, int pageCount, out long records)
{
if (_isAvailable.Value == false)
{
records = 0;
return Enumerable.Empty<IAuditEntry>();
}
using (ScopeProvider.CreateScope(autoComplete: true))
{
return _auditEntryRepository.GetPage(pageIndex, pageCount, out records);
}
}
/// <summary>
/// Determines whether the repository is available.
/// </summary>
private bool DetermineIsAvailable()
{
using (ScopeProvider.CreateScope(autoComplete: true))
{
return _auditEntryRepository.IsAvailable();
}
}
}
}
| |
using System;
using NUnit.Framework;
using System.IO;
using System.Diagnostics;
using Parrano.Api;
namespace Parrano.Tests
{
[TestFixture]
public class PSLibExtensionsTests
{
[SetUp]
public void SetUp()
{
tempFilename = Path.GetTempFileName();
}
[TearDown]
public void TearDown()
{
if (File.Exists(tempFilename))
{
try
{
File.Delete(tempFilename);
}
catch { }
}
}
private string tempFilename;
[Test]
public void TestOpenPSDocHandleFilename()
{
string filename = tempFilename;
IntPtr psdoc = PSLibExtensions.OpenPSDocHandle(filename);
Assert.That(psdoc.ToInt32() > 0, "OpenPSDocHandle method returned unexpected result.");
PSLibExtensions.ClosePSDocHandle(psdoc);
string resultFileContents = File.ReadAllText(tempFilename);
Trace.WriteLine("Contents:");
Trace.WriteLine(resultFileContents);
Assert.That(
resultFileContents.StartsWith("%!PS-Adobe-3.0"),
"File was created, but the contents are wrong.");
Assert.That(resultFileContents.Contains(
"%%BeginSetup" + Environment.NewLine +
"PslibDict begin" + Environment.NewLine +
"%%EndSetup"),
"File was created, but the contents are wrong.");
Assert.That(resultFileContents.EndsWith("%%EOF"),
"File was created, but the contents are wrong.");
}
[Test]
public void TestOpenPSDocHandleFilenamePageSize()
{
string filename = tempFilename;
PageSize pageSize = PageSize.Letter;
IntPtr expectedIntPtr = IntPtr.Zero;
IntPtr resultIntPtr = IntPtr.Zero;
resultIntPtr = PSLibExtensions.OpenPSDocHandle(filename, pageSize);
Assert.Less(expectedIntPtr.ToInt32(), resultIntPtr.ToInt32(), "OpenPSDocHandle method returned unexpected result.");
PSLibExtensions.ClosePSDocHandle(resultIntPtr);
string resultFileContents = File.ReadAllText(tempFilename);
Trace.WriteLine("Contents:");
Trace.WriteLine(resultFileContents);
Assert.That(
resultFileContents.Contains(
"%%Page: 1 1" + Environment.NewLine +
"%%PageBoundingBox: 0 0 612 792"
),
"File was created, but the contents are wrong.");
}
[Test]
public void TestOpenPSDocHandleFilenamePageWidthPageHeight()
{
string filename = tempFilename;
IntPtr psdoc = PSLibExtensions.OpenPSDocHandle(filename, PSLibExtensions.LetterWidth, PSLibExtensions.LetterHeight);
Assert.That(psdoc.ToInt32() > 0, "OpenPSDocHandle method returned unexpected result.");
PSLibExtensions.ClosePSDocHandle(psdoc);
string resultFileContents = File.ReadAllText(tempFilename);
Trace.WriteLine("Contents:");
Trace.WriteLine(resultFileContents);
Assert.That(
resultFileContents.Contains(
"%%Page: 1 1" + Environment.NewLine +
"%%PageBoundingBox: 0 0 " + PSLibExtensions.LetterWidth + " " + PSLibExtensions.LetterHeight),
"File was created, but the contents are wrong.");
}
private static string GetPSLibVersionString()
{
return "pslib " + PSLib.PS_get_majorversion() + "." + PSLib.PS_get_minorversion() + "." + PSLib.PS_get_subminorversion();
}
[Test]
public void TestOpenPSDocHandleFilenamePageWidthPageHeightInfoValues()
{
string filename = tempFilename;
InfoFields infoFields = new InfoFields();
infoFields.Author = "Ursula Kroeber Le Guin";
infoFields.Subject = "Testing Parrano";
infoFields.Title = "A test document";
infoFields.Creator = "Parrano v1.0";
IntPtr psdoc = PSLibExtensions.OpenPSDocHandle(filename, PSLibExtensions.LetterWidth, PSLibExtensions.LetterHeight, infoFields);
Assert.That(psdoc.ToInt32() > 0, "OpenPSDocHandle method returned unexpected result.");
PSLibExtensions.ClosePSDocHandle(psdoc);
string resultFileContents = File.ReadAllText(tempFilename);
Trace.WriteLine("Contents:");
Trace.WriteLine(resultFileContents);
string version = GetPSLibVersionString();
// validate doc created
Assert.That(
resultFileContents.Contains(
"%%Page: 1 1" + Environment.NewLine +
"%%PageBoundingBox: 0 0 " + PSLibExtensions.LetterWidth + " " + PSLibExtensions.LetterHeight),
"File was created, but the contents are wrong.");
// validate DSC comments.
Assert.That(
resultFileContents.Contains(
string.Format("%%{0}: {1} ({2})", "Creator", infoFields.Creator, version)),
"File contents look wrong.");
Assert.That(
resultFileContents.Contains(
string.Format("%%{0}: {1}", "Author", infoFields.Author)),
"File contents look wrong.");
Assert.That(
resultFileContents.Contains(
string.Format("%%{0}: {1}", "Title", infoFields.Title)),
"File contents look wrong.");
// validate pdfmarks
Assert.That(
resultFileContents.Contains(
string.Format("/{0} ({1})", "Subject", infoFields.Subject)),
"File contents look wrong.");
Assert.That(
resultFileContents.Contains(
string.Format("/{0} ({1})", "Author", infoFields.Author)),
"File contents look wrong.");
Assert.That(
resultFileContents.Contains(
string.Format("/{0} ({1})", "Title", infoFields.Title)),
"File contents look wrong.");
Assert.That(
resultFileContents.Contains(
string.Format("/{0} ({1} \\({2}\\))", "Creator", infoFields.Creator, version)),
"File contents look wrong.");
}
[Test]
public void TestDrawLine()
{
Random r = new Random();
float x1 = r.Next(256);
float y1 = r.Next(256);
float x2 = r.Next(256);
float y2 = r.Next(256);
string filename = tempFilename;
IntPtr psdoc = PSLibExtensions.OpenPSDocHandle(filename);
Assert.That(psdoc.ToInt32() > 0, "OpenPSDocHandle method returned unexpected result.");
PSLibExtensions.DrawLine(psdoc, x1, y1, x2, y2);
PSLibExtensions.ClosePSDocHandle(psdoc);
string resultFileContents = File.ReadAllText(tempFilename);
Trace.WriteLine("Contents:");
Trace.WriteLine(resultFileContents);
Assert.That(
resultFileContents.StartsWith("%!PS-Adobe-3.0"),
"File was created, but beginning looks wrong.");
Assert.That(
resultFileContents.Contains(
"%%BeginSetup" + Environment.NewLine +
"PslibDict begin" + Environment.NewLine +
"%%EndSetup"),
"File was created, but setup looks wrong.");
string expectedLinePhrase = "newpath" + Environment.NewLine +
string.Format("{0:0.00} {1:0.00} a", x1, y1) + Environment.NewLine +
string.Format("{0:0.00} {1:0.00} l", x2, y2) + Environment.NewLine +
"stroke";
Trace.WriteLine(string.Empty);
Trace.WriteLine("Expected line phrase:");
Trace.WriteLine(expectedLinePhrase);
Trace.WriteLine(string.Empty);
Assert.That(
resultFileContents.Contains(expectedLinePhrase),
"File was created, but line phrase looks wrong.");
Assert.That(
resultFileContents.EndsWith("%%EOF"),
"File was created, but end looks wrong.");
}
[Test]
public void TestClosePSDocHandle()
{
IntPtr psdoc = IntPtr.Zero;
// make sure that calling this with a bad handle causes the expected exception
try
{
PSLibExtensions.ClosePSDocHandle(psdoc);
}
catch (Exception ex)
{
Assert.IsTrue(ex is AccessViolationException);
}
// get a valid handle
psdoc = PSLibExtensions.OpenPSDocHandle(tempFilename);
Assert.That(psdoc.ToInt32() > 0, "OpenPSDocHandle method returned unexpected result.");
try
{
// close the valid handle
PSLibExtensions.ClosePSDocHandle(psdoc);
}
catch (AccessViolationException avEx)
{
// if closing a valid handle causes this exception
// well, that's really weird.
Assert.Fail("The pointer returned seems to be valid, but caused an exception when closing it. Exception was: " + avEx.Message);
}
catch (Exception ex)
{
// if some other exception happens, just pass it along.
Assert.Fail("An unknown exception occured when closing the handle. Exception was: " + ex.Message);
}
// check the file for valid contents.
string resultFileContents = File.ReadAllText(tempFilename);
Trace.WriteLine("Contents:");
Trace.WriteLine(resultFileContents);
Assert.That(
resultFileContents.StartsWith("%!PS-Adobe-3.0"),
"File was created, but the contents are wrong.");
Assert.That(resultFileContents.Contains(
"%%BeginSetup" + Environment.NewLine +
"PslibDict begin" + Environment.NewLine +
"%%EndSetup"),
"File was created, but the contents are wrong.");
Assert.That(resultFileContents.EndsWith("%%EOF"),
"File was created, but the contents are wrong.");
}
}
}
| |
public class LimLexer
{
public static string specialChars = ":._";
public string s;
public int currentPos;
public char current { get { return s[currentPos]; } }
public ArrayList charLineIndex = new ArrayList();
public long lineHint;
public long maxChar;
public Stack posStack = new Stack();
public Stack tokenStack = new Stack();
public ArrayList tokenStream = new ArrayList();
public int resultIndex = 0;
public LimToken errorToken;
public string errorDescription;
public void print()
{
LimToken first = tokenStream.Get(0) as LimToken;
if (first != null)
{
first.print();
}
System.Console.WriteLine();
}
public void printTokens()
{
int i;
for (i = 0; i < tokenStream.Count; i++)
{
LimToken t = tokenStream.Get(i) as LimToken;
System.Console.Write("'{0}' {1}", t.name, t.typeName());
if (i < tokenStream.Count - 1)
{
System.Console.Write(", ");
}
}
System.Console.WriteLine();
}
public int lex()
{
pushPos();
messageChain();
if (!onNULL())
{
if (errorToken == null)
{
if (tokenStream.Count != 0)
{
errorToken = currentToken();
}
else
{
errorToken = addTokenStringType(s.Substring(currentPos, 30), LimTokenType.NO_TOKEN);
}
errorToken.error = "Syntax error near this location";
}
return -1;
}
return 0;
}
public LimToken top()
{
if (resultIndex >= tokenStream.Count) return null;
return tokenStream.Get(resultIndex) as LimToken;
}
public int lastPos()
{
return System.Convert.ToInt32(posStack.Peek());
}
public void pushPos()
{
tokenStack.Push(tokenStream.Count - 1);
posStack.Push(currentPos);
}
public void popPos()
{
tokenStack.Pop();
posStack.Pop();
}
public LimTokenType topType()
{
if (top() == null) return 0;
return top().type;
}
public LimToken pop()
{
LimToken first = top();
resultIndex++;
return first;
}
public void popPosBack()
{
int i = System.Convert.ToInt32(tokenStack.Pop());
int topIndex = System.Convert.ToInt32(tokenStack.Peek());
if (i > -1)
{
if (i != topIndex)
{
LimToken parent = currentToken();
if (parent != null)
{
parent.nextToken = null;
}
}
}
currentPos = System.Convert.ToInt32(posStack.Pop());
}
public char nextChar()
{
if (currentPos >= s.Length)
return '\0';
char c = current;
currentPos++;
return c;
}
public char peekChar()
{
if (currentPos >= s.Length)
return '\0';
char c = current;
return c;
}
public char prevChar()
{
currentPos--;
char c = current;
return c;
}
public int readPadding()
{
int r = 0;
while (readWhitespace() != 0 || readComment() != 0)
{
r = 1;
}
return r;
}
// grabbing
public int grabLength()
{
int i1 = lastPos();
int i2 = currentPos;
return i2 - i1;
}
public LimToken grabTokenType(LimTokenType type)
{
int len = grabLength();
string s1 = s.Substring(lastPos(), len);
if (len == 0)
{
throw new System.Exception("LimLexer fatal error: empty token\n");
}
return addTokenStringType(s1, type);
}
public int currentLineNumber()
{
return 0;
}
public LimToken addTokenStringType(string s1, LimTokenType type)
{
LimToken top = currentToken();
LimToken t = new LimToken();
t.lineNumber = currentLineNumber();
t.charNumber = currentPos;
if (t.charNumber < 0)
{
System.Console.WriteLine("bad t->charNumber = %i\n", t.charNumber);
}
t.name = s1;
t.type = type;
if (top != null)
{
top.nextToken = t;
}
tokenStream.Add(t);
return t;
}
public LimToken currentToken()
{
if (tokenStream.Count == 0) return null;
return tokenStream.Get(tokenStream.Count - 1) as LimToken;
}
// message chain
public void messageChain()
{
do
{
while (readTerminator() != 0 || readSeparator() != 0 || readComment() != 0) ;
} while (readMessage() != 0);
}
// symbols
public int readSymbol()
{
if (readNumber() != 0 || readOperator() != 0 || readIdentifier() != 0 || readQuote() != 0) return 1;
return 0;
}
public int readIdentifier()
{
pushPos();
while (readLetter() != 0 || readDigit() != 0 || readSpecialChar() != 0) ;
if (grabLength() != 0)
{
if (s[currentPos - 1] == ':' && s[currentPos] == '=') prevChar();
grabTokenType(LimTokenType.IDENTIFIER_TOKEN);
popPos();
return 1;
}
return 0;
}
public int readOperator()
{
char c;
pushPos();
c = nextChar();
if (c == 0)
{
popPosBack();
return 0;
}
else {
prevChar();
}
while (readOpChar() != 0) ;
if (grabLength() != 0)
{
grabTokenType(LimTokenType.IDENTIFIER_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
public bool onNULL()
{
return currentPos == s.Length;
}
// helpers
public int readTokenCharsType(string chars, LimTokenType type)
{
foreach (char c in chars)
{
if (readTokenCharType(c, type) != 0)
return 1;
}
return 0;
}
public int readTokenCharType(char c, LimTokenType type)
{
pushPos();
if (readChar(c) != 0)
{
grabTokenType(type);
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readTokenString(string s)
{
pushPos();
if (readString(s) != 0)
{
grabTokenType(LimTokenType.IDENTIFIER_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readString(string str)
{
int len = str.Length;
if (len > s.Length - currentPos)
len = s.Length - currentPos;
if (onNULL())
{
return 0;
}
string inmem = s.Substring(currentPos, len);
if (inmem.Equals(str))
{
currentPos += len;
return 1;
}
return 0;
}
public int readCharIn(string s)
{
if (!onNULL())
{
char c = nextChar();
if (s.IndexOf(c) != -1)
{
return 1;
}
prevChar();
}
return 0;
}
public int readCharInRange(char first, char last)
{
if (!onNULL())
{
char c = nextChar();
if ((int)c >= (int)first && (int)c <= (int)last)
{
return 1;
}
prevChar();
}
return 0;
}
public int readNonASCIIChar()
{
if (!onNULL())
{
char nc = nextChar();
if (nc >= 0x80)
return 1;
prevChar();
}
return 0;
}
public int readChar(char ch)
{
if (!onNULL())
{
char c = nextChar();
if (c == ch)
{
return 1;
}
prevChar();
}
return 0;
}
public int readCharAnyCase(char ch)
{
if (!onNULL())
{
char c = nextChar();
if (System.Char.ToLower(c) == System.Char.ToLower(ch))
{
return 1;
}
prevChar();
}
return 0;
}
public bool readNonReturn()
{
if (onNULL()) return false;
if (nextChar() != '\n') return true;
prevChar();
return false;
}
public bool readNonQuote()
{
if (onNULL()) return false;
if (nextChar() != '"') return true;
prevChar();
return false;
}
// character definitions
public int readCharacters()
{
int read = 0;
while (readCharacter() != 0)
{
read = 1;
}
return read;
}
public int readCharacter()
{
return System.Convert.ToInt32(readLetter() != 0 || readDigit() != 0 || readSpecialChar() != 0 || readOpChar() != 0);
}
public int readOpChar()
{
return readCharIn(":'~!@$%^&*-+=|\\<>?/");
}
public int readSpecialChar()
{
return readCharIn(LimLexer.specialChars);
}
public int readDigit()
{
return readCharInRange('0', '9');
}
public int readLetter() // grab all symbols
{
return System.Convert.ToInt32(readCharInRange('A', 'Z') != 0 || readCharInRange('a', 'z') != 0
|| readNonASCIIChar() != 0);
}
// comments
public int readComment()
{
return readSlashSlashComment();
}
private int readSlashSlashComment()
{
this.pushPos();
if (nextChar() == '/')
{
if (nextChar() == '/')
{
while (readNonReturn()) { }
popPos();
return 1;
}
}
popPosBack();
return 0;
}
// quotes
public int readQuote()
{
return System.Convert.ToInt32(readTriQuote() != 0 || readMonoQuote() != 0);
}
public int readMonoQuote()
{
pushPos();
if (nextChar() == '"')
{
while (true)
{
char c = nextChar();
if (c == '"')
{
break;
}
if (c == '\\')
{
nextChar();
continue;
}
if (c == 0)
{
errorToken = currentToken();
if (errorToken != null)
{
errorToken.error = "unterminated quote";
}
popPosBack();
return 0;
}
}
grabTokenType(LimTokenType.MONOQUOTE_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readTriQuote()
{
pushPos();
if (readString("\"\"\"") != 0)
{
while (readString("\"\"\"") == 0)
{
char c = nextChar();
if (c == 0)
{
popPosBack();
return 0;
}
}
grabTokenType(LimTokenType.TRIQUOTE_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
// terminators
public int readTerminator()
{
int terminated = 0;
pushPos();
readSeparator();
while (readTerminatorChar() != 0)
{
terminated = 1;
readSeparator();
}
if (terminated != 0)
{
LimToken top = currentToken();
// avoid double terminators
if (top != null && top.type == LimTokenType.TERMINATOR_TOKEN)
{
return 1;
}
addTokenStringType(";", LimTokenType.TERMINATOR_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readTerminatorChar()
{
return readCharIn(";\n");
}
// separators
public int readSeparator()
{
pushPos();
while (readSeparatorChar() != 0) ;
if (grabLength() != 0)
{
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readSeparatorChar()
{
if (readCharIn(" \f\r\t\v") != 0)
{
return 1;
}
else
{
pushPos();
if (readCharIn("\\") != 0)
{
while (readCharIn(" \f\r\t\v") != 0) ;
if (readCharIn("\n") != 0)
{
popPos();
return 1;
}
}
popPosBack();
return 0;
}
}
// whitespace
int readWhitespace()
{
pushPos();
while (readWhitespaceChar() != 0) ;
if (grabLength() != 0)
{
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readWhitespaceChar()
{
return readCharIn(" \f\r\t\v\n");
}
///
public int readDigits()
{
int read = 0;
pushPos();
while (readDigit() != 0)
{
read = 1;
}
if (read == 0)
{
popPosBack();
return 0;
}
popPos();
return read;
}
public int readNumber()
{
return System.Convert.ToInt32(readHexNumber() != 0 || readDecimal() != 0);
}
public int readExponent()
{
if (readCharAnyCase('e') != 0)
{
if (readChar('-') != 0 || readChar('+') != 0) { }
if (readDigits() == 0)
{
return -1;
}
return 1;
}
return 0;
}
public int readDecimalPlaces()
{
if (readChar('.') != 0)
{
if (readDigits() == 0)
{
return -1;
}
return 1;
}
return 0;
}
public int readDecimal()
{
pushPos();
if (readDigits() != 0)
{
if (readDecimalPlaces() == -1)
{
popPosBack();
return 0;
}
}
else
{
if (readDecimalPlaces() != 1)
{
popPosBack();
return 0;
}
}
if (readExponent() == -1)
{
popPosBack();
return 0;
}
if (grabLength() != 0)
{
grabTokenType(LimTokenType.NUMBER_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readHexNumber()
{
int read = 0;
pushPos();
if (readChar('0') != 0 && readCharAnyCase('x') != 0)
{
while (readDigits() != 0 || readCharacters() != 0)
{
read++;
}
}
if (read != 0 && grabLength() != 0)
{
grabTokenType(LimTokenType.HEXNUMBER_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
/// message
public string nameForGroupChar(char groupChar)
{
switch (groupChar)
{
case '(': return "";
case '[': return "squareBrackets";
case '{': return "curlyBrackets";
}
throw new System.Exception("LimLexer: fatal error - invalid group char" + groupChar);
}
public void readMessageError(string name)
{
popPosBack();
errorToken = currentToken();
errorToken.error = name;
}
public int readMessage()
{
int foundSymbol = 0;
pushPos();
readPadding();
foundSymbol = readSymbol();
char groupChar;
while (readSeparator() != 0 || readComment() != 0) ;
groupChar = peekChar();
// this is bug in original IoVM so I've commented this out
if ("[{".IndexOf(groupChar) != -1 || (foundSymbol == 0 &&
groupChar == '('))
{
string groupName = nameForGroupChar(groupChar);
addTokenStringType(groupName, LimTokenType.IDENTIFIER_TOKEN);
}
if (readTokenCharsType("([{", LimTokenType.OPENPAREN_TOKEN) != 0)
{
readPadding();
do
{
LimTokenType type = currentToken().type;
readPadding();
// Empty argument: (... ,)
if (LimTokenType.COMMA_TOKEN == type)
{
char c = current;
if (',' == c || ")]}".IndexOf(c) != -1)
{
readMessageError("missing argument in argument list");
return 0;
}
}
if (groupChar == '[') specialChars = "._";
messageChain();
if (groupChar == '[') specialChars = ":._";
readPadding();
} while (readTokenCharType(',', LimTokenType.COMMA_TOKEN) != 0);
if (readTokenCharsType(")]}", LimTokenType.CLOSEPAREN_TOKEN) == 0)
{
if (groupChar == '(')
{
readMessageError("unmatched ()s");
}
else if (groupChar == '[')
{
readMessageError("unmatched []s");
}
else if (groupChar == '{')
{
readMessageError("unmatched {}s");
}
return 0;
}
popPos();
return 1;
}
if (foundSymbol != 0)
{
popPos();
return 1;
}
popPosBack();
return 0;
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AfricasTalkingCS;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
namespace AfricasTalkingCS_Tests
{
[TestClass]
public class PaymentService
{
private static string apikey = "6c36e56b86c24c2ff66adaff340d60793dff71ac304bc551f7056ca76dd8032a";
private static string username = "sandbox";
private readonly AfricasTalkingGateway _atGWInstance = new AfricasTalkingGateway(username,apikey);
private string TestId = "ATPid_e738bcb66505a9c0cf00868e569e9026";
[Ignore]
[TestMethod]
public void DoMobileCheckout()
{
var phoneNumber = "+254720000001";
var productName = "coolproduct";
var currency = "KES";
decimal amount = 1000M;
var providerChannel = "mychannel";
var metadata = new Dictionary<string, string>
{
{"dest","oracle"}
};
C2BDataResults checkoutResponse = _atGWInstance.Checkout(productName, phoneNumber, currency, amount, providerChannel, metadata);
var success = checkoutResponse.Status =="PendingConfirmation";
TestId = checkoutResponse.TransactionId;
Assert.IsTrue(success, "Should successfully send Mobile Checkout prompt");
}
[Ignore]
[TestMethod]
public void DoBusinessToClientTransaction()
{
const string rec1PhoneNum = "+254720000004";
const string rec2PhoneNum = "+254720000005";
const string productName = "awesomeproduct";
const string rec1Name = "Mr. Smith";
const string rec2Name = "Seraph";
const string currency = "KES";
const decimal rec1Amount = 2000M;
const decimal rec2Amount = 8050M;
var rec1 = new MobileB2CRecepient(rec1Name, rec1PhoneNum, currency, rec1Amount);
rec1.AddMetadata("reason","New Glasses");
var rec2 = new MobileB2CRecepient(rec2Name, rec2PhoneNum, currency, rec2Amount);
rec2.AddMetadata("reason", "Gift from the Oracle");
IList<MobileB2CRecepient> recepients = new List<MobileB2CRecepient>
{
rec1,
rec2
};
DataResult b2cresponse = _atGWInstance.MobileB2C(productName, recepients);
var success = b2cresponse.NumQueued == 2;
Assert.IsTrue(success, "Should successfully disburse B2C transactions to valid phone numbers");
}
[Ignore]
[TestMethod]
public void DoBusinessToBusinessTransaction()
{
const string originProduct = "awesomeproduct";
const string destProduct = "coolproduct";
const decimal amount = 200;
const string destChannel = "mychannel";
const string providerChannel = "Athena";
const string currency = "KES";
dynamic metadata = new JObject();
metadata.originator = "Oracle";
metadata.usage = "simulation";
const string transferType = "BusinessToBusinessTransfer";
B2BResult response = _atGWInstance.MobileB2B(originProduct, providerChannel, transferType, currency, amount, destChannel, destProduct, metadata);
var success = response.Status == "Queued";
Assert.IsTrue(success);
}
[Ignore]
[TestMethod]
public void DoBankCheckout()
{
const string otp = "1234";
string transId = "id";
var productName = "coolproduct";
var accountName = "Fela Kuti";
var accountNumber = "1234567890";
var bankCode = 234001;
var currencyCode = "NGN";
var amount = 1000.5M;
var dob = "2017-11-22";
var metadata = new Dictionary<string, string> { { "Reason", "Do something cool" } };
var narration = "We're buying something cool";
var receBank = new BankAccount(accountNumber, bankCode, dob, accountName);
BankCheckoutResponse getTransactionId = _atGWInstance.BankCheckout(productName, receBank, currencyCode, amount, narration, metadata);
transId = getTransactionId.TransactionId;
var validateTransaction = _atGWInstance.OtpValidate(transId, otp);
validateTransaction = JsonConvert.DeserializeObject(validateTransaction);
var success = validateTransaction["status"] == "Success";
Assert.IsTrue(success, "Should succcessfully process bank checkout");
}
[Ignore]
[TestMethod]
public void DoBankTransfer()
{
const string productname = "coolproduct";
var currency_code = "NGN";
var recipient1_account_name = "Alyssa Hacker";
var recipient1_account_number = "1234567890";
var recipient1_bank_code = 234001;
decimal recipient1_amount = 1500.50M;
var recipient1_narration = "December Bonus";
var recipient2_account_name = "Ben BitDiddle";
var recipient2_account_number = "234567891";
var recipient2_bank_code = 234004;
decimal recipient2_amount = 1500.50M;
var recipient2_narration = "November Bonus";
var recepient1_account = new BankAccount(recipient1_account_number, recipient1_bank_code, recipient1_account_name);
var recepient1 = new BankTransferRecipients(recipient1_amount, recepient1_account, currency_code, recipient1_narration);
recepient1.AddMetadata("Reason", "Early Bonus");
var recipient2_account = new BankAccount(recipient2_account_number, recipient2_bank_code, recipient2_account_name);
var recipient2 = new BankTransferRecipients(recipient2_amount, recipient2_account, currency_code, recipient2_narration);
recipient2.AddMetadata("Reason", "Big Wins");
IList<BankTransferRecipients> recipients = new List<BankTransferRecipients>
{
recepient1,
recipient2
};
BankTransferResults bankTransferResults = _atGWInstance.BankTransfer(productname, recipients);
var success = (bankTransferResults.Entries.Count == 2 ); // Number of recipinets is 2.
Assert.IsTrue(success, "Should succesfully transfer monies between bank accounts");
}
[Ignore]
[TestMethod]
public void DoCardCheckout()
{
const string Otp = "1234";
var transactionId = "id";
const string ProductName = "awesomeproduct";
const string CurrencyCode = "NGN";
const decimal Amount = 7500.50M;
const string Narration = "Buy Aluku Records";
var metadata = new Dictionary<string, string>
{
{ "Parent Company", "Offering Records" },
{ "C.E.O", "Boddhi Satva" }
};
const short CardCvv = 123;
const string CardNum = "123456789012345";
const string CountryCode = "NG";
const string CardPin = "1234";
const int ValidTillMonth = 9;
const int ValidTillYear = 2019;
var cardDetails = new PaymentCard(CardPin, CountryCode, CardCvv, ValidTillMonth, ValidTillYear, CardNum);
CardCheckoutResults checkout = _atGWInstance.CardCheckout(
ProductName,
cardDetails,
CurrencyCode,
Amount,
Narration,
metadata);
transactionId = checkout.TransactionId;
var validate = _atGWInstance.ValidateCardOtp(transactionId, Otp);
var res = JsonConvert.DeserializeObject(validate);
var success = res["status"] == "Success" && checkout.Status == "PendingValidation";
Assert.IsTrue(success, "Should succesfully complete a Card checkout transaction");
}
[Ignore]
[TestMethod]
public void DoWalletTransfer()
{
const int productCode = 1234;
const string productName = "coolproduct";
decimal amount = 150M;
string currencyCode = "KES";
Dictionary<string, string> metadata = new Dictionary<string, string>
{
{"mode" , "transfer"}
};
StashResponse stashResponse = _atGWInstance.WalletTransfer(productName, productCode, currencyCode, amount, metadata);
var success = stashResponse.Status == "Success";
Assert.IsTrue(success, "Should transfer amounts between wallets");
}
[Ignore]
[TestMethod]
public void DoTopupStash()
{
const string productName = "coolproduct";
decimal amount = 150M;
string currencyCode = "KES";
Dictionary <string, string> metadata = new Dictionary<string, string> {
{"what this is","cool stuff"}
};
StashResponse stashResponse = _atGWInstance.TopupStash(productName, currencyCode, amount, metadata);
var success = stashResponse.Status == "Success";
Assert.IsTrue(success, "Should successfully topup product stash");
}
[Ignore]
[TestMethod]
public void DoFindTransaction()
{
string transactionIdResponse = _atGWInstance.FindTransaction(TestId);
JObject transactionIdResponseJson = JObject.Parse(transactionIdResponse);
var status = transactionIdResponseJson.GetValue("status");
var success = (status.ToString() == "Success");
Assert.IsTrue(success, "Should successfully find a transaction given it's ID");
}
[Ignore]
[TestMethod]
public void DoFetchProductTransactions()
{
const string productName = "coolproduct";
const string pageNumber = "1";
const string count = "3";
string fetchTransactionsResponse = _atGWInstance.FetchProductTransactions(productName, pageNumber,count);
JObject fetchTransactionsResponseJson = JObject.Parse(fetchTransactionsResponse);
var fetchTransactionsResponseStatus = fetchTransactionsResponseJson.GetValue("status");
var success = (fetchTransactionsResponseStatus.ToString() == "Success");
Assert.IsTrue(success, "Should successfully fetch transactions with default params");
}
[Ignore]
[TestMethod]
public void DoFetchProductTransactionsByDateDate()
{
const string productName = "coolproduct";
const string pageNumber = "1";
const string count = "3";
DateTime today = DateTime.Today;
string startDate = today.ToString("yyyy-MM-dd");
string endDate = today.ToString("yyyy-MM-dd");
string fetchTransactionsResponse = _atGWInstance.FetchProductTransactions(productName, pageNumber,count, startDate, endDate);
JObject fetchTransactionsResponseJson = JObject.Parse(fetchTransactionsResponse);
var fetchTransactionsResponseStatus = fetchTransactionsResponseJson.GetValue("status");
var success = (fetchTransactionsResponseStatus.ToString() == "Success");
Assert.IsTrue(success, "Should successfully fetch transactions based on given date");
}
[Ignore]
[TestMethod]
public void DoFetchProductTransactionByCategory()
{
const string productName = "coolproduct";
const string pageNumber = "1";
const string count = "3";
const string category = "MobileCheckout";
string fetchTransactionsResponse = _atGWInstance.FetchProductTransactions(productName, pageNumber,count, category);
JObject fetchTransactionsResponseJson = JObject.Parse(fetchTransactionsResponse);
var fetchTransactionsResponseStatus = fetchTransactionsResponseJson.GetValue("status");
var success = (fetchTransactionsResponseStatus.ToString() == "Success");
Assert.IsTrue(success, "Should successfully fetch transactions based on category");
}
[Ignore]
[TestMethod]
public void DoFetchWalletTransactions()
{
const string pageNumber = "1";
const string count = "3";
string fetchTransactionsResponse = _atGWInstance.FetchWalletTransactions(pageNumber,count);
JObject fetchTransactionsResponseJson = JObject.Parse(fetchTransactionsResponse);
var fetchTransactionsResponseStatus = fetchTransactionsResponseJson.GetValue("status");
var success = (fetchTransactionsResponseStatus.ToString() == "Success");
Assert.IsTrue(success, "Should successfully fetch wallet transactions with default params");
}
[Ignore]
[TestMethod]
public void DoFetchWalletTransactionsByDate()
{
const string pageNumber = "1";
const string count = "3";
DateTime today = DateTime.Today;
string startDate = today.ToString("yyyy-MM-dd");
string endDate = today.ToString("yyyy-MM-dd");
string fetchTransactionsResponse = _atGWInstance.FetchWalletTransactions(pageNumber,count, startDate, endDate);
JObject fetchTransactionsResponseJson = JObject.Parse(fetchTransactionsResponse);
var fetchTransactionsResponseStatus = fetchTransactionsResponseJson.GetValue("status");
var success = (fetchTransactionsResponseStatus.ToString() == "Success");
Assert.IsTrue(success, "Should successfully fetch wallet transactions by date");
}
[TestMethod]
public void DoFetchWalletBalance()
{
string fetchBalanceResponse = _atGWInstance.FetchWalletBalance();
JObject fetchBalanceResponseJson = JObject.Parse(fetchBalanceResponse);
var fetchBalanceResponseStatus = fetchBalanceResponseJson.GetValue("status");
var success = (fetchBalanceResponseStatus.ToString() == "Success");
Assert.IsTrue(success, "Should successfully fetch wallet balance");
}
}
}
| |
//
// System.Web.UI.WebControls.PagerSettings.cs
//
// Authors:
// Lluis Sanchez Gual (lluis@novell.com)
//
// (C) 2005 Novell, Inc (http://www.novell.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.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
#if NET_2_0
using System.ComponentModel;
using System.Security.Permissions;
namespace System.Web.UI.WebControls
{
[TypeConverterAttribute (typeof(ExpandableObjectConverter))]
[AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public sealed class PagerSettings: IStateManager
{
StateBag ViewState = new StateBag ();
Control ctrl;
public PagerSettings ()
{
}
internal PagerSettings (Control ctrl)
{
this.ctrl = ctrl;
}
[WebCategoryAttribute ("Appearance")]
[NotifyParentPropertyAttribute (true)]
[UrlPropertyAttribute]
[DefaultValueAttribute ("")]
[EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public string FirstPageImageUrl {
get {
object ob = ViewState ["FirstPageImageUrl"];
if (ob != null) return (string) ob;
return string.Empty;
}
set {
ViewState ["FirstPageImageUrl"] = value;
}
}
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute ("<<")]
[NotifyParentPropertyAttribute (true)]
public string FirstPageText {
get {
object ob = ViewState ["FirstPageText"];
if (ob != null) return (string) ob;
return "<<";
}
set {
ViewState ["FirstPageText"] = value;
}
}
[WebCategoryAttribute ("Appearance")]
[NotifyParentPropertyAttribute (true)]
[UrlPropertyAttribute]
[DefaultValueAttribute ("")]
[EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public string LastPageImageUrl {
get {
object ob = ViewState ["LastPageImageUrl"];
if (ob != null) return (string) ob;
return string.Empty;
}
set {
ViewState ["LastPageImageUrl"] = value;
}
}
[NotifyParentPropertyAttribute (true)]
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute (">>")]
public string LastPageText {
get {
object ob = ViewState ["LastPageText"];
if (ob != null) return (string) ob;
return ">>";
}
set {
ViewState ["LastPageText"] = value;
}
}
[NotifyParentPropertyAttribute (true)]
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute (PagerButtons.Numeric)]
public PagerButtons Mode {
get {
object ob = ViewState ["Mode"];
if (ob != null) return (PagerButtons) ob;
return PagerButtons.Numeric;
}
set {
ViewState ["Mode"] = value;
}
}
[WebCategoryAttribute ("Appearance")]
[NotifyParentPropertyAttribute (true)]
[UrlPropertyAttribute]
[DefaultValueAttribute ("")]
[EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public string NextPageImageUrl {
get {
object ob = ViewState ["NextPageImageUrl"];
if (ob != null) return (string) ob;
return string.Empty;
}
set {
ViewState ["NextPageImageUrl"] = value;
}
}
[WebCategoryAttribute ("Appearance")]
[NotifyParentPropertyAttribute (true)]
[DefaultValueAttribute (">")]
public string NextPageText {
get {
object ob = ViewState ["NextPageText"];
if (ob != null) return (string) ob;
return ">";
}
set {
ViewState ["NextPageText"] = value;
}
}
[WebCategoryAttribute ("Behavior")]
[NotifyParentPropertyAttribute (true)]
[DefaultValueAttribute (10)]
public int PageButtonCount {
get {
object ob = ViewState ["PageButtonCount"];
if (ob != null) return (int) ob;
return 10;
}
set {
ViewState ["PageButtonCount"] = value;
}
}
[WebCategoryAttribute ("Layout")]
[DefaultValueAttribute (PagerPosition.Bottom)]
[NotifyParentPropertyAttribute (true)]
public PagerPosition Position {
get {
object ob = ViewState ["Position"];
if (ob != null) return (PagerPosition) ob;
return PagerPosition.Bottom;
}
set {
ViewState ["Position"] = value;
}
}
[WebCategoryAttribute ("Appearance")]
[NotifyParentPropertyAttribute (true)]
[UrlPropertyAttribute]
[DefaultValueAttribute ("")]
[EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public string PreviousPageImageUrl {
get {
object ob = ViewState ["PreviousPageImageUrl"];
if (ob != null) return (string) ob;
return string.Empty;
}
set {
ViewState ["PreviousPageImageUrl"] = value;
}
}
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute ("<")]
[NotifyParentPropertyAttribute (true)]
public string PreviousPageText {
get {
object ob = ViewState ["PreviousPageText"];
if (ob != null) return (string) ob;
return "<";
}
set {
ViewState ["PreviousPageText"] = value;
}
}
[WebCategoryAttribute ("Appearance")]
[DefaultValueAttribute (true)]
[NotifyParentPropertyAttribute (true)]
public bool Visible {
get {
object ob = ViewState ["Visible"];
if (ob != null) return (bool) ob;
return true;
}
set {
ViewState ["Visible"] = value;
}
}
public override string ToString ()
{
return string.Empty;
}
void IStateManager.LoadViewState (object savedState)
{
ViewState.LoadViewState (savedState);
}
object IStateManager.SaveViewState ()
{
return ViewState.SaveViewState();
}
void IStateManager.TrackViewState ()
{
ViewState.TrackViewState();
}
bool IStateManager.IsTrackingViewState
{
get { return ViewState.IsTrackingViewState; }
}
internal Table CreatePagerControl (int currentPage, int pageCount)
{
Table table = new Table ();
TableRow row = new TableRow ();
table.Rows.Add (row);
if (Mode == PagerButtons.NextPrevious || Mode == PagerButtons.NextPreviousFirstLast)
{
if (currentPage > 0) {
if (Mode == PagerButtons.NextPreviousFirstLast)
row.Cells.Add (CreateCell (FirstPageText, FirstPageImageUrl, "Page", "First"));
row.Cells.Add (CreateCell (PreviousPageText, PreviousPageImageUrl, "Page", "Prev"));
}
if (currentPage < pageCount - 1) {
row.Cells.Add (CreateCell (NextPageText, NextPageImageUrl, "Page", "Next"));
if (Mode == PagerButtons.NextPreviousFirstLast)
row.Cells.Add (CreateCell (LastPageText, LastPageImageUrl, "Page", "Last"));
}
}
else if (Mode == PagerButtons.Numeric || Mode == PagerButtons.NumericFirstLast)
{
int first = currentPage / PageButtonCount;
int last = first + PageButtonCount;
if (last >= pageCount) last = pageCount;
if (first > 0) {
if (Mode == PagerButtons.NumericFirstLast)
row.Cells.Add (CreateCell (FirstPageText, FirstPageImageUrl, "Page", "First"));
row.Cells.Add (CreateCell (PreviousPageText, PreviousPageImageUrl, "Page", "Prev"));
}
for (int n = first; n < last; n++)
row.Cells.Add (CreateCell ((n+1).ToString(), string.Empty, (n != currentPage) ? "Page" : "", (n+1).ToString()));
if (last < pageCount - 1) {
row.Cells.Add (CreateCell (NextPageText, NextPageImageUrl, "Page", "Next"));
if (Mode == PagerButtons.NumericFirstLast)
row.Cells.Add (CreateCell (LastPageText, LastPageImageUrl, "Page", "Last"));
}
}
return table;
}
TableCell CreateCell (string text, string image, string command, string argument)
{
TableCell cell = new TableCell ();
cell.Controls.Add (new DataControlButton (ctrl, text, image, command, argument, true));
return cell;
}
}
}
#endif
| |
" NAME CaseStatement
AUTHOR cgreuter@calum.csclub.uwaterloo.ca (Chris Reuter)
URL (none)
FUNCTION Control structure similar to C's switch/case construct.
KEYWORDS case switch
ST-VERSIONS Squeak
PREREQUISITES (none)
CONFLICTS (none known)
DISTRIBUTION world
VERSION 0.0.1
DATE 03-Sep-98
SUMMARY
This is my trivial Squeak port of Paul Bauman'scase statements as published in the July/August1997 issue of The Smalltalk Report.It seems to work correctly, but your mileagemay vary. If you do find and fix a bug, pleasesend me a copy of the changes.See the class comment for documentation.
Chris Reuter
"!
'From Squeak 2.0 of May 22, 1998 on 17 July 1998 at 7:34:18 pm'!
Object subclass: #Case
instanceVariableNames: 'satisfied response criterion '
classVariableNames: ''
poolDictionaries: ''
category: 'Case Statement'!
!Object methodsFor: 'case statement'!
switch
"Answer a new instance of Case with the receiver as the
criterion to test against."
^Case for: self! !
!Case commentStamp: 'cgr 7/17/1998 19:34' prior: 0!
Case class add a robust case statement implementation to Smalltalk. The implemenation does NOT require any
compiler changes. The code is from the article, "Smalltalk Case Statements" by Paul Baumann in the July/August
1997 issue of The Smalltalk Report. Baumann's article illustrates the ease of providing support for a case
statement, gives examples of their use, and explains why the example case statement is appropiate. Comments
taken from Baumann's article on the factors of when using a case statement is good. These factors are:
(a) tests must be performed in sequence;
(b) the conditional test is complex;
(c) the test conditions are not consistent;
(d) the criterion isn't easily represented by the application classes;
(e) the test conditions depend on state of the criterion rather than the class or behavior of the criterion;
(f) ease of maintenance is more important than performance;
(g) there are more than three possible results.
Various class examples illustrate some factor or factors as stated by Baumann.
InstanceVariables:
satisfied <Boolean | nil >
response <Object> result of execBlock value where execBlock is from one of the following:
caseIs: testObject then: execBlock
caseIsAny: testCollection then: execBlock
isFalse: testBlock then: execBlock
isTrue: testBlock then: execBlock
default: execBlock
criterion <Object> for which an instance of Case was made. Case class >> for: anObject
which is sent by Object >> switch
ClassVariables: NONE
!
!Case methodsFor: 'public'!
case: oneArgTestBlock process: execBlock
"Idential to #case:then: except that the receiver
will not be satisfied, and processing will fall
through to the next statement."
self isSatisfied ifFalse: [
(oneArgTestBlock value: criterion) ifTrue: [
self response: execBlock value.
satisfied := false.
].
].
^self response! !
!Case methodsFor: 'public'!
case: oneArgTestBlock then: execBlock
"oneArgTestBlock must return a boolean value
when passed the criterion of the receiver."
self isSatisfied ifFalse: [
(oneArgTestBlock value: criterion) ifTrue: [
self response: execBlock value.
satisfied := true.
].
].
^self response! !
!Case methodsFor: 'public'!
caseIs: testObject process: execBlock
"Idential to #caseIs:then: except that the receiver
will not be satisfied, and processing will fall
through to the next statement."
^self
case: [:caseCriterion| caseCriterion = testObject ]
process: execBlock! !
!Case methodsFor: 'public'!
caseIs: testObject then: execBlock
"If testObject equals the criterion of the
receiver, then satisfy the receiver and
answer the value of execBlock."
^self
case: [:caseCriterion| caseCriterion = testObject ]
then: execBlock! !
!Case methodsFor: 'public'!
caseIsAny: testCollection process: execBlock
"Idential to #caseIsAny:then: except that the receiver
will not be satisfied, and processing will fall
through to the next statement."
^self
case: [:caseCriterion| testCollection includes: caseCriterion ]
process: execBlock! !
!Case methodsFor: 'public'!
caseIsAny: testCollection then: execBlock
"If testCollection includes the criterion of the
receiver, then satisfy the receiver and
answer the value of execBlock."
^self
case: [:caseCriterion| testCollection includes: caseCriterion ]
then: execBlock! !
!Case methodsFor: 'public'!
default: execBlock
"This method sets the response without signaling
the receiver has been satisfied. Note that the value
of satisfied can be nil, true, or false; and that only
a value of nil indicates that no case was run."
satisfied isNil ifTrue: [self response: execBlock value].
^self response! !
!Case methodsFor: 'public'!
isFalse: testBlock process: execBlock
"Idential to #isFalse:then: except that the receiver
will not be satisfied, and processing will fall
through to the next statement."
^self
case: [:caseCriterion| testBlock value not ]
process: execBlock! !
!Case methodsFor: 'public'!
isFalse: testBlock then: execBlock
"testBlock is a zero argument block that when
evaluates false, execBlock will be executed.
The criterion of the receiver is ignored."
^self
case: [:caseCriterion| testBlock value not ]
then: execBlock! !
!Case methodsFor: 'public'!
isTrue: testBlock process: execBlock
"Idential to #isTrue:then: except that the receiver
will not be satisfied, and processing will fall
through to the next statement."
^self
case: [:caseCriterion| testBlock value ]
process: execBlock! !
!Case methodsFor: 'public'!
isTrue: testBlock then: execBlock
"testBlock is a zero argument block that when
evaluates true, execBlock will be executed.
The criterion of the receiver is ignored."
^self
case: [:caseCriterion| testBlock value ]
then: execBlock! !
!Case methodsFor: 'private'!
criterion: anObject
"Set the standard of judging a true case."
criterion := anObject! !
!Case methodsFor: 'private'!
isSatisfied
"satisfied may be nil, false, or true."
^satisfied == true! !
!Case methodsFor: 'private'!
response
"Answer the last response for a processed
selection, or nil if no selections were processed."
^response! !
!Case methodsFor: 'private'!
response: newResponse
"Set the value that will be returned for
the receiver."
response := newResponse! !
!Case class methodsFor: 'documentation'!
aaClassComment
"Class comment located here so it does not get lost when filed in to Digitalk Smalltalk.
Case class add a robust case statement implementation to Smalltalk. The implemenation does NOT require any complier changes. The code is from the article, 'Smalltalk Case Statements' by Paul Baumann in the July/August 1997 issue of The Smalltalk Report. Baumann's article illustrates the ease of providing support for a case statement, gives examples of their use, and explains why the example case statement is appropiate. Comments taken from Baumann's article on the factors of when using a case statement is good. These factors are:
(a) tests must be performed in sequence;
(b) the conditional test is complex;
(c) the test conditions are not consistent;
(d) the criterioan isn't easily represented by the application classes;
(e) the test conditions depend on state of the criterion reather than the class or behavior of the criterion;
(f) ease of maintenance is more important than performance;
(g) there are more than three possible results.
Various class examples illustrate some factor or factors as stated by Baumann.
InstanceVariables:
satisfied <Boolean | nil >
response <Object> result of execBlock value where execBlock is from one of the following:
caseIs: testObject then: execBlock
caseIsAny: testCollection then: execBlock
isFalse: testBlock then: execBlock
isTrue: testBlock then: execBlock
default: execBlock
criterion <Object> for which an instance of Case was made using
Case class >> for: anObject which is send by Object >> switch
ClassVariables: NONE
"! !
!Case class methodsFor: 'documentation'!
programersGuide
"
A simple example is given in #vendLargestAvailableCurrency: unVendedCurrenyValue
The first part of the method after comments is:
| hasHundred hasFifty hasTwenty hasTen |
hasHundred := true. hasFifty := true. hasTwenty := true. hasTen := true.
^unVendedCurrenyValue switch
. . . cascaded case keyword messages . . .
The activation of the Case statements is via the unary message #switch. #switch creates an instance of Case with the receiver (unVendedCurrenyValue) stored in the instance variable, criterion. The cascaded case keyword messages are then send to the instance of Case. The method is exited when the first #case: block that is 'satisfied' after processing the #then: block. If no case: blocks were satisfied then the default: block is executed.
See Case instance protocol 'public' for the available types of Case keyword messages. The meanings of Case keyword and arguments are as follows:
default: aBlock - where aBlock is a zero argument block which is executed if none of the preceeding case statements criterion tests were satisified.
A then: keyword means exit the case cascade after evaluating execBlock.
A process: keyword means evaluate the execBlock and continue with the next case statement.
oneArgTestBlock - a one argument block which will be sent the value of criterion when evaluated.
Block MUST answer a boolean indicating the result of the test.
execBlock - a zero argument block to evaluate when the criterion test result is true (satisfied).
testObject - test the testObject equal (=) the criterion.
testCollection - A collection of obects which the criterion must be equal(=) to one of them.
testBlock - a one argument block that must answer a boolean. The criterion is send to testBlock.
Case Statements that will test against the criterion.
case: oneArgTestBlock then: execBlock
case: oneArgTestBlock process: execBlock
caseIs: testObject then: execBlock
caseIs: testObject process: execBlock
caseIsAny: testCollection then: execBlock
caseIsAny: testCollection process: execBlock
For #caseIs: testObject, testObject is tested to be equal the criterion.
For #caseIsAny: testCollection, testCollection includes: criterion
Case Statements that will NOT test against the criterion.
isFalse: testBlock then: execBlock
isFalse: testBlock process: execBlock
isTrue: testBlock then: execBlock
isTrue: testBlock process: execBlock
Argument testBlock is a zero argument block that must evaluate to a boolean.
"! !
!Case class methodsFor: 'examples'!
enumerationTest: anInteger
"Answer true if anInteger is included in collection else answer false.
This can be combined with other caseIsAny:then: and case:then: statements to test aValue to be one of a combination of discrete values or passed any of several range tests."
"Case enumerationTest: 6."
"Case enumerationTest: 10."
^anInteger switch
caseIsAny: #( 1 3 6 12 16) then: [ true ];
default: [ false ].! !
!Case class methodsFor: 'examples'!
vendLargestAvailableCurrency: unVendedCurrenyValue
"Similiar to Baumann's MoneyVendor>>vendLargestAvailableCurrency but modified to not require
additional classes or new methods. "
"Case vendLargestAvailableCurrency: 5"
"Case vendLargestAvailableCurrency: 50"
"Case vendLargestAvailableCurrency: 500"
| hasHundred hasFifty hasTwenty hasTen |
hasHundred := true. hasFifty := true. hasTwenty := true. hasTen := true.
^unVendedCurrenyValue switch
case: [:value | value >= 100 and: [hasHundred]]
then: ['vend hundred'];
case: [:value | value >= 50 and: [hasFifty]]
then: ['vend fifty'];
case: [:value | value >= 20 and: [hasTwenty]]
then: ['vend twenty'];
case: [:value | value >= 10 and: [hasTen]]
then: ['vend ten'];
default: ['raise out of cash signal']! !
!Case class methodsFor: 'instance creation'!
for: anObject
^self new criterion: anObject! !
| |
#define STRATUS_TRACE
#if STRATUS_TRACE
using System;
using System.Diagnostics;
using System.Text;
using UnityEngine;
namespace Stratus
{
/// <summary>
/// Provides debugging facilities
/// </summary>
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoad]
#endif
public static class StratusDebug
{
//------------------------------------------------------------------------/
// Properties
//------------------------------------------------------------------------/
/// <summary>
/// Whether logging is currently enabled
/// </summary>
public static bool logging = true;
/// <summary>
/// Whether time stamps are enabled
/// </summary>
public static bool timeStamp = true;
/// <summary>
/// If true, will notify subscribes to <see cref="onLog"/> of logging callbacks
/// </summary>
public static bool invokeLogEvent = false;
/// <summary>
/// The color of the time stamp
/// </summary>
public static Color timestampLabelColor => _timestampLabelColor.Value;
private static readonly Lazy<Color> _timestampLabelColor = new Lazy<Color>(() => isProSkin ? Color.green.ScaleSaturation(0.5f) : Color.green);
/// <summary>
/// The color used of the GameObject of the class being called
/// </summary>
public static Color gameObjectLabelColor => _gameObjectLabelColor.Value;
private static readonly Lazy<Color> _gameObjectLabelColor = new Lazy<Color>(() => isProSkin ? StratusGUIStyles.Colors.azureTriad.first.ScaleSaturation(0.5f) : StratusGUIStyles.Colors.azureTriad.first);
/// <summary>
/// The color of the class the function being called belongs to
/// </summary>
public static Color classLabelColor => _classLabelColor.Value;
private static readonly Lazy<Color> _classLabelColor = new Lazy<Color>(() => isProSkin ? StratusGUIStyles.Colors.azureTriad.second.ScaleSaturation(0.5f) : StratusGUIStyles.Colors.azureTriad.second);
/// <summary>
/// The color of the function being called
/// </summary>
public static Color methodLabelColor => _methodLabelColor.Value;
private static readonly Lazy<Color> _methodLabelColor = new Lazy<Color>(() => isProSkin ? StratusGUIStyles.Colors.azureTriad.third.ScaleSaturation(0.5f) : StratusGUIStyles.Colors.azureTriad.third);
/// <summary>
/// Whether this is running as a player executable rather than in the editor
/// </summary>
public static bool isPlayer => !Application.isEditor;
/// <summary>
/// Whether the user is using the pro skin (dark thene)
/// </summary>
public static bool isProSkin
{
get
{
#if UNITY_EDITOR
return UnityEditor.EditorGUIUtility.isProSkin;
#else
return false;
#endif
}
}
/// <summary>
/// Whether to log the timestamp
/// </summary>
public static bool logTimestamp => Application.isPlaying ? timeStamp : false;
/// <summary>
/// The singular string builder used for logging
/// </summary>
private static StringBuilder builder = new StringBuilder();
//------------------------------------------------------------------------/
// Events
//------------------------------------------------------------------------/
/// <summary>
/// If event handling is enabled, notifies subscribers whenever logging is done through this class
/// </summary>
public static event Action<string, LogType> onLog;
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
/// <summary>
/// Logs the given message of the given type to the console
/// </summary>
public static void Log(object message, LogType logType, object source = null, int frame = 1)
{
if (!logging || isPlayer)
{
return;
}
StackTrace stackTrace = new StackTrace();
builder.Clear();
// If timestamp is enabled, prefix the current time
if (logTimestamp)
{
builder.Append(ComposeTimestamp());
}
// If there's a provided component reference, get the name of its owner gameobject
if (source != null)
{
builder.Append(ComposeSourcePrefix(source));
}
// Get the name of the method and class that called this
builder.Append(ComposeLogPrefix(stackTrace, frame));
// Append the message
builder.Append(message);
// Now output it to the aporopiate Unity log function
string output = builder.ToString();
if (invokeLogEvent)
{
onLog?.Invoke(output, logType);
}
switch (logType)
{
case LogType.Log:
UnityEngine.Debug.Log(output, source as UnityEngine.Object);
break;
case LogType.Error:
UnityEngine.Debug.LogError(output, source as UnityEngine.Object);
break;
case LogType.Assert:
UnityEngine.Debug.LogAssertion(output, source as UnityEngine.Object);
break;
case LogType.Warning:
UnityEngine.Debug.LogWarning(output, source as UnityEngine.Object);
break;
case LogType.Exception:
throw new NotSupportedException($"Logging exceptions is not supported by this function");
}
}
/// <summary>
/// Prints the given message to the console, prefixing it with the name of the method
/// and the class name. (And optionally, its owner GameObject)
/// </summary>
/// <param name="message">The message object.</param>
/// <param name="component">The component which invoked this method. </param>
/// <param name="color">The color of the message</param>
public static void Log(object message, object source = null, int frame = 1)
{
Log(message, LogType.Log, source, frame + 1);
}
/// <summary>
/// If log is true, prints the given message to the console, prefixing it with the name of the method
/// and the class name. (And optionally, its owner GameObject)
/// </summary>
/// <param name="log"></param>
/// <param name="message"></param>
/// <param name="source"></param>
/// <param name="frame"></param>
public static void LogIf(bool log, object message, object source = null, int frame = 1)
{
if (log)
{
Log(message, source, frame + 1);
}
}
/// <summary>
/// Prints the given message, prefixing it with the name of the method
/// and the class name. (And optionally, its owner GameObject)
/// </summary>
/// <param name="message">The message object.</param>
/// <param name="component">The component which invoked this method. </param>
/// <param name="color">The color of the message</param>
public static void LogWarning(object message, object source = null, int frame = 1)
{
Log(message, LogType.Warning, source, frame + 1);
}
/// <summary>
/// Prints the given message, prefixing it with the name of the method
/// and the class name. This is printed as an error followed by an exception.
/// </summary>
/// <param name="message">The error message.</param>
/// <param name="component">The component which invoked the method.</param>
/// <param name="throwException">Whether to throw an exception.</param>
public static void LogError(object message, object source = null, int frame = 1)
{
Log(message, LogType.Error, source, frame + 1);
}
public static void LogErrorBreak(object message, object source = null, int frame = 1)
{
LogError(message, source, frame + 1);
UnityEngine.Debug.Break();
}
/// <summary>
/// Composes the class.method prefix used by the various logging functions
/// </summary>
/// <param name="stackTrace"></param>
/// <param name="frame"></param>
/// <returns></returns>
private static string ComposeLogPrefix(StackTrace stackTrace, int frame)
{
string methodName = stackTrace.GetFrame(frame).GetMethod().Name;
string className = stackTrace.GetFrame(frame).GetMethod().ReflectedType.Name;
string classStr = Format(className, classLabelColor, FontStyle.Bold);
string methodStr = Format(methodName, methodLabelColor, FontStyle.Bold);
// Make the prefix
string prefix = $"{classStr}.{methodStr}: ";
return prefix;
}
/// <summary>
/// If the source object isn't null, composes a formatted string
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
private static string ComposeSourcePrefix(object source)
{
return $" {Format(source.ToString(), gameObjectLabelColor, FontStyle.BoldAndItalic)} ";
}
/// <summary>
/// Composes a string of text with the timestamp used by logging functions
/// </summary>
/// <returns></returns>
private static string ComposeTimestamp()
{
return Format("[" + Math.Round(Time.unscaledTime, 2) + "] ", timestampLabelColor);
}
/// <summary>
/// Displays a modal dialog in Editor
/// </summary>
/// <param name="title"></param>
/// <param name="message"></param>
/// <param name="ok"></param>
/// <param name="onOk"></param>
public static void Dialog(string title, string message, string ok = "OK", System.Action onOk = null)
{
#if UNITY_EDITOR
if (UnityEditor.EditorUtility.DisplayDialog(title, message, ok))
{
onOk?.Invoke();
}
#endif
}
/// <summary>
/// Displays a modal dialog in Editor
/// </summary>
/// <param name="title"></param>
/// <param name="message"></param>
/// <param name="ok"></param>
/// <param name="cancel"></param>
/// <param name="onOk"></param>
public static void Dialog(string title, string message, string ok, string cancel, System.Action onOk = null)
{
#if UNITY_EDITOR
if (UnityEditor.EditorUtility.DisplayDialog(title, message, ok, cancel))
{
onOk?.Invoke();
}
#endif
}
/// <summary>
/// Formats a string, applying stylying and coloring to it
/// </summary>
/// <param name="obj"></param>
/// <param name="color"></param>
/// <param name="italic"></param>
/// <returns></returns>
private static string Format(object obj, Color color, FontStyle style = FontStyle.Normal)
{
if (obj == null)
{
}
return obj.ToString().ToRichText(style, color);
}
}
}
#endif
// References:
// http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method
// http://web.archive.org/web/20130124234247/http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html
| |
// Copyright (c) Aghyad khlefawi. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Coddee.Data;
using Coddee.Exceptions;
using Coddee.Mvvm;
using Coddee.Services;
using Coddee.Services.Dialogs;
using Coddee.Validation;
namespace Coddee.WPF
{
/// <summary>
/// A base class for editors ViewModels that provide the ability to add and edit a model
/// </summary>
/// <typeparam name="TEditor">The same type of the ViewModel inheriting this class</typeparam>
/// <typeparam name="TView">The view type of the ViewModel</typeparam>
/// <typeparam name="TModel">The type of the model to be added or edited.</typeparam>
public abstract class EditorViewModelBase<TEditor, TView, TModel> : ViewModelBase<TView>,
IEditorViewModel<TView, TModel>
where TView : System.Windows.UIElement, new()
where TModel : new()
where TEditor : EditorViewModelBase<TEditor, TView, TModel>
{
private const string _eventsSource = "EditorBase";
/// <summary>
/// The fields marked with <see cref="EditorFieldAttribute"/>
/// </summary>
protected IEnumerable<EditorFieldInfo> _editorFields;
/// <inheritdoc />
protected EditorViewModelBase()
{
Saved += OnSave;
Canceled += OnCanceled;
}
/// <summary>
/// A dynamically generated action to clear the editor fields base on <see cref="EditorFieldAttribute"/>
/// </summary>
protected Action<TEditor> _clearAction;
/// <inheritdoc />
public event EventHandler<EditorSaveArgs<TModel>> Saved;
/// <inheritdoc />
public event EventHandler<EditorSaveArgs<TModel>> Canceled;
/// <inheritdoc />
public override ViewModelOptions DefaultViewModelOptions => ViewModelOptions.Editor;
private OperationType _operationType;
/// <summary>
/// The type of the operation that is currently happening in the editor.
/// </summary>
public OperationType OperationType
{
get { return _operationType; }
set { SetProperty(ref this._operationType, value); }
}
private TModel _editedItem;
/// <inheritdoc />
public TModel EditedItem
{
get { return _editedItem; }
set { SetProperty(ref this._editedItem, value); }
}
private bool _isSaving;
/// <summary>
/// Indicates whether the editor is currently performing the save operation.
/// </summary>
public bool IsSaving
{
get { return _isSaving; }
set
{
SetProperty(ref _isSaving, value);
if (_dialog != null)
{
var saveCommand = _dialog.Commands.FirstOrDefault(e => e.Tag == ActionCommandTags.SaveCommand);
if (saveCommand != null)
saveCommand.SetCanExecute(!value);
}
}
}
private bool _fillingValues;
/// <summary>
/// Indicates whether the editor is currently filling the fields from the edited object.
/// </summary>
public bool FillingValues
{
get { return _fillingValues; }
set { SetProperty(ref this._fillingValues, value); }
}
private string _title;
/// <inheritdoc />
public string Title
{
get { return _title; }
set { SetProperty(ref this._title, value); }
}
private string _fullTitle;
/// <inheritdoc />
public string FullTitle
{
get { return _fullTitle; }
set { SetProperty(ref this._fullTitle, value); }
}
/// <inheritdoc />
public virtual void Add()
{
OperationType = OperationType.Add;
Clear();
OnAdd();
FullTitle = _localization["AddTemplate"].Replace("$Name$", _localization[Title]);
}
/// <inheritdoc />
public virtual void Clear()
{
EditedItem = new TModel();
_clearAction?.Invoke((TEditor)this);
}
/// <inheritdoc />
public virtual void Edit(TModel item)
{
FillingValues = true;
OperationType = OperationType.Edit;
Clear();
FullTitle = _localization["EditTemplate"].Replace("$Name$", _localization[Title]);
EditedItem = _mapper.Map<TModel>(item);
OnEdit(item);
FillingValues = false;
}
/// <inheritdoc />
protected override async Task OnInitialization()
{
GetEditorFields();
await base.OnInitialization();
_mapper.RegisterMap<TModel, TModel>();
_mapper.RegisterTwoWayMap<TEditor, TModel>();
GenerateClearFunction();
}
/// <inheritdoc />
protected override void SetValidationRules(List<IValidationRule> validationRules)
{
base.SetValidationRules(validationRules);
foreach (var editorFieldInfo in _editorFields.Where(e => e.Attribute.IsRequired))
{
var property = Expression.Property(Expression.Constant(this), editorFieldInfo.Property.Name);
var lambda = Expression.Lambda<Func<object>>(property).Compile();
var rule = new ValidationRule(ValidationType.Error, Validators.GetValidator(editorFieldInfo.Property.PropertyType), editorFieldInfo.Property.Name, lambda);
validationRules.Add(rule);
}
}
private void GetEditorFields()
{
_editorFields = typeof(TEditor).GetProperties().Where(e => e.IsDefined(typeof(EditorFieldAttribute), true)).Select(e => new EditorFieldInfo
{
Attribute = e.GetCustomAttribute<EditorFieldAttribute>(),
Property = e
});
}
private void GenerateClearFunction()
{
if (_editorFields.Any())
{
var param = Expression.Parameter(typeof(TEditor), "e");
var expressions = new List<Expression<Action<TEditor>>>(_editorFields.Count());
foreach (var fielInfo in _editorFields)
{
Expression<Action<TEditor>> clearExpression = null;
switch (fielInfo.Property.GetCustomAttribute<EditorFieldAttribute>().ClearAction)
{
case ClearAction.Default:
// Generate default assign expression ( e=> e.Property = default(T) )
clearExpression = Expression.Lambda<Action<TEditor>>(Expression.Assign(Expression.Property(param, fielInfo.Property.Name), Expression.Default(fielInfo.Property.PropertyType)), param);
break;
case ClearAction.Clear:
// Generate call expressions ( e=>e.Clear() )
var method = fielInfo.Property.DeclaringType.GetMethod(nameof(ICollection<object>.Clear));
if (method != null)
{
clearExpression = Expression.Lambda<Action<TEditor>>(Expression.Call(Expression.Property(param, fielInfo.Property.Name), method), param);
}
break;
}
if (clearExpression != null)
expressions.Add(clearExpression);
}
// Generate block expression to call clear function for each property
// (e=> e.Property1 = default(T);
// e.Property2.Clear();
// )
var exp = Expression.Lambda<Action<TEditor>>(Expression.Block(expressions.Select(ex => Expression.Invoke(ex, param))), param);
//Compile the expression to a lambda
_clearAction = exp.Compile();
}
}
/// <summary>
/// Executed when the <see cref="Add"/> method is called
/// </summary>
protected virtual void OnAdd()
{
}
/// <summary>
/// Executed when the <see cref="Edit"/> method is called
/// </summary>
/// <param name="item">The edited item.</param>
protected virtual async Task OnEdit(TModel item)
{
await MapEditedItemToEditor(item);
}
/// <summary>
/// Map the values from the edited item to the editor fields.
/// </summary>
protected virtual Task MapEditedItemToEditor(TModel item)
{
_mapper.MapInstance(item, (TEditor)this);
return completedTask;
}
/// <summary>
/// Map the values from the editor fields to the edited item .
/// </summary>
/// <param name="item"></param>
protected virtual Task MapEditorToEditedItem(TModel item)
{
_mapper.MapInstance((TEditor)this, item);
return completedTask;
}
/// <inheritdoc />
public void Cancel()
{
Canceled?.Invoke(this, new EditorSaveArgs<TModel>(OperationType, EditedItem));
}
/// <summary>
/// Called perform the edited item is sent to the repository.
/// </summary>
public virtual async Task PreSave()
{
await MapEditorToEditedItem(EditedItem);
}
/// <inheritdoc />
public virtual async Task Save()
{
try
{
IsBusy = true;
IsSaving = true;
//Validation
var validationResult = Validate();
if (validationResult != null && !validationResult.IsValid)
{
if (ViewModelOptions.ShowErrors)
{
ShowErrors(validationResult);
}
IsBusy = false;
throw new ValidationException(validationResult);
}
await PreSave();
var result = await SaveItem();
Saved?.Invoke(this, new EditorSaveArgs<TModel>(OperationType, result));
IsBusy = false;
IsSaving = false;
}
catch (ValidationException)
{
IsBusy = false;
IsSaving = false;
throw;
}
catch (Exception ex)
{
_logger?.Log(_eventsSource, ex);
IsBusy = false;
IsSaving = false;
throw;
}
}
/// <summary>
/// Performs the save to the data store.
/// </summary>
/// <returns></returns>
protected virtual Task<TModel> SaveItem()
{
return Task.FromResult(EditedItem);
}
/// <summary>
/// Display the errors to the user.
/// </summary>
/// <param name="res">The last validation result</param>
protected virtual void ShowErrors(ValidationResult res)
{
res.Errors.ForEach(e => _toast.ShowToast(e, ToastType.Error));
res.Warnings.ForEach(e => _toast.ShowToast(e, ToastType.Warning));
}
/// <summary>
/// Called after the <see cref="Save"/> method is called.
/// </summary>
public virtual void OnSave(object sender, EditorSaveArgs<TModel> e)
{
}
/// <summary>
/// Called after the <see cref="Cancel"/> method is called.
/// </summary>
public virtual void OnCanceled(object sender, EditorSaveArgs<TModel> e)
{
}
private IDialog _dialog;
/// <inheritdoc />
public virtual void Show()
{
if (_dialog == null)
_dialog = _dialogService.CreateDialog(Title, (IEditorViewModel)this);
_dialog.Show();
}
}
/// <summary>
/// A base class for editors ViewModels that provide the ability to add and edit a model
/// </summary>
/// <typeparam name="TEditor">The same type of the ViewModel inheriting this class</typeparam>
/// <typeparam name="TView">The view type of the ViewModel</typeparam>
/// <typeparam name="TModel">The type of the model to be added or edited.</typeparam>
/// <typeparam name="TRepository">The <see cref="IRepository"/> that the editor will send the item to.</typeparam>
/// <typeparam name="TKey">The key type of the model.</typeparam>
public abstract class EditorViewModelBase<TEditor, TView, TRepository, TModel, TKey> : EditorViewModelBase<TEditor, TView, TModel>
where TView : System.Windows.UIElement, new()
where TModel : class, IUniqueObject<TKey>, new()
where TRepository : class, ICRUDRepository<TModel, TKey>
where TEditor : EditorViewModelBase<TEditor, TView, TModel>
{
/// <summary>
/// The model repository.
/// </summary>
protected TRepository _repository;
/// <inheritdoc />
protected override async Task OnInitialization()
{
await base.OnInitialization();
_repository = GetRepository<TRepository>();
}
/// <inheritdoc />
protected override async Task<TModel> SaveItem()
{
return await _repository.Update(OperationType, EditedItem);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class ImportingMember : ImportingItem
{
private readonly ReflectionWritableMember _member;
public ImportingMember(ContractBasedImportDefinition definition, ReflectionWritableMember member, ImportType importType)
: base(definition, importType)
{
if (member == null)
{
throw new ArgumentNullException(nameof(member));
}
_member = member;
}
public void SetExportedValue(object instance, object value)
{
if (RequiresCollectionNormalization())
{
SetCollectionMemberValue(instance, (IEnumerable)value);
}
else
{
SetSingleMemberValue(instance, value);
}
}
private bool RequiresCollectionNormalization()
{
if (Definition.Cardinality != ImportCardinality.ZeroOrMore)
{ // If we're not looking at a collection import, then don't
// 'normalize' the collection.
return false;
}
if (_member.CanWrite && ImportType.IsAssignableCollectionType)
{ // If we can simply replace the entire value of the property/field, then
// we don't need to 'normalize' the collection.
return false;
}
return true;
}
private void SetSingleMemberValue(object instance, object value)
{
EnsureWritable();
try
{
_member.SetValue(instance, value);
}
catch (TargetInvocationException exception)
{ // Member threw an exception. Avoid letting this
// leak out as a 'raw' unhandled exception, instead,
// we'll add some context and rethrow.
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportThrewException,
_member.GetDisplayName()),
Definition.ToElement(),
exception.InnerException);
}
catch (TargetParameterCountException exception)
{
// Exception was a TargetParameterCountException this occurs when we try to set an Indexer that has an Import
// this is not supported in MEF currently. Ideally we would validate against it, however, we already shipped
// so we will turn it into a ComposablePartException instead, that they should already be prepared for
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ImportNotValidOnIndexers,
_member.GetDisplayName()),
Definition.ToElement(),
exception.InnerException);
}
}
private void EnsureWritable()
{
if (!_member.CanWrite)
{ // Property does not have a setter, or
// field is marked as read-only.
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportNotWritable,
_member.GetDisplayName()),
Definition.ToElement());
}
}
private void SetCollectionMemberValue(object instance, IEnumerable values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
ICollection<object> collection = null;
Type itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType);
if (itemType != null)
{
collection = GetNormalizedCollection(itemType, instance);
}
EnsureCollectionIsWritable(collection);
PopulateCollection(collection, values);
}
private ICollection<object> GetNormalizedCollection(Type itemType, object instance)
{
if (itemType == null)
{
throw new ArgumentNullException(nameof(itemType));
}
object collectionObject = null;
if (_member.CanRead)
{
try
{
collectionObject = _member.GetValue(instance);
}
catch (TargetInvocationException exception)
{
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionGetThrewException,
_member.GetDisplayName()),
Definition.ToElement(),
exception.InnerException);
}
}
if (collectionObject == null)
{
ConstructorInfo constructor = ImportType.ActualType.GetConstructor(Type.EmptyTypes);
// If it contains a default public constructor create a new instance.
if (constructor != null)
{
try
{
collectionObject = constructor.SafeInvoke();
}
catch (TargetInvocationException exception)
{
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionConstructionThrewException,
_member.GetDisplayName(),
ImportType.ActualType.FullName),
Definition.ToElement(),
exception.InnerException);
}
SetSingleMemberValue(instance, collectionObject);
}
}
if (collectionObject == null)
{
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionNull,
_member.GetDisplayName()),
Definition.ToElement());
}
return CollectionServices.GetCollectionWrapper(itemType, collectionObject);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void EnsureCollectionIsWritable(ICollection<object> collection)
{
bool isReadOnly = true;
try
{
if (collection != null)
{
isReadOnly = collection.IsReadOnly;
}
}
catch (Exception exception)
{
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionIsReadOnlyThrewException,
_member.GetDisplayName(),
collection.GetType().FullName),
Definition.ToElement(),
exception);
}
if (isReadOnly)
{
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionNotWritable,
_member.GetDisplayName()),
Definition.ToElement());
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void PopulateCollection(ICollection<object> collection, IEnumerable values)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
try
{
collection.Clear();
}
catch (Exception exception)
{
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionClearThrewException,
_member.GetDisplayName(),
collection.GetType().FullName),
Definition.ToElement(),
exception);
}
foreach (object value in values)
{
try
{
collection.Add(value);
}
catch (Exception exception)
{
throw new ComposablePartException(
string.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportCollectionAddThrewException,
_member.GetDisplayName(),
collection.GetType().FullName),
Definition.ToElement(),
exception);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
{
internal class ProjectExternalErrorReporter : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2
{
internal static readonly IReadOnlyList<string> CustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Telemetry);
internal static readonly IReadOnlyList<string> CompilerDiagnosticCustomTags = ImmutableArray.Create(WellKnownDiagnosticTags.Compiler, WellKnownDiagnosticTags.Telemetry);
private readonly ProjectId _projectId;
private readonly string _errorCodePrefix;
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly ExternalErrorDiagnosticUpdateSource _diagnosticProvider;
public ProjectExternalErrorReporter(ProjectId projectId, string errorCodePrefix, IServiceProvider serviceProvider)
{
_projectId = projectId;
_errorCodePrefix = errorCodePrefix;
_workspace = serviceProvider.GetMefService<VisualStudioWorkspaceImpl>();
_diagnosticProvider = serviceProvider.GetMefService<ExternalErrorDiagnosticUpdateSource>();
Debug.Assert(_workspace != null);
Debug.Assert(_diagnosticProvider != null);
}
private bool CanHandle(string errorId)
{
// we accept all compiler diagnostics
if (errorId.StartsWith(_errorCodePrefix))
{
return true;
}
return _diagnosticProvider.SupportedDiagnosticId(_projectId, errorId);
}
public int AddNewErrors(IVsEnumExternalErrors pErrors)
{
var projectErrors = new HashSet<DiagnosticData>();
var documentErrorsMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>();
var errors = new ExternalError[1];
while (pErrors.Next(1, errors, out var fetched) == VSConstants.S_OK && fetched == 1)
{
var error = errors[0];
DiagnosticData diagnostic;
if (error.bstrFileName != null)
{
diagnostic = CreateDocumentDiagnosticItem(error);
if (diagnostic != null)
{
var diagnostics = documentErrorsMap.GetOrAdd(diagnostic.DocumentId, _ => new HashSet<DiagnosticData>());
diagnostics.Add(diagnostic);
continue;
}
projectErrors.Add(CreateProjectDiagnosticItem(error));
}
else
{
projectErrors.Add(CreateProjectDiagnosticItem(error));
}
}
_diagnosticProvider.AddNewErrors(_projectId, projectErrors, documentErrorsMap);
return VSConstants.S_OK;
}
public int ClearAllErrors()
{
_diagnosticProvider.ClearErrors(_projectId);
return VSConstants.S_OK;
}
public int GetErrors(out IVsEnumExternalErrors pErrors)
{
pErrors = null;
Debug.Fail("This is not implemented, because no one called it.");
return VSConstants.E_NOTIMPL;
}
private DiagnosticData CreateProjectDiagnosticItem(ExternalError error)
{
return GetDiagnosticData(error);
}
private DiagnosticData CreateDocumentDiagnosticItem(ExternalError error)
{
var hostProject = _workspace.GetHostProject(_projectId);
if (!hostProject.ContainsFile(error.bstrFileName))
{
return null;
}
var hostDocument = hostProject.GetCurrentDocumentFromPath(error.bstrFileName);
var line = error.iLine;
var column = error.iCol;
var containedDocument = hostDocument as ContainedDocument;
if (containedDocument != null)
{
var span = new VsTextSpan
{
iStartLine = line,
iStartIndex = column,
iEndLine = line,
iEndIndex = column,
};
var spans = new VsTextSpan[1];
Marshal.ThrowExceptionForHR(containedDocument.ContainedLanguage.BufferCoordinator.MapPrimaryToSecondarySpan(
span,
spans));
line = spans[0].iStartLine;
column = spans[0].iStartIndex;
}
return GetDiagnosticData(error, hostDocument.Id, line, column);
}
public int ReportError(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")]VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName)
{
ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, iLine, iColumn, bstrFileName);
return VSConstants.S_OK;
}
// TODO: Use PreserveSig instead of throwing these exceptions for common cases.
public void ReportError2(string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")]VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName)
{
// first we check whether given error is something we can take care.
if (!CanHandle(bstrErrorId))
{
// it is not, let project system takes care.
throw new NotImplementedException();
}
if ((iEndLine >= 0 && iEndColumn >= 0) &&
((iEndLine < iStartLine) ||
(iEndLine == iStartLine && iEndColumn < iStartColumn)))
{
throw new ArgumentException(ServicesVSResources.End_position_must_be_start_position);
}
var priority = (VSTASKPRIORITY)nPriority;
DiagnosticSeverity severity;
switch (priority)
{
case VSTASKPRIORITY.TP_HIGH:
severity = DiagnosticSeverity.Error;
break;
case VSTASKPRIORITY.TP_NORMAL:
severity = DiagnosticSeverity.Warning;
break;
case VSTASKPRIORITY.TP_LOW:
severity = DiagnosticSeverity.Info;
break;
default:
throw new ArgumentException(ServicesVSResources.Not_a_valid_value, nameof(nPriority));
}
if (iStartLine < 0 || iStartColumn < 0)
{
// we now takes care of errors that is not belong to file as well.
var projectDiagnostic = GetDiagnosticData(
null, bstrErrorId, bstrErrorMessage, severity,
null, 0, 0, 0, 0,
bstrFileName, 0, 0, 0, 0);
_diagnosticProvider.AddNewErrors(_projectId, projectDiagnostic);
return;
}
var hostProject = _workspace.GetHostProject(_projectId);
if (!hostProject.ContainsFile(bstrFileName))
{
var projectDiagnostic = GetDiagnosticData(
null, bstrErrorId, bstrErrorMessage, severity,
null, iStartLine, iStartColumn, iEndLine, iEndColumn,
bstrFileName, iStartLine, iStartColumn, iEndLine, iEndColumn);
_diagnosticProvider.AddNewErrors(_projectId, projectDiagnostic);
return;
}
var hostDocument = hostProject.GetCurrentDocumentFromPath(bstrFileName);
var diagnostic = GetDiagnosticData(
hostDocument.Id, bstrErrorId, bstrErrorMessage, severity,
null, iStartLine, iStartColumn, iEndLine, iEndColumn,
bstrFileName, iStartLine, iStartColumn, iEndLine, iEndColumn);
_diagnosticProvider.AddNewErrors(hostDocument.Id, diagnostic);
}
public int ClearErrors()
{
_diagnosticProvider.ClearErrors(_projectId);
return VSConstants.S_OK;
}
private string GetErrorId(ExternalError error)
{
return string.Format("{0}{1:0000}", _errorCodePrefix, error.iErrorID);
}
private static int GetWarningLevel(DiagnosticSeverity severity)
{
return severity == DiagnosticSeverity.Error ? 0 : 1;
}
private static DiagnosticSeverity GetDiagnosticSeverity(ExternalError error)
{
return error.fError != 0 ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning;
}
private DiagnosticData GetDiagnosticData(
ExternalError error, DocumentId id = null, int line = 0, int column = 0)
{
if (id != null)
{
// save error line/column (surface buffer location) as mapped line/column so that we can display
// right location on closed Venus file.
return GetDiagnosticData(
id, GetErrorId(error), error.bstrText, GetDiagnosticSeverity(error),
null, error.iLine, error.iCol, error.iLine, error.iCol, error.bstrFileName, line, column, line, column);
}
return GetDiagnosticData(
id, GetErrorId(error), error.bstrText, GetDiagnosticSeverity(error), null, 0, 0, 0, 0, null, 0, 0, 0, 0);
}
private static bool IsCompilerDiagnostic(string errorId)
{
if (!string.IsNullOrEmpty(errorId) && errorId.Length > 2)
{
var prefix = errorId.Substring(0, 2);
if (prefix.Equals("CS", StringComparison.OrdinalIgnoreCase) || prefix.Equals("BC", StringComparison.OrdinalIgnoreCase))
{
var suffix = errorId.Substring(2);
return int.TryParse(suffix, out var id);
}
}
return false;
}
private static IReadOnlyList<string> GetCustomTags(string errorId)
{
return IsCompilerDiagnostic(errorId) ? CompilerDiagnosticCustomTags : CustomTags;
}
private DiagnosticData GetDiagnosticData(
DocumentId id, string errorId, string message, DiagnosticSeverity severity,
string mappedFilePath, int mappedStartLine, int mappedStartColumn, int mappedEndLine, int mappedEndColumn,
string originalFilePath, int originalStartLine, int originalStartColumn, int originalEndLine, int originalEndColumn)
{
return new DiagnosticData(
id: errorId,
category: WellKnownDiagnosticTags.Build,
message: message,
title: message,
enuMessageForBingSearch: message, // Unfortunately, there is no way to get ENU text for this since this is an external error.
severity: severity,
defaultSeverity: severity,
isEnabledByDefault: true,
warningLevel: GetWarningLevel(severity),
customTags: GetCustomTags(errorId),
properties: DiagnosticData.PropertiesForBuildDiagnostic,
workspace: _workspace,
projectId: _projectId,
location: new DiagnosticDataLocation(id,
sourceSpan: null,
originalFilePath: originalFilePath,
originalStartLine: originalStartLine,
originalStartColumn: originalStartColumn,
originalEndLine: originalEndLine,
originalEndColumn: originalEndColumn,
mappedFilePath: mappedFilePath,
mappedStartLine: mappedStartLine,
mappedStartColumn: mappedStartColumn,
mappedEndLine: mappedEndLine,
mappedEndColumn: mappedEndColumn));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class ClearTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
HybridDictionary hd;
const int BIG_LENGTH = 100;
// simple string values
string[] valuesShort =
{
"",
" ",
"$%^#",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keysShort =
{
Int32.MaxValue.ToString(),
" ",
System.DateTime.Today.ToString(),
"",
"$%^#"
};
string[] valuesLong = new string[BIG_LENGTH];
string[] keysLong = new string[BIG_LENGTH];
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
for (int i = 0; i < BIG_LENGTH; i++)
{
valuesLong[i] = "Item" + i;
keysLong[i] = "keY" + i;
}
// [] HybridDictionary is constructed as expected
//-----------------------------------------------------------------
hd = new HybridDictionary();
cnt = hd.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1} after default ctor", hd.Count, 0));
}
// [] Clear() on empty dictionary
//
hd.Clear();
cnt = hd.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", hd.Count, 0));
}
cnt = hd.Keys.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, Keys.Count is {0} instead of {1} after Clear()", cnt, 0));
}
cnt = hd.Values.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, Values.Count is {0} instead of {1} after Clear()", cnt, 0));
}
// [] Add simple strings and Clear()
//
cnt = hd.Count;
for (int i = 0; i < valuesShort.Length; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
if (hd.Count != valuesShort.Length)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, valuesShort.Length));
}
hd.Clear();
cnt = hd.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", hd.Count, 0));
}
cnt = hd.Keys.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, Keys.Count is {0} instead of {1} after Clear()", cnt, 0));
}
cnt = hd.Values.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, Values.Count is {0} instead of {1} after Clear()", cnt, 0));
}
//
// [] Add Intl strings and Clear()
//
int len = valuesShort.Length;
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
// Add items
//
cnt = hd.Count;
for (int i = 0; i < len; i++)
{
hd.Add(intlValues[i + len], intlValues[i]);
}
if (hd.Count != (cnt + len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len));
}
hd.Clear();
cnt = hd.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", hd.Count, 0));
}
cnt = hd.Keys.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, Keys.Count is {0} instead of {1} after Clear()", cnt, 0));
}
cnt = hd.Values.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, Values.Count is {0} instead of {1} after Clear()", cnt, 0));
}
//
// [] Add many simple strings and Clear()
//
hd.Clear();
for (int i = 0; i < valuesLong.Length; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
if (hd.Count != valuesLong.Length)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, valuesLong.Length));
}
hd.Clear();
cnt = hd.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", hd.Count, 0));
}
cnt = hd.Keys.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, Keys.Count is {0} instead of {1} after Clear()", cnt, 0));
}
cnt = hd.Values.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, Values.Count is {0} instead of {1} after Clear()", cnt, 0));
}
// Clear should clear underlying collection's items
hd = new HybridDictionary();
for (int i = 0; i < 100; i++)
hd.Add("key_" + i, "val_" + i);
ICollection icol1 = hd.Keys;
ICollection icol2 = hd.Values;
hd.Clear();
if (icol1.Count != 0)
{
Assert.False(true, string.Format("Error, icol1.Count wrong, expected {0} got {1}", 0, icol1.Count));
}
if (icol2.Count != 0)
{
Assert.False(true, string.Format("Error, icol2.Count wrong, expected {0} got {1}", 0, icol2.Count));
}
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Configuration;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Hosting;
using System.Web.Security;
using System.Xml.Linq;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
namespace Site.Areas.Setup
{
public abstract class SetupManager
{
public abstract bool Exists();
public abstract ConnectionStringSettings GetConnectionString();
public abstract string GetWebsiteName();
public abstract void Save(Uri organizationServiceUrl, AuthenticationProviderType authenticationType, string domain, string username, string password, Guid websiteId);
public abstract bool Enabled();
protected virtual void SaveWebsiteBinding(Guid websiteId)
{
using (var service = new OrganizationService(new CrmConnection(GetConnectionString())))
{
var website = new EntityReference("adx_website", websiteId);
var siteName = GetSiteName();
var virtualPath = HostingEnvironment.ApplicationVirtualPath ?? "/";
var query = new QueryExpression("adx_websitebinding") { ColumnSet = new ColumnSet("adx_websiteid") };
query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
query.Criteria.AddCondition("adx_sitename", ConditionOperator.Equal, siteName);
var pathFilter = query.Criteria.AddFilter(LogicalOperator.Or);
if (!virtualPath.StartsWith("/")) virtualPath = "/" + virtualPath;
pathFilter.AddCondition("adx_virtualpath", ConditionOperator.Equal, virtualPath);
pathFilter.AddCondition("adx_virtualpath", ConditionOperator.Equal, virtualPath.Substring(1));
if (virtualPath.Substring(1) == string.Empty)
{
pathFilter.AddCondition("adx_virtualpath", ConditionOperator.Null);
}
var bindings = service.RetrieveMultiple(query);
if (bindings.Entities.Count == 0)
{
var websiteBinding = CreateWebsiteBinding(website, siteName, virtualPath);
service.Create(websiteBinding);
}
}
}
private static Entity CreateWebsiteBinding(EntityReference websiteId, string siteName, string virtualPath)
{
var websiteBinding = new Entity("adx_websitebinding");
websiteBinding.SetAttributeValue<string>("adx_name", StringExtensions.FormatWith("Binding: {0}{1}", siteName, virtualPath));
websiteBinding.SetAttributeValue<EntityReference>("adx_websiteid", websiteId);
websiteBinding.SetAttributeValue<string>("adx_sitename", siteName);
websiteBinding.SetAttributeValue<string>("adx_virtualpath", virtualPath);
return websiteBinding;
}
public static string GetSiteName()
{
string siteName = HostingEnvironment.SiteName;
var match = SiteNameRegex.Match(siteName);
return match.Success && match.Groups["site"].Success
? match.Groups["site"].Value
: siteName;
}
/// <summary>
/// Regular expression to grep site name
/// </summary>
private static readonly Regex SiteNameRegex = new Regex(@"^.+_IN_\d+_(?<site>.+)$|^(?<site>[^\(\)]+)\(\d+\)$", RegexOptions.IgnoreCase);
}
internal class DefaultSetupManager : SetupManager
{
private DefaultSetupManager() { }
public static SetupManager Create()
{
return new DefaultSetupManager();
}
public override void Save(Uri organizationServiceUrl, AuthenticationProviderType authenticationType, string domain, string username, string password, Guid websiteId)
{
var xml = new XElement("settings");
xml.SetElementValue("organizationServiceUrl", organizationServiceUrl.OriginalString);
xml.SetElementValue("authenticationType", authenticationType.ToString());
xml.SetElementValue("domain", domain);
xml.SetElementValue("username", username);
xml.SetElementValue("password", Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(password), _machineKeyPurposes)));
xml.Save(_settingsPath.Value);
try
{
SaveWebsiteBinding(websiteId);
}
catch (Exception)
{
File.Delete(_settingsPath.Value);
}
}
public override bool Exists()
{
return File.Exists(_settingsPath.Value);
}
public override ConnectionStringSettings GetConnectionString()
{
return Exists() ? _connectionString.Value : null;
}
public override string GetWebsiteName()
{
return Exists() ? _websiteName.Value : null;
}
public override bool Enabled()
{
return _isEnabled.Value;
}
private static readonly Lazy<string> _settingsPath = new Lazy<string>(GetSettingsPath);
private static readonly Lazy<ConnectionStringSettings> _connectionString = new Lazy<ConnectionStringSettings>(InitConnectionString);
private static readonly Lazy<string> _websiteName = new Lazy<string>(InitWebsiteName);
private static readonly string[] _machineKeyPurposes = { "adxstudio", "setup" };
private static readonly Lazy<bool> _isEnabled = new Lazy<bool>(CheckPortalConfigType);
private static string GetSettingsPath()
{
var virtualPath = ConfigurationManager.AppSettings[typeof(SetupManager).FullName + ".SettingsPath"] ?? "~/App_Data/settings.xml";
var settingsPath = HostingEnvironment.MapPath(virtualPath);
var dataDirectory = Path.GetDirectoryName(settingsPath);
if (!Directory.Exists(dataDirectory))
{
Directory.CreateDirectory(dataDirectory);
}
return settingsPath;
}
private static ConnectionStringSettings InitConnectionString()
{
var xml = XElement.Load(_settingsPath.Value);
var organizationServiceUrl = GetUrl(xml, "organizationServiceUrl");
var authenticationType = ToAuthType(GetEnum<AuthenticationProviderType>(xml, "authenticationType"));
var domain = GetText(xml, "domain");
var username = GetText(xml, "username");
var password = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(GetText(xml, "password")), _machineKeyPurposes));
var connectionString = authenticationType == AuthenticationType.AD
? StringExtensions.FormatWith("AuthType={0}; Url={1}; Username={2}; Password={3}; Domain={4};", authenticationType, organizationServiceUrl, username, password, domain)
: StringExtensions.FormatWith("AuthType={0}; Url={1}; Username={2}; Password={3};", authenticationType, organizationServiceUrl, username, password);
return new ConnectionStringSettings("Xrm", connectionString);
}
private static AuthenticationType ToAuthType(AuthenticationProviderType? apt)
{
if (apt == AuthenticationProviderType.ActiveDirectory) return AuthenticationType.AD;
if (apt == AuthenticationProviderType.Federation) return AuthenticationType.IFD;
if (apt == AuthenticationProviderType.OnlineFederation) return AuthenticationType.Office365;
if (apt == AuthenticationProviderType.LiveId) return AuthenticationType.Live;
return AuthenticationType.InvalidConnection;
}
private static string InitWebsiteName()
{
var xml = XElement.Load(_settingsPath.Value);
return GetText(xml, "websiteName");
}
private static string GetText(XContainer xml, string tagName)
{
var element = xml.Element(tagName);
return element != null ? element.Value : null;
}
private static Uri GetUrl(XContainer xml, string tagName)
{
var text = GetText(xml, tagName);
return !string.IsNullOrWhiteSpace(text) ? new Uri(text) : null;
}
private static T? GetEnum<T>(XContainer xml, string tagName) where T : struct
{
var text = GetText(xml, tagName);
return !string.IsNullOrWhiteSpace(text) ? StringExtensions.ToEnum<T>(text) as T? : null;
}
private enum PortalConfigType
{
OnLine,
OnPrem,
Azure
}
private static bool CheckPortalConfigType()
{
var portalConfigType = ConfigurationManager.AppSettings["PortalConfigType"];
PortalConfigType result;
if (!Enum.TryParse(portalConfigType, true, out result))
{
result = PortalConfigType.OnLine;
}
return (result != PortalConfigType.OnLine);
}
/// <summary>
/// Decision switch for the sort of Auth to login to CRM with
/// </summary>
public enum AuthenticationType
{
/// <summary>
/// Active Directory Auth
/// </summary>
AD,
/// <summary>
/// Live Auth
/// </summary>
Live,
/// <summary>
/// SPLA Auth
/// </summary>
IFD,
/// <summary>
/// CLAIMS based Auth
/// </summary>
Claims,
/// <summary>
/// Office365 base login process
/// </summary>
Office365,
/// <summary>
/// OAuth based Auth
/// </summary>
OAuth,
/// <summary>
/// Invalid connection
/// </summary>
InvalidConnection = -1
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.Implementation.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public class ProjectCacheHostServiceFactoryTests
{
private void Test(Action<IProjectCacheHostService, ProjectId, ICachedObjectOwner, ObjectReference<object>> action)
{
// Putting cacheService.CreateStrongReference in a using statement
// creates a temporary local that isn't collected in Debug builds
// Wrapping it in a lambda allows it to get collected.
var cacheService = new ProjectCacheService(null, int.MaxValue);
var projectId = ProjectId.CreateNewId();
var owner = new Owner();
var instance = ObjectReference.CreateFromFactory(() => new object());
action(cacheService, projectId, owner, instance);
}
[Fact]
public void TestCacheKeepsObjectAlive1()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
instance.UseReference(i => cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, i));
instance.AssertHeld();
}
instance.AssertReleased();
GC.KeepAlive(owner);
});
}
[Fact]
public void TestCacheKeepsObjectAlive2()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
instance.UseReference(i => cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, i));
instance.AssertHeld();
}
instance.AssertReleased();
GC.KeepAlive(owner);
});
}
[Fact]
public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected1()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, instance);
owner = null;
instance.AssertReleased();
}
});
}
[Fact]
public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected2()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, instance);
owner = null;
instance.AssertReleased();
}
});
}
[Fact]
public void TestImplicitCacheKeepsObjectAlive1()
{
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cacheService = new ProjectCacheService(workspace, int.MaxValue);
var reference = ObjectReference.CreateFromFactory(() => new object());
reference.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, r));
reference.AssertHeld();
GC.KeepAlive(cacheService);
}
[Fact]
public void TestImplicitCacheMonitoring()
{
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cacheService = new ProjectCacheService(workspace, 10);
var weak = PutObjectInImplicitCache(cacheService);
weak.AssertReleased();
GC.KeepAlive(cacheService);
}
private static ObjectReference<object> PutObjectInImplicitCache(ProjectCacheService cacheService)
{
var reference = ObjectReference.CreateFromFactory(() => new object());
reference.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, r));
return reference;
}
[Fact]
public void TestP2PReference()
{
var workspace = new AdhocWorkspace();
var project1 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj1", "proj1", LanguageNames.CSharp);
var project2 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj2", "proj2", LanguageNames.CSharp, projectReferences: SpecializedCollections.SingletonEnumerable(new ProjectReference(project1.Id)));
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { project1, project2 });
var solution = workspace.AddSolution(solutionInfo);
var instanceTracker = ObjectReference.CreateFromFactory(() => new object());
var cacheService = new ProjectCacheService(workspace, int.MaxValue);
using (var cache = cacheService.EnableCaching(project2.Id))
{
instanceTracker.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(project1.Id, (object)null, r));
solution = null;
workspace.OnProjectRemoved(project1.Id);
workspace.OnProjectRemoved(project2.Id);
}
// make sure p2p reference doesn't go to implicit cache
instanceTracker.AssertReleased();
}
[Fact]
public void TestEjectFromImplicitCache()
{
List<Compilation> compilations = new List<Compilation>();
for (int i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++)
{
compilations.Add(CSharpCompilation.Create(i.ToString()));
}
var weakFirst = ObjectReference.Create(compilations[0]);
var weakLast = ObjectReference.Create(compilations[compilations.Count - 1]);
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cache = new ProjectCacheService(workspace, int.MaxValue);
for (int i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++)
{
cache.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, compilations[i]);
}
compilations = null;
weakFirst.AssertReleased();
weakLast.AssertHeld();
GC.KeepAlive(cache);
}
[Fact]
public void TestCacheCompilationTwice()
{
var comp1 = CSharpCompilation.Create("1");
var comp2 = CSharpCompilation.Create("2");
var comp3 = CSharpCompilation.Create("3");
var weak3 = ObjectReference.Create(comp3);
var weak1 = ObjectReference.Create(comp1);
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cache = new ProjectCacheService(workspace, int.MaxValue);
var key = ProjectId.CreateNewId();
var owner = new object();
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp1);
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp2);
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3);
// When we cache 3 again, 1 should stay in the cache
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3);
comp1 = null;
comp2 = null;
comp3 = null;
weak3.AssertHeld();
weak1.AssertHeld();
GC.KeepAlive(cache);
}
private class Owner : ICachedObjectOwner
{
object ICachedObjectOwner.CachedObject { get; set; }
}
private static void CollectGarbage()
{
for (var i = 0; i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
private class MockHostServices : HostServices
{
public static readonly MockHostServices Instance = new MockHostServices();
private MockHostServices() { }
protected internal override HostWorkspaceServices CreateWorkspaceServices(Workspace workspace)
{
return new MockHostWorkspaceServices(this, workspace);
}
}
private class MockHostWorkspaceServices : HostWorkspaceServices
{
private readonly HostServices _hostServices;
private readonly Workspace _workspace;
private static readonly IWorkspaceTaskSchedulerFactory s_taskSchedulerFactory = new WorkspaceTaskSchedulerFactory();
public MockHostWorkspaceServices(HostServices hostServices, Workspace workspace)
{
_hostServices = hostServices;
_workspace = workspace;
}
public override HostServices HostServices => _hostServices;
public override Workspace Workspace => _workspace;
public override IEnumerable<TLanguageService> FindLanguageServices<TLanguageService>(MetadataFilter filter)
{
return ImmutableArray<TLanguageService>.Empty;
}
public override TWorkspaceService GetService<TWorkspaceService>()
{
if (s_taskSchedulerFactory is TWorkspaceService)
{
return (TWorkspaceService)s_taskSchedulerFactory;
}
return default(TWorkspaceService);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestCByte()
{
var test = new BooleanBinaryOpTest__TestCByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestCByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Byte> _fld1;
public Vector256<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestCByte testClass)
{
var result = Avx.TestC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestCByte testClass)
{
fixed (Vector256<Byte>* pFld1 = &_fld1)
fixed (Vector256<Byte>* pFld2 = &_fld2)
{
var result = Avx.TestC(
Avx.LoadVector256((Byte*)(pFld1)),
Avx.LoadVector256((Byte*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector256<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector256<Byte> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestCByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
}
public BooleanBinaryOpTest__TestCByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestC(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestC(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestC(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector256<Byte>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestC(
Avx.LoadVector256((Byte*)(pClsVar1)),
Avx.LoadVector256((Byte*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
var result = Avx.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestCByte();
var result = Avx.TestC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestCByte();
fixed (Vector256<Byte>* pFld1 = &test._fld1)
fixed (Vector256<Byte>* pFld2 = &test._fld2)
{
var result = Avx.TestC(
Avx.LoadVector256((Byte*)(pFld1)),
Avx.LoadVector256((Byte*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Byte>* pFld1 = &_fld1)
fixed (Vector256<Byte>* pFld2 = &_fld2)
{
var result = Avx.TestC(
Avx.LoadVector256((Byte*)(pFld1)),
Avx.LoadVector256((Byte*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestC(
Avx.LoadVector256((Byte*)(&test._fld1)),
Avx.LoadVector256((Byte*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Byte> op1, Vector256<Byte> op2, bool result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((~left[i] & right[i]) == 0);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestC)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security.Infrastructure;
using Microsoft.Owin.Security.OAuth.Messages;
using Newtonsoft.Json;
namespace Microsoft.Owin.Security.OAuth
{
internal class OAuthAuthorizationServerHandler : AuthenticationHandler<OAuthAuthorizationServerOptions>
{
private readonly ILogger _logger;
private AuthorizeEndpointRequest _authorizeEndpointRequest;
private OAuthValidateClientRedirectUriContext _clientContext;
public OAuthAuthorizationServerHandler(ILogger logger)
{
_logger = logger;
}
protected override Task<AuthenticationTicket> AuthenticateCoreAsync()
{
return Task.FromResult<AuthenticationTicket>(null);
}
public override async Task<bool> InvokeAsync()
{
var matchRequestContext = new OAuthMatchEndpointContext(Context, Options);
if (Options.AuthorizeEndpointPath.HasValue && Options.AuthorizeEndpointPath == Request.Path)
{
matchRequestContext.MatchesAuthorizeEndpoint();
}
else if (Options.TokenEndpointPath.HasValue && Options.TokenEndpointPath == Request.Path)
{
matchRequestContext.MatchesTokenEndpoint();
}
await Options.Provider.MatchEndpoint(matchRequestContext);
if (matchRequestContext.IsRequestCompleted)
{
return true;
}
if (matchRequestContext.IsAuthorizeEndpoint || matchRequestContext.IsTokenEndpoint)
{
if (!Options.AllowInsecureHttp &&
String.Equals(Request.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
{
_logger.WriteWarning("Authorization server ignoring http request because AllowInsecureHttp is false.");
return false;
}
if (matchRequestContext.IsAuthorizeEndpoint)
{
return await InvokeAuthorizeEndpointAsync();
}
if (matchRequestContext.IsTokenEndpoint)
{
await InvokeTokenEndpointAsync();
return true;
}
}
return false;
}
private async Task<bool> InvokeAuthorizeEndpointAsync()
{
var authorizeRequest = new AuthorizeEndpointRequest(Request.Query);
var clientContext = new OAuthValidateClientRedirectUriContext(
Context,
Options,
authorizeRequest.ClientId,
authorizeRequest.RedirectUri);
if (!String.IsNullOrEmpty(authorizeRequest.RedirectUri))
{
bool acceptableUri = true;
Uri validatingUri;
if (!Uri.TryCreate(authorizeRequest.RedirectUri, UriKind.Absolute, out validatingUri))
{
// The redirection endpoint URI MUST be an absolute URI
// http://tools.ietf.org/html/rfc6749#section-3.1.2
acceptableUri = false;
}
else if (!String.IsNullOrEmpty(validatingUri.Fragment))
{
// The endpoint URI MUST NOT include a fragment component.
// http://tools.ietf.org/html/rfc6749#section-3.1.2
acceptableUri = false;
}
else if (!Options.AllowInsecureHttp &&
String.Equals(validatingUri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
{
// The redirection endpoint SHOULD require the use of TLS
// http://tools.ietf.org/html/rfc6749#section-3.1.2.1
acceptableUri = false;
}
if (!acceptableUri)
{
clientContext.SetError(Constants.Errors.InvalidRequest);
return await SendErrorRedirectAsync(clientContext, clientContext);
}
}
await Options.Provider.ValidateClientRedirectUri(clientContext);
if (!clientContext.IsValidated)
{
_logger.WriteVerbose("Unable to validate client information");
return await SendErrorRedirectAsync(clientContext, clientContext);
}
var validatingContext = new OAuthValidateAuthorizeRequestContext(
Context,
Options,
authorizeRequest,
clientContext);
if (string.IsNullOrEmpty(authorizeRequest.ResponseType))
{
_logger.WriteVerbose("Authorize endpoint request missing required response_type parameter");
validatingContext.SetError(Constants.Errors.InvalidRequest);
}
else if (!authorizeRequest.IsAuthorizationCodeGrantType &&
!authorizeRequest.IsImplicitGrantType)
{
_logger.WriteVerbose("Authorize endpoint request contains unsupported response_type parameter");
validatingContext.SetError(Constants.Errors.UnsupportedResponseType);
}
else
{
await Options.Provider.ValidateAuthorizeRequest(validatingContext);
}
if (!validatingContext.IsValidated)
{
// an invalid request is not processed further
return await SendErrorRedirectAsync(clientContext, validatingContext);
}
_clientContext = clientContext;
_authorizeEndpointRequest = authorizeRequest;
var authorizeEndpointContext = new OAuthAuthorizeEndpointContext(Context, Options);
await Options.Provider.AuthorizeEndpoint(authorizeEndpointContext);
return authorizeEndpointContext.IsRequestCompleted;
}
protected override async Task ApplyResponseGrantAsync()
{
// only successful results of an authorize request are altered
if (_clientContext == null ||
_authorizeEndpointRequest == null ||
Response.StatusCode != 200)
{
return;
}
// only apply with signin of matching authentication type
AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);
if (signin == null)
{
return;
}
string location = _clientContext.RedirectUri;
if (_authorizeEndpointRequest.IsAuthorizationCodeGrantType)
{
DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
signin.Properties.IssuedUtc = currentUtc;
signin.Properties.ExpiresUtc = currentUtc.Add(Options.AuthorizationCodeExpireTimeSpan);
// associate client_id with all subsequent tickets
signin.Properties.Dictionary[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId;
if (!string.IsNullOrEmpty(_authorizeEndpointRequest.RedirectUri))
{
// keep original request parameter for later comparison
signin.Properties.Dictionary[Constants.Extra.RedirectUri] = _authorizeEndpointRequest.RedirectUri;
}
var context = new AuthenticationTokenCreateContext(
Context,
Options.AuthorizationCodeFormat,
new AuthenticationTicket(signin.Identity, signin.Properties));
await Options.AuthorizationCodeProvider.CreateAsync(context);
string code = context.Token;
if (string.IsNullOrEmpty(code))
{
_logger.WriteError("response_type code requires an Options.AuthorizationCodeProvider implementing a single-use token.");
var errorContext = new OAuthValidateAuthorizeRequestContext(Context, Options, _authorizeEndpointRequest, _clientContext);
errorContext.SetError(Constants.Errors.UnsupportedResponseType);
await SendErrorRedirectAsync(_clientContext, errorContext);
}
location = WebUtilities.AddQueryString(location, Constants.Parameters.Code, code);
if (!String.IsNullOrEmpty(_authorizeEndpointRequest.State))
{
location = WebUtilities.AddQueryString(location, Constants.Parameters.State, _authorizeEndpointRequest.State);
}
Response.Redirect(location);
}
else if (_authorizeEndpointRequest.IsImplicitGrantType)
{
DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
signin.Properties.IssuedUtc = currentUtc;
signin.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan);
// associate client_id with access token
signin.Properties.Dictionary[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId;
var accessTokenContext = new AuthenticationTokenCreateContext(
Context,
Options.AccessTokenFormat,
new AuthenticationTicket(signin.Identity, signin.Properties));
await Options.AccessTokenProvider.CreateAsync(accessTokenContext);
string accessToken = accessTokenContext.Token;
if (string.IsNullOrEmpty(accessToken))
{
accessToken = accessTokenContext.SerializeTicket();
}
DateTimeOffset? accessTokenExpiresUtc = accessTokenContext.Ticket.Properties.ExpiresUtc;
var appender = new Appender(location, '#');
appender
.Append(Constants.Parameters.AccessToken, accessToken)
.Append(Constants.Parameters.TokenType, Constants.TokenTypes.Bearer);
if (accessTokenExpiresUtc.HasValue)
{
TimeSpan? expiresTimeSpan = accessTokenExpiresUtc - currentUtc;
var expiresIn = (long)(expiresTimeSpan.Value.TotalSeconds + .5);
appender.Append(Constants.Parameters.ExpiresIn, expiresIn.ToString(CultureInfo.InvariantCulture));
}
if (!String.IsNullOrEmpty(_authorizeEndpointRequest.State))
{
appender.Append(Constants.Parameters.State, _authorizeEndpointRequest.State);
}
Response.Redirect(appender.ToString());
}
}
private async Task InvokeTokenEndpointAsync()
{
DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
// remove milliseconds in case they don't round-trip
currentUtc = currentUtc.Subtract(TimeSpan.FromMilliseconds(currentUtc.Millisecond));
IFormCollection form = await Request.ReadFormAsync();
var clientContext = new OAuthValidateClientAuthenticationContext(
Context,
Options,
form);
await Options.Provider.ValidateClientAuthentication(clientContext);
if (!clientContext.IsValidated)
{
_logger.WriteError("clientID is not valid.");
if (!clientContext.HasError)
{
clientContext.SetError(Constants.Errors.InvalidClient);
}
await SendErrorAsJsonAsync(clientContext);
return;
}
var tokenEndpointRequest = new TokenEndpointRequest(form);
var validatingContext = new OAuthValidateTokenRequestContext(Context, Options, tokenEndpointRequest, clientContext);
AuthenticationTicket ticket = null;
if (tokenEndpointRequest.IsAuthorizationCodeGrantType)
{
// Authorization Code Grant http://tools.ietf.org/html/rfc6749#section-4.1
// Access Token Request http://tools.ietf.org/html/rfc6749#section-4.1.3
ticket = await InvokeTokenEndpointAuthorizationCodeGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsResourceOwnerPasswordCredentialsGrantType)
{
// Resource Owner Password Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.3
// Access Token Request http://tools.ietf.org/html/rfc6749#section-4.3.2
ticket = await InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsClientCredentialsGrantType)
{
// Client Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.4
// Access Token Request http://tools.ietf.org/html/rfc6749#section-4.4.2
ticket = await InvokeTokenEndpointClientCredentialsGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsRefreshTokenGrantType)
{
// Refreshing an Access Token
// http://tools.ietf.org/html/rfc6749#section-6
ticket = await InvokeTokenEndpointRefreshTokenGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsCustomExtensionGrantType)
{
// Defining New Authorization Grant Types
// http://tools.ietf.org/html/rfc6749#section-8.3
ticket = await InvokeTokenEndpointCustomGrantAsync(validatingContext, currentUtc);
}
else
{
// Error Response http://tools.ietf.org/html/rfc6749#section-5.2
// The authorization grant type is not supported by the
// authorization server.
_logger.WriteError("grant type is not recognized");
validatingContext.SetError(Constants.Errors.UnsupportedGrantType);
}
if (ticket == null)
{
await SendErrorAsJsonAsync(validatingContext);
return;
}
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan);
var tokenEndpointContext = new OAuthTokenEndpointContext(
Context,
Options,
ticket,
tokenEndpointRequest);
await Options.Provider.TokenEndpoint(tokenEndpointContext);
if (tokenEndpointContext.TokenIssued)
{
ticket = new AuthenticationTicket(
tokenEndpointContext.Identity,
tokenEndpointContext.Properties);
}
else
{
_logger.WriteError("Token was not issued to tokenEndpointContext");
validatingContext.SetError(Constants.Errors.InvalidGrant);
await SendErrorAsJsonAsync(validatingContext);
return;
}
var accessTokenContext = new AuthenticationTokenCreateContext(
Context,
Options.AccessTokenFormat,
ticket);
await Options.AccessTokenProvider.CreateAsync(accessTokenContext);
string accessToken = accessTokenContext.Token;
if (string.IsNullOrEmpty(accessToken))
{
accessToken = accessTokenContext.SerializeTicket();
}
DateTimeOffset? accessTokenExpiresUtc = ticket.Properties.ExpiresUtc;
var refreshTokenCreateContext = new AuthenticationTokenCreateContext(
Context,
Options.RefreshTokenFormat,
accessTokenContext.Ticket);
await Options.RefreshTokenProvider.CreateAsync(refreshTokenCreateContext);
string refreshToken = refreshTokenCreateContext.Token;
var memory = new MemoryStream();
byte[] body;
using (var writer = new JsonTextWriter(new StreamWriter(memory)))
{
writer.WriteStartObject();
writer.WritePropertyName(Constants.Parameters.AccessToken);
writer.WriteValue(accessToken);
writer.WritePropertyName(Constants.Parameters.TokenType);
writer.WriteValue(Constants.TokenTypes.Bearer);
if (accessTokenExpiresUtc.HasValue)
{
TimeSpan? expiresTimeSpan = accessTokenExpiresUtc - currentUtc;
var expiresIn = (long)expiresTimeSpan.Value.TotalSeconds;
if (expiresIn > 0)
{
writer.WritePropertyName(Constants.Parameters.ExpiresIn);
writer.WriteValue(expiresIn);
}
}
if (!String.IsNullOrEmpty(refreshToken))
{
writer.WritePropertyName(Constants.Parameters.RefreshToken);
writer.WriteValue(refreshToken);
}
foreach (var additionalResponseParameter in tokenEndpointContext.AdditionalResponseParameters)
{
writer.WritePropertyName(additionalResponseParameter.Key);
writer.WriteValue(additionalResponseParameter.Value);
}
writer.WriteEndObject();
writer.Flush();
body = memory.ToArray();
}
Response.ContentType = "application/json;charset=UTF-8";
Response.Headers.Set("Cache-Control", "no-cache");
Response.Headers.Set("Pragma", "no-cache");
Response.Headers.Set("Expires", "-1");
Response.ContentLength = memory.ToArray().Length;
await Response.WriteAsync(body, Request.CallCancelled);
}
private async Task<AuthenticationTicket> InvokeTokenEndpointAuthorizationCodeGrantAsync(
OAuthValidateTokenRequestContext validatingContext,
DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
var authorizationCodeContext = new AuthenticationTokenReceiveContext(
Context,
Options.AuthorizationCodeFormat,
tokenEndpointRequest.AuthorizationCodeGrant.Code);
await Options.AuthorizationCodeProvider.ReceiveAsync(authorizationCodeContext);
AuthenticationTicket ticket = authorizationCodeContext.Ticket;
if (ticket == null)
{
_logger.WriteError("invalid authorization code");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
if (!ticket.Properties.ExpiresUtc.HasValue ||
ticket.Properties.ExpiresUtc < currentUtc)
{
_logger.WriteError("expired authorization code");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
string clientId;
if (!ticket.Properties.Dictionary.TryGetValue(Constants.Extra.ClientId, out clientId) ||
!String.Equals(clientId, validatingContext.ClientContext.ClientId, StringComparison.Ordinal))
{
_logger.WriteError("authorization code does not contain matching client_id");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
string redirectUri;
if (ticket.Properties.Dictionary.TryGetValue(Constants.Extra.RedirectUri, out redirectUri))
{
ticket.Properties.Dictionary.Remove(Constants.Extra.RedirectUri);
if (!String.Equals(redirectUri, tokenEndpointRequest.AuthorizationCodeGrant.RedirectUri, StringComparison.Ordinal))
{
_logger.WriteError("authorization code does not contain matching redirect_uri");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
}
await Options.Provider.ValidateTokenRequest(validatingContext);
var grantContext = new OAuthGrantAuthorizationCodeContext(
Context, Options, ticket);
if (validatingContext.IsValidated)
{
await Options.Provider.GrantAuthorizationCode(grantContext);
}
return ReturnOutcome(
validatingContext,
grantContext,
grantContext.Ticket,
Constants.Errors.InvalidGrant);
}
private async Task<AuthenticationTicket> InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync(
OAuthValidateTokenRequestContext validatingContext,
DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
await Options.Provider.ValidateTokenRequest(validatingContext);
var grantContext = new OAuthGrantResourceOwnerCredentialsContext(
Context,
Options,
validatingContext.ClientContext.ClientId,
tokenEndpointRequest.ResourceOwnerPasswordCredentialsGrant.UserName,
tokenEndpointRequest.ResourceOwnerPasswordCredentialsGrant.Password,
tokenEndpointRequest.ResourceOwnerPasswordCredentialsGrant.Scope);
if (validatingContext.IsValidated)
{
await Options.Provider.GrantResourceOwnerCredentials(grantContext);
}
return ReturnOutcome(
validatingContext,
grantContext,
grantContext.Ticket,
Constants.Errors.InvalidGrant);
}
private async Task<AuthenticationTicket> InvokeTokenEndpointClientCredentialsGrantAsync(
OAuthValidateTokenRequestContext validatingContext,
DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
await Options.Provider.ValidateTokenRequest(validatingContext);
if (!validatingContext.IsValidated)
{
return null;
}
var grantContext = new OAuthGrantClientCredentialsContext(
Context,
Options,
validatingContext.ClientContext.ClientId,
tokenEndpointRequest.ClientCredentialsGrant.Scope);
await Options.Provider.GrantClientCredentials(grantContext);
return ReturnOutcome(
validatingContext,
grantContext,
grantContext.Ticket,
Constants.Errors.UnauthorizedClient);
}
private async Task<AuthenticationTicket> InvokeTokenEndpointRefreshTokenGrantAsync(
OAuthValidateTokenRequestContext validatingContext,
DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
var refreshTokenContext = new AuthenticationTokenReceiveContext(
Context,
Options.RefreshTokenFormat,
tokenEndpointRequest.RefreshTokenGrant.RefreshToken);
await Options.RefreshTokenProvider.ReceiveAsync(refreshTokenContext);
AuthenticationTicket ticket = refreshTokenContext.Ticket;
if (ticket == null)
{
_logger.WriteError("invalid refresh token");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
if (!ticket.Properties.ExpiresUtc.HasValue ||
ticket.Properties.ExpiresUtc < currentUtc)
{
_logger.WriteError("expired refresh token");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
await Options.Provider.ValidateTokenRequest(validatingContext);
var grantContext = new OAuthGrantRefreshTokenContext(Context, Options, ticket);
if (validatingContext.IsValidated)
{
await Options.Provider.GrantRefreshToken(grantContext);
}
return ReturnOutcome(
validatingContext,
grantContext,
grantContext.Ticket,
Constants.Errors.InvalidGrant);
}
private async Task<AuthenticationTicket> InvokeTokenEndpointCustomGrantAsync(
OAuthValidateTokenRequestContext validatingContext,
DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
await Options.Provider.ValidateTokenRequest(validatingContext);
var grantContext = new OAuthGrantCustomExtensionContext(
Context,
Options,
validatingContext.ClientContext.ClientId,
tokenEndpointRequest.GrantType,
tokenEndpointRequest.CustomExtensionGrant.Parameters);
if (validatingContext.IsValidated)
{
await Options.Provider.GrantCustomExtension(grantContext);
}
return ReturnOutcome(
validatingContext,
grantContext,
grantContext.Ticket,
Constants.Errors.UnsupportedGrantType);
}
private static AuthenticationTicket ReturnOutcome(
OAuthValidateTokenRequestContext validatingContext,
BaseValidatingContext<OAuthAuthorizationServerOptions> grantContext,
AuthenticationTicket ticket,
string defaultError)
{
if (!validatingContext.IsValidated)
{
return null;
}
if (!grantContext.IsValidated)
{
if (grantContext.HasError)
{
validatingContext.SetError(
grantContext.Error,
grantContext.ErrorDescription,
grantContext.ErrorUri);
}
else
{
validatingContext.SetError(defaultError);
}
return null;
}
if (ticket == null)
{
validatingContext.SetError(defaultError);
return null;
}
return ticket;
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The MemoryStream is Disposed by the StreamWriter")]
private Task SendErrorAsJsonAsync(
BaseValidatingContext<OAuthAuthorizationServerOptions> validatingContext)
{
string error = validatingContext.HasError ? validatingContext.Error : Constants.Errors.InvalidRequest;
string errorDescription = validatingContext.HasError ? validatingContext.ErrorDescription : null;
string errorUri = validatingContext.HasError ? validatingContext.ErrorUri : null;
var memory = new MemoryStream();
byte[] body;
using (var writer = new JsonTextWriter(new StreamWriter(memory)))
{
writer.WriteStartObject();
writer.WritePropertyName(Constants.Parameters.Error);
writer.WriteValue(error);
if (!string.IsNullOrEmpty(errorDescription))
{
writer.WritePropertyName(Constants.Parameters.ErrorDescription);
writer.WriteValue(errorDescription);
}
if (!string.IsNullOrEmpty(errorUri))
{
writer.WritePropertyName(Constants.Parameters.ErrorUri);
writer.WriteValue(errorUri);
}
writer.WriteEndObject();
writer.Flush();
body = memory.ToArray();
}
Response.StatusCode = 400;
Response.ContentType = "application/json;charset=UTF-8";
Response.Headers.Set("Cache-Control", "no-cache");
Response.Headers.Set("Pragma", "no-cache");
Response.Headers.Set("Expires", "-1");
Response.Headers.Set("Content-Length", body.Length.ToString(CultureInfo.InvariantCulture));
return Response.WriteAsync(body, Request.CallCancelled);
}
private Task<bool> SendErrorRedirectAsync(
OAuthValidateClientRedirectUriContext clientContext,
BaseValidatingContext<OAuthAuthorizationServerOptions> validatingContext)
{
if (clientContext == null)
{
throw new ArgumentNullException("clientContext");
}
string error = validatingContext.HasError ? validatingContext.Error : Constants.Errors.InvalidRequest;
string errorDescription = validatingContext.HasError ? validatingContext.ErrorDescription : null;
string errorUri = validatingContext.HasError ? validatingContext.ErrorUri : null;
if (!clientContext.IsValidated)
{
// write error in response body if client_id or redirect_uri have not been validated
return SendErrorPageAsync(error, errorDescription, errorUri);
}
// redirect with error if client_id and redirect_uri have been validated
string location = WebUtilities.AddQueryString(clientContext.RedirectUri, Constants.Parameters.Error, error);
if (!string.IsNullOrEmpty(errorDescription))
{
location = WebUtilities.AddQueryString(location, Constants.Parameters.ErrorDescription, errorDescription);
}
if (!string.IsNullOrEmpty(errorDescription))
{
location = WebUtilities.AddQueryString(location, Constants.Parameters.ErrorUri, errorUri);
}
Response.Redirect(location);
// request is handled, does not pass on to application
return Task.FromResult(true);
}
private async Task<bool> SendErrorPageAsync(string error, string errorDescription, string errorUri)
{
Response.StatusCode = 400;
Response.Headers.Set("Cache-Control", "no-cache");
Response.Headers.Set("Pragma", "no-cache");
Response.Headers.Set("Expires", "-1");
if (Options.ApplicationCanDisplayErrors)
{
Context.Set("oauth.Error", error);
Context.Set("oauth.ErrorDescription", errorDescription);
Context.Set("oauth.ErrorUri", errorUri);
// request is not handled - pass through to application for rendering
return false;
}
var memory = new MemoryStream();
byte[] body;
using (var writer = new StreamWriter(memory))
{
writer.WriteLine("error: {0}", error);
if (!string.IsNullOrEmpty(errorDescription))
{
writer.WriteLine("error_description: {0}", errorDescription);
}
if (!string.IsNullOrEmpty(errorUri))
{
writer.WriteLine("error_uri: {0}", errorUri);
}
writer.Flush();
body = memory.ToArray();
}
Response.ContentType = "text/plain;charset=UTF-8";
Response.Headers.Set("Content-Length", body.Length.ToString(CultureInfo.InvariantCulture));
await Response.WriteAsync(body, Request.CallCancelled);
// request is handled, does not pass on to application
return true;
}
private class Appender
{
private readonly char _delimiter;
private readonly StringBuilder _sb;
private bool _hasDelimiter;
public Appender(string value, char delimiter)
{
_sb = new StringBuilder(value);
_delimiter = delimiter;
_hasDelimiter = value.IndexOf(delimiter) != -1;
}
public Appender Append(string name, string value)
{
_sb.Append(_hasDelimiter ? '&' : _delimiter)
.Append(Uri.EscapeDataString(name))
.Append('=')
.Append(Uri.EscapeDataString(value));
_hasDelimiter = true;
return this;
}
public override string ToString()
{
return _sb.ToString();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall.IO;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Graphics.Texture;
#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
using Microsoft.Xna.Framework.Graphics;
#endif
#if XNA4
using Color = Microsoft.Xna.Framework.Color;
#endif
namespace FlatRedBall.Graphics.Renderers
{
public static class ImageDataRenderer
{
#region Fields
static Color[] sTemporaryTextureBuffer;
#endregion
#region Methods
public static void RenderSprite(Sprite sprite, int leftPixel, int topPixel, int pixelWidth, int pixelHeight, ImageData imageData)
{
if (sprite.Texture == null || sprite.BlendOperation != BlendOperation.Regular)
{
// for now throw an exception, later we may want to handle pure color rendering and stuff like that
throw new NotImplementedException();
}
ImageData spriteTextureImageData = ImageData.FromTexture2D(sprite.Texture);
#if FRB_MDX
ColorOperation colorOperation = GraphicalEnumerations.TranslateTextureOperationToColorOperation(sprite.ColorOperation);
#else
ColorOperation colorOperation = sprite.ColorOperation;
#endif
spriteTextureImageData.ApplyColorOperation(colorOperation, sprite.Red, sprite.Green, sprite.Blue, sprite.Alpha);
int rightBound = System.Math.Min(imageData.Width, leftPixel + pixelWidth);
int bottomBound = System.Math.Min(imageData.Height, topPixel + pixelHeight);
int actualWidth = rightBound - leftPixel;
int actualHeight = bottomBound - topPixel;
for (int destinationX = leftPixel; destinationX < rightBound; destinationX++)
{
for (int destinationY = topPixel; destinationY < bottomBound; destinationY++)
{
int sourcePixelX = spriteTextureImageData.Width * (destinationX - leftPixel) / pixelWidth;
int sourcePixelY = spriteTextureImageData.Height * (destinationY - topPixel) / pixelHeight;
Color sourcePixel = spriteTextureImageData.GetPixelColor(sourcePixelX, sourcePixelY);
if (sourcePixel.A != 255)
{
Color destinationPixel = imageData.GetPixelColor(destinationX, destinationY);
#if FRB_MDX
sourcePixel = Color.FromArgb(
System.Math.Max(sourcePixel.A, destinationPixel.A),
(byte)(destinationPixel.R * (255 - sourcePixel.A) / 255.0f + sourcePixel.R * (sourcePixel.A) / 255.0f),
(byte)(destinationPixel.G * (255 - sourcePixel.A) / 255.0f + sourcePixel.G * (sourcePixel.A) / 255.0f),
(byte)(destinationPixel.B * (255 - sourcePixel.A) / 255.0f + sourcePixel.B * (sourcePixel.A) / 255.0f));
// This is probably not accurate, but will work currently. Eventually we may want to look at how blending is actually performed
#else
sourcePixel.R = (byte)(destinationPixel.R * (255 - sourcePixel.A) / 255.0f + sourcePixel.R * (sourcePixel.A) / 255.0f);
sourcePixel.G = (byte)(destinationPixel.G * (255 - sourcePixel.A) / 255.0f + sourcePixel.G * (sourcePixel.A) / 255.0f);
sourcePixel.B = (byte)(destinationPixel.B * (255 - sourcePixel.A) / 255.0f + sourcePixel.B * (sourcePixel.A) / 255.0f);
// This is probably not accurate, but will work currently. Eventually we may want to look at how blending is actually performed
sourcePixel.A = System.Math.Max(sourcePixel.A, destinationPixel.A);
#endif
}
imageData.SetPixel(destinationX, destinationY, sourcePixel);
}
}
}
public static ImageData RenderSpriteGrid(SpriteGrid spriteGrid)
{
int textureWidth = (int)(.5f + spriteGrid.FurthestRightX - spriteGrid.FurthestLeftX);
int textureHeight = (int)(.5f + spriteGrid.FurthestTopY - spriteGrid.FurthestBottomY);
ImageData imageData = new ImageData(textureWidth, textureHeight);
RenderSpriteGrid(spriteGrid, imageData);
return imageData;
}
public static void RenderSpriteGrid(SpriteGrid spriteGrid, ImageData imageData)
{
throw new NotImplementedException();
//// The SpriteGrid should be full
//spriteGrid.FillToBounds();
//int textureWidth = (int)(.5f + spriteGrid.FurthestRightX - spriteGrid.FurthestLeftX);
//int textureHeight = (int)(.5f + spriteGrid.FurthestTopY - spriteGrid.FurthestBottomY);
//if (imageData.Width != textureWidth || imageData.Height != textureHeight)
//{
// throw new ArgumentException("Image data is the wrong dimensions");
//}
//Dictionary<string, ImageData> mCachedImageDatas = new Dictionary<string, ImageData>();
//int pixelWidthPerSprite = (int)(.5f + (float)textureHeight / spriteGrid.VisibleSprites.Count);
//for (int row = spriteGrid.MinDisplayedRowIndex(); row <= spriteGrid.MaxDisplayedRowIndex(); row++)
//{
// for (int column = spriteGrid.MinDisplayedColIndex(); column <= spriteGrid.MaxDisplayedColIndex(); column++)
// {
// Sprite spriteAtIndex = spriteGrid.GetSpriteAtIndex(row, column);
// if (!mCachedImageDatas.ContainsKey(spriteAtIndex.Texture.Name))
// {
// ImageData imageDataForThisSprite = ImageData.FromTexture2D(spriteAtIndex.Texture);
// mCachedImageDatas.Add(spriteAtIndex.Texture.Name, imageDataForThisSprite);
// }
// ImageData imageDataToPullFrom = mCachedImageDatas[spriteAtIndex.Texture.Name];
// for (int pixelX = 0; pixelX < pixelWidthPerSprite; pixelX++)
// {
// for (int pixelY = 0; pixelY < pixelWidthPerSprite; pixelY++)
// {
// float textureX = (.5f + pixelX) / pixelWidthPerSprite;
// float textureY = (.5f + pixelY) / pixelWidthPerSprite;
// int xToWriteAt = (column - spriteGrid.MinDisplayedColIndex()) * pixelWidthPerSprite + pixelX;
// int yToWriteAt = (spriteGrid.MaxDisplayedRowIndex() - row) * pixelWidthPerSprite + pixelY;
// int spriteXPixelCoordinate = (int)(.5f + spriteAtIndex.LeftTextureCoordinate * spriteAtIndex.Texture.Width) + pixelX;
// int spriteYPixelCoordinate = (int)(.5f + spriteAtIndex.TopTextureCoordinate * spriteAtIndex.Texture.Height) + pixelY;
// // For now we'll just handle the errors in a naive way. Return here if issues occur with pixel mismatchings
// if (spriteXPixelCoordinate >= imageDataToPullFrom.Width)
// {
// spriteXPixelCoordinate = imageDataToPullFrom.Width - 1;
// }
// if (spriteYPixelCoordinate >= imageDataToPullFrom.Height)
// {
// spriteYPixelCoordinate = imageDataToPullFrom.Height - 1;
// }
// imageData.SetPixel(xToWriteAt, yToWriteAt, imageDataToPullFrom.Data[spriteXPixelCoordinate + spriteYPixelCoordinate * imageDataToPullFrom.Width]);
// }
// }
// }
//}
}
public static void RenderText(string text, BitmapFont bitmapFont, ImageData imageData)
{
RenderText(text, bitmapFont, imageData, 0, 0);
}
public static void RenderText(string text, BitmapFont bitmapFont, ImageData imageData, int x, int y)
{
sTemporaryTextureBuffer = new Color[bitmapFont.Texture.Width * bitmapFont.Texture.Height];
bitmapFont.Texture.GetData<Color>(sTemporaryTextureBuffer);
for (int i = 0; i < text.Length; i++)
{
RenderLetter(text[i], bitmapFont, imageData, x, y);
x += (int)(bitmapFont.GetCharacterSpacing(text[i]) * 8);
}
}
private static void RenderLetter(char letter, BitmapFont bitmapFont, ImageData imageData, int x, int y)
{
float tvTop = 0;
float tvBottom = 0;
float tuLeft = 0;
float tuRight = 0;
int textureWidth = bitmapFont.Texture.Width;
int textureHeight = bitmapFont.Texture.Height;
bitmapFont.AssignCharacterTextureCoordinates((int)letter, out tvTop, out tvBottom, out tuLeft, out tuRight);
float characterHeight = bitmapFont.GetCharacterHeight(letter);
int pixelLeft = (int)(tuLeft * textureWidth);
int pixelTop = (int)(tvTop * textureHeight);
int pixelRight = (int)(tuRight * textureWidth);
int pixelBottom = (int)(tvBottom * textureWidth);
float unitPerPixel = (characterHeight / (float)(pixelBottom - pixelTop));
int pixelFromTop = (int)(bitmapFont.LineHeightInPixels * bitmapFont.DistanceFromTopOfLine((int)letter) / (2));// * .25f);
for (int sourceY = pixelTop; sourceY < pixelBottom; sourceY++)
{
for (int sourceX = pixelLeft; sourceX < pixelRight; sourceX++)
{
Color colorFromSource = sTemporaryTextureBuffer[sourceY * textureHeight + sourceX];
if (colorFromSource.A != 0)
{
imageData.SetPixel(x + (sourceX - pixelLeft), pixelFromTop + y + (sourceY - pixelTop), colorFromSource);
}
}
}
}
#endregion
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
#if NET20
using Util.Json.Utilities.LinqBridge;
#else
#endif
using Json.Net.Serialization;
using Json.Net.Utilities;
namespace Json.Net
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public abstract class JsonReader : IDisposable
{
/// <summary>
/// Specifies the state of the reader.
/// </summary>
protected internal enum State
{
/// <summary>
/// The Read method has not been called.
/// </summary>
Start,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Complete,
/// <summary>
/// Reader is at a property.
/// </summary>
Property,
/// <summary>
/// Reader is at the start of an object.
/// </summary>
ObjectStart,
/// <summary>
/// Reader is in an object.
/// </summary>
Object,
/// <summary>
/// Reader is at the start of an array.
/// </summary>
ArrayStart,
/// <summary>
/// Reader is in an array.
/// </summary>
Array,
/// <summary>
/// The Close method has been called.
/// </summary>
Closed,
/// <summary>
/// Reader has just read a value.
/// </summary>
PostValue,
/// <summary>
/// Reader is at the start of a constructor.
/// </summary>
ConstructorStart,
/// <summary>
/// Reader in a constructor.
/// </summary>
Constructor,
/// <summary>
/// An error occurred that prevents the read operation from continuing.
/// </summary>
Error,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Finished
}
// current Token data
private JsonToken _tokenType;
private object _value;
internal char _quoteChar;
internal State _currentState;
internal ReadType _readType;
private JsonPosition _currentPosition;
private CultureInfo _culture;
private DateTimeZoneHandling _dateTimeZoneHandling;
private int? _maxDepth;
private bool _hasExceededMaxDepth;
internal DateParseHandling _dateParseHandling;
internal FloatParseHandling _floatParseHandling;
private string _dateFormatString;
private readonly List<JsonPosition> _stack;
/// <summary>
/// Gets the current reader state.
/// </summary>
/// <value>The current reader state.</value>
protected State CurrentState
{
get { return _currentState; }
}
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the reader is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the reader is closed; otherwise false. The default is true.
/// </value>
public bool CloseInput { get; set; }
/// <summary>
/// Gets or sets a value indicating whether multiple pieces of JSON content can
/// be read from a continuous stream without erroring.
/// </summary>
/// <value>
/// true to support reading multiple pieces of JSON content; otherwise false. The default is false.
/// </value>
public bool SupportMultipleContent { get; set; }
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public virtual char QuoteChar
{
get { return _quoteChar; }
protected internal set { _quoteChar = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get { return _dateParseHandling; }
set { _dateParseHandling = value; }
}
/// <summary>
/// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get { return _floatParseHandling; }
set { _floatParseHandling = value; }
}
/// <summary>
/// Get or set how custom date formatted strings are parsed when reading JSON.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString; }
set { _dateFormatString = value; }
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public int? MaxDepth
{
get { return _maxDepth; }
set
{
if (value <= 0)
throw new ArgumentException("Value must be positive.", "value");
_maxDepth = value;
}
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
public virtual JsonToken TokenType
{
get { return _tokenType; }
}
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object Value
{
get { return _value; }
}
/// <summary>
/// Gets The Common Language Runtime (CLR) type for the current JSON token.
/// </summary>
public virtual Type ValueType
{
get { return (_value != null) ? _value.GetType() : null; }
}
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public virtual int Depth
{
get
{
int depth = _stack.Count;
if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
return depth;
else
return depth + 1;
}
}
/// <summary>
/// Gets the path of the current JSON token.
/// </summary>
public virtual string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
IEnumerable<JsonPosition> positions = (!insideContainer)
? _stack
: _stack.Concat(new[] { _currentPosition });
return JsonPosition.BuildPath(positions);
}
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
internal JsonPosition GetPosition(int depth)
{
if (depth < _stack.Count)
return _stack[depth];
return _currentPosition;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
protected JsonReader()
{
_currentState = State.Start;
_stack = new List<JsonPosition>(4);
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
_dateParseHandling = DateParseHandling.DateTime;
_floatParseHandling = FloatParseHandling.Double;
CloseInput = true;
}
private void Push(JsonContainerType value)
{
UpdateScopeWithFinishedValue();
if (_currentPosition.Type == JsonContainerType.None)
{
_currentPosition = new JsonPosition(value);
}
else
{
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
// this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler
if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth)
{
_hasExceededMaxDepth = true;
throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
}
}
}
private JsonContainerType Pop()
{
JsonPosition oldPosition;
if (_stack.Count > 0)
{
oldPosition = _currentPosition;
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
oldPosition = _currentPosition;
_currentPosition = new JsonPosition();
}
if (_maxDepth != null && Depth <= _maxDepth)
_hasExceededMaxDepth = false;
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns>
public abstract bool Read();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract int? ReadAsInt32();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract string ReadAsString();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public abstract byte[] ReadAsBytes();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract decimal? ReadAsDecimal();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTime? ReadAsDateTime();
#if !NET20
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTimeOffset? ReadAsDateTimeOffset();
#endif
internal virtual bool ReadInternal()
{
throw new NotImplementedException();
}
#if !NET20
internal DateTimeOffset? ReadAsDateTimeOffsetInternal()
{
_readType = ReadType.ReadAsDateTimeOffset;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Date)
{
if (Value is DateTime)
SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false);
return (DateTimeOffset)Value;
}
if (t == JsonToken.Null)
return null;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
object temp;
DateTimeOffset dt;
if (DateTimeUtils.TryParseDateTime(s, DateParseHandling.DateTimeOffset, DateTimeZoneHandling, _dateFormatString, Culture, out temp))
{
dt = (DateTimeOffset)temp;
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
SetToken(JsonToken.Date, dt, false);
return dt;
}
throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
#endif
internal byte[] ReadAsBytesInternal()
{
_readType = ReadType.ReadAsBytes;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (IsWrappedInTypeObject())
{
byte[] data = ReadAsBytes();
ReadInternal();
SetToken(JsonToken.Bytes, data, false);
return data;
}
// attempt to convert possible base 64 string to bytes
if (t == JsonToken.String)
{
string s = (string)Value;
byte[] data;
Guid g;
if (s.Length == 0)
{
data = new byte[0];
}
else if (ConvertUtils.TryConvertGuid(s, out g))
{
data = g.ToByteArray();
}
else
{
data = Convert.FromBase64String(s);
}
SetToken(JsonToken.Bytes, data, false);
return data;
}
if (t == JsonToken.Null)
return null;
if (t == JsonToken.Bytes)
{
if (ValueType == typeof(Guid))
{
byte[] data = ((Guid)Value).ToByteArray();
SetToken(JsonToken.Bytes, data, false);
return data;
}
return (byte[])Value;
}
if (t == JsonToken.StartArray)
{
List<byte> data = new List<byte>();
while (ReadInternal())
{
t = TokenType;
switch (t)
{
case JsonToken.Integer:
data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
byte[] d = data.ToArray();
SetToken(JsonToken.Bytes, d, false);
return d;
case JsonToken.Comment:
// skip
break;
default:
throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
}
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal decimal? ReadAsDecimalInternal()
{
_readType = ReadType.ReadAsDecimal;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is decimal))
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false);
return (decimal)Value;
}
if (t == JsonToken.Null)
return null;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
decimal d;
if (decimal.TryParse(s, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d, false);
return d;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal int? ReadAsInt32Internal()
{
_readType = ReadType.ReadAsInt32;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is int))
SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false);
return (int)Value;
}
if (t == JsonToken.Null)
return null;
int i;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (int.TryParse(s, NumberStyles.Integer, Culture, out i))
{
SetToken(JsonToken.Integer, i, false);
return i;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
internal string ReadAsStringInternal()
{
_readType = ReadType.ReadAsString;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.String)
return (string)Value;
if (t == JsonToken.Null)
return null;
if (IsPrimitiveToken(t))
{
if (Value != null)
{
string s;
if (Value is IFormattable)
s = ((IFormattable)Value).ToString(null, Culture);
else
s = Value.ToString();
SetToken(JsonToken.String, s, false);
return s;
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal DateTime? ReadAsDateTimeInternal()
{
_readType = ReadType.ReadAsDateTime;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
} while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Date)
return (DateTime)Value;
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
DateTime dt;
object temp;
if (DateTimeUtils.TryParseDateTime(s, DateParseHandling.DateTime, DateTimeZoneHandling, _dateFormatString, Culture, out temp))
{
dt = (DateTime)temp;
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
if (TokenType == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
private bool IsWrappedInTypeObject()
{
_readType = ReadType.Read;
if (TokenType == JsonToken.StartObject)
{
if (!ReadInternal())
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
if (Value.ToString() == JsonTypeReflector.TypePropertyName)
{
ReadInternal();
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
ReadInternal();
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return true;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
return false;
}
/// <summary>
/// Skips the children of the current token.
/// </summary>
public void Skip()
{
if (TokenType == JsonToken.PropertyName)
Read();
if (IsStartToken(TokenType))
{
int depth = Depth;
while (Read() && (depth < Depth))
{
}
}
}
/// <summary>
/// Sets the current token.
/// </summary>
/// <param name="newToken">The new token.</param>
protected void SetToken(JsonToken newToken)
{
SetToken(newToken, null, true);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected void SetToken(JsonToken newToken, object value)
{
SetToken(newToken, value, true);
}
internal void SetToken(JsonToken newToken, object value, bool updateIndex)
{
_tokenType = newToken;
_value = value;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JsonContainerType.Object);
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JsonContainerType.Constructor);
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
break;
case JsonToken.PropertyName:
_currentState = State.Property;
_currentPosition.PropertyName = (string)value;
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.String:
case JsonToken.Raw:
case JsonToken.Bytes:
SetPostValueState(updateIndex);
break;
}
}
internal void SetPostValueState(bool updateIndex)
{
if (Peek() != JsonContainerType.None)
_currentState = State.PostValue;
else
SetFinished();
if (updateIndex)
UpdateScopeWithFinishedValue();
}
private void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
_currentPosition.Position++;
}
private void ValidateEnd(JsonToken endToken)
{
JsonContainerType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
if (Peek() != JsonContainerType.None)
_currentState = State.PostValue;
else
SetFinished();
}
/// <summary>
/// Sets the state based on current token type.
/// </summary>
protected void SetStateBasedOnCurrent()
{
JsonContainerType currentObject = Peek();
switch (currentObject)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Constructor;
break;
case JsonContainerType.None:
SetFinished();
break;
default:
throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
}
}
private void SetFinished()
{
if (SupportMultipleContent)
_currentState = State.Start;
else
_currentState = State.Finished;
}
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JsonContainerType.Object;
case JsonToken.EndArray:
return JsonContainerType.Array;
case JsonToken.EndConstructor:
return JsonContainerType.Constructor;
default:
throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
void IDisposable.Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
Close();
}
/// <summary>
/// Changes the <see cref="State"/> to Closed.
/// </summary>
public virtual void Close()
{
_currentState = State.Closed;
_tokenType = JsonToken.None;
_value = null;
}
}
}
| |
// Created by Paul Gonzalez Becerra
using System;
using Saserdote.Mathematics;
namespace Saserdote.Mathematics.Collision
{
public class BVCylinder:BoundingVolume
{
#region --- Field Variables ---
// Variables
public Point3f pPos;
public float height;
private float pRadius;
public readonly static BVCylinder EMPTY= new BVCylinder(Point3f.ORIGIN, 0f, 0f);
#endregion // Field Variables
#region --- Constructors ---
public BVCylinder(Point3f pmPos, float pmHeight, float pmRadius)
{
pPos= pmPos;
height= Math.Abs(pmHeight);
pRadius= Math.Abs(pmRadius);
}
public BVCylinder(float pmX, float pmY, float pmZ, float pmHeight, float pmRadius):this(new Point3f(pmX, pmY, pmZ), pmHeight, pmRadius) {}
#endregion // Constructors
#region --- Properties ---
// Gets and sets the radius of the cylinder
public float radius
{
get { return pRadius; }
set { pRadius= Math.Abs(value); }
}
// Gets the bottom position of the cylinder
public Point3f bottomPos
{
get { return pPos; }
}
// Gets the middle position of the cylinder
public Point3f midPos
{
get { return new Point3f(pPos.x, pPos.y+height*0.5f, pPos.z); }
}
// Gets the top position of the cylinder
public Point3f topPos
{
get { return new Point3f(pPos.x, pPos.y+height, pPos.z); }
}
#endregion // Properties
#region --- Inherited Properties ---
// Gets the points of the bounding volume
public override Point3f[] points
{
get
{
// Variables
Point3f[] bots= Mathx.createCircularPoints(pPos, pRadius, 16);
Point3f[] tops= Mathx.createCircularPoints(topPos, pRadius, 16);
Point3f[] total= new Point3f[bots.Length+tops.Length];
int h= 0;
for(int k= 0; k< bots.Length; k++)
total[h++]= bots[k];
for(int k= 0; k< tops.Length; k++)
total[h++]= tops[k];
return total;
}
}
// Gets and sets the position of the bounding volume
public override Point3f position
{
get { return pPos; }
set { pPos= value; }
}
#endregion // Inherited Properties
#region --- Static Methods ---
// Creates a cylindrical bounding volume from the given 3d points
public static BVCylinder createFromPoints(Point3f[] vertices)
{
if(vertices== null)
throw new ArgumentNullException();
if(vertices.Length== 0)
throw new ArgumentException("No vertices declared");
// Variables
Point3f min= new Point3f(float.MinValue);
Point3f max= new Point3f(float.MaxValue);
float r;
float h;
for(int i= 0; i< vertices.Length; i++)
{
min= Mathx.min(vertices[i], min);
max= Mathx.max(vertices[i], max);
}
r= Mathx.calcLength(max.x-min.x, max.z-min.z);
r/= 2f;
h= max.y-min.y;
min= max|min;
min.y= max.y;
return new BVCylinder(min, h, r);
}
#endregion // Static Methods
#region --- Methods ---
// Converts the bounding cylinder into a bounding box
public BVCircle toCircle()
{
return new BVCircle(pPos.x, pPos.z, pRadius);
}
// Finds if the two cylinders are intersecting each other
public bool intersects(ref BVCylinder collider)
{
if(Math.Abs(pPos.x-collider.pPos.x)> pRadius+collider.radius)
return false;
if(Math.Abs(pPos.z-collider.pPos.z)> pRadius+collider.radius)
return false;
if(pPos.y> collider.topPos.y)
return false;
if(topPos.y< collider.pPos.y)
return false;
return true;
}
public bool intersects(BVCylinder collider) { return intersects(ref collider); }
// Finds if the cylinder collides with the box
public bool intersects(ref BVBox collider)
{
return collider.intersects(this);
}
public bool intersects(BVBox collider) { return intersects(ref collider); }
// Finds if the points are contained within the cylinder
public bool contains(ref float x, ref float y, ref float z)
{
if(Math.Abs(pPos.x-x)> pRadius)
return false;
if(Math.Abs(pPos.z-z)> pRadius)
return false;
if(pPos.y> y)
return false;
if(topPos.y< y)
return false;
return true;
}
public bool contains(ref float x, ref float y, float z) { return contains(ref x, ref y, ref z); }
public bool contains(float x, float y, float z) { return contains(ref x, ref y, ref z); }
#endregion // Methods
#region --- Inherited Methods ---
// Finds if the two bounding volumes intersect each other
public override bool intersects(ref BoundingVolume collider)
{
if(collider== null)
return false;
if(collider is BVCylinder)
{
// Variables
BVCylinder cyln= (BVCylinder)collider;
return intersects(ref cyln);
}
if(collider is BVBox)
{
// Variables
BVBox bbox= (BVBox)collider;
return intersects(ref bbox);
}
return false;
}
// Finds if the given 2d vector is inside the volume
public override bool contains(ref Vector2 vec)
{
return contains(ref vec.x, ref vec.y, 0f);
}
// Finds if the given 3d vector is inside the volume
public override bool contains(ref Vector3 vec)
{
return contains(ref vec.x, ref vec.y, ref vec.z);
}
// Finds if the given 2d point is inside the volume
public override bool contains(ref Point2i pt)
{
return contains((float)pt.x, (float)pt.y, 0f);
}
public override bool contains(ref Point2f pt)
{
return contains(ref pt.x, ref pt.y, 0f);
}
// Finds if the given 3d point is inside the volume
public override bool contains(ref Point3i pt)
{
return contains((float)pt.x, (float)pt.y, (float)pt.z);
}
public override bool contains(ref Point3f pt)
{
return contains(ref pt.x, ref pt.y, ref pt.z);
}
// Gets the indices to make a line mesh out of it later in Saserdote
public override ushort[] getRendableLineIndices()
{
return new ushort[]
{
0, 15, 16, 31,
15, 14, 31, 30,
14, 13, 30, 29,
13, 12, 29, 28,
12, 11, 28, 27,
11, 10, 27, 26,
10, 9, 26, 25,
9, 8, 25, 24,
8, 7, 24, 23,
7, 6, 23, 22,
6, 5, 22, 21,
5, 4, 21, 20,
4, 3, 20, 19,
3, 2, 19, 18,
2, 1, 18, 17,
1, 0, 17, 16,
0, 16,
15, 31,
14, 30,
13, 29,
12, 28,
11, 27,
10, 26,
9, 25,
8, 24,
7, 23,
6, 22,
5, 21,
4, 20,
3, 19,
2, 18,
1, 17
};
}
#endregion // Inherited Methods
}
}
// End of File
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class HttpHeaderValueCollectionTest
{
// Note: These are not real known headers, so they won't be returned if we call HeaderDescriptor.Get().
private static readonly HeaderDescriptor knownStringHeader = (new KnownHeader("known-string-header", HttpHeaderType.General, new MockHeaderParser(typeof(string)))).Descriptor;
private static readonly HeaderDescriptor knownUriHeader = (new KnownHeader("known-uri-header", HttpHeaderType.General, new MockHeaderParser(typeof(Uri)))).Descriptor;
private static readonly Uri specialValue = new Uri("http://special/");
private static readonly Uri invalidValue = new Uri("http://invalid/");
private static readonly TransferCodingHeaderValue specialChunked = new TransferCodingHeaderValue("chunked");
// Note that this type just forwards calls to HttpHeaders. So this test method focuses on making sure
// the correct calls to HttpHeaders are made. This test suite will not test HttpHeaders functionality.
[Fact]
public void IsReadOnly_CallProperty_AlwaysFalse()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownStringHeader, headers);
Assert.False(collection.IsReadOnly);
}
[Fact]
public void Count_AddSingleValueThenQueryCount_ReturnsValueCountWithSpecialValues()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownStringHeader, headers,
"special");
Assert.Equal(0, collection.Count);
headers.Add(knownStringHeader, "value2");
Assert.Equal(1, collection.Count);
headers.Clear();
headers.Add(knownStringHeader, "special");
Assert.Equal(1, collection.Count);
headers.Add(knownStringHeader, "special");
headers.Add(knownStringHeader, "special");
Assert.Equal(3, collection.Count);
}
[Fact]
public void Count_AddMultipleValuesThenQueryCount_ReturnsValueCountWithSpecialValues()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownStringHeader, headers,
"special");
Assert.Equal(0, collection.Count);
collection.Add("value1");
headers.Add(knownStringHeader, "special");
Assert.Equal(2, collection.Count);
headers.Add(knownStringHeader, "special");
headers.Add(knownStringHeader, "value2");
headers.Add(knownStringHeader, "special");
Assert.Equal(5, collection.Count);
}
[Fact]
public void Add_CallWithNullValue_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Assert.Throws<ArgumentNullException>(() => { collection.Add(null); });
}
[Fact]
public void Add_AddValues_AllValuesAdded()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.Equal(3, collection.Count);
}
[Fact]
public void Add_UseSpecialValue_Success()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.Equal(String.Empty, headers.TransferEncoding.ToString());
headers.TransferEncoding.Add(specialChunked);
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked, headers.TransferEncoding.First());
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
}
[Fact]
public void Add_UseSpecialValueWithSpecialAlreadyPresent_AddsDuplicate()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncodingChunked = true;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
headers.TransferEncoding.Add(specialChunked);
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(2, headers.TransferEncoding.Count);
Assert.Equal("chunked, chunked", headers.TransferEncoding.ToString());
// removes first instance of
headers.TransferEncodingChunked = false;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
// does not add duplicate
headers.TransferEncodingChunked = true;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
}
[Fact]
public void ParseAdd_CallWithNullValue_NothingAdded()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.ParseAdd(null);
Assert.False(collection.IsSpecialValueSet);
Assert.Equal(0, collection.Count);
Assert.Equal(String.Empty, collection.ToString());
}
[Fact]
public void ParseAdd_AddValues_AllValuesAdded()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.ParseAdd("http://www.example.org/1/");
collection.ParseAdd("http://www.example.org/2/");
collection.ParseAdd("http://www.example.org/3/");
Assert.Equal(3, collection.Count);
}
[Fact]
public void ParseAdd_UseSpecialValue_Added()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.ParseAdd(specialValue.AbsoluteUri);
Assert.True(collection.IsSpecialValueSet);
Assert.Equal(specialValue.ToString(), collection.ToString());
}
[Fact]
public void ParseAdd_AddBadValue_Throws()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess";
Assert.Throws<FormatException>(() => { headers.WwwAuthenticate.ParseAdd(input); });
}
[Fact]
public void TryParseAdd_CallWithNullValue_NothingAdded()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
Assert.True(headers.WwwAuthenticate.TryParseAdd(null));
Assert.False(headers.WwwAuthenticate.IsSpecialValueSet);
Assert.Equal(0, headers.WwwAuthenticate.Count);
Assert.Equal(String.Empty, headers.WwwAuthenticate.ToString());
}
[Fact]
public void TryParseAdd_AddValues_AllAdded()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
Assert.True(collection.TryParseAdd("http://www.example.org/1/"));
Assert.True(collection.TryParseAdd("http://www.example.org/2/"));
Assert.True(collection.TryParseAdd("http://www.example.org/3/"));
Assert.Equal(3, collection.Count);
}
[Fact]
public void TryParseAdd_UseSpecialValue_Added()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
Assert.True(collection.TryParseAdd(specialValue.AbsoluteUri));
Assert.True(collection.IsSpecialValueSet);
Assert.Equal(specialValue.ToString(), collection.ToString());
}
[Fact]
public void TryParseAdd_AddBadValue_False()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess";
Assert.False(headers.WwwAuthenticate.TryParseAdd(input));
Assert.Equal(string.Empty, headers.WwwAuthenticate.ToString());
Assert.Equal(string.Empty, headers.ToString());
}
[Fact]
public void TryParseAdd_AddBadAfterGoodValue_False()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Negotiate"));
string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess";
Assert.False(headers.WwwAuthenticate.TryParseAdd(input));
Assert.Equal("Negotiate", headers.WwwAuthenticate.ToString());
Assert.Equal("WWW-Authenticate: Negotiate\r\n", headers.ToString());
}
[Fact]
public void Clear_AddValuesThenClear_NoElementsInCollection()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.Equal(3, collection.Count);
collection.Clear();
Assert.Equal(0, collection.Count);
}
[Fact]
public void Clear_AddValuesAndSpecialValueThenClear_EverythingCleared()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.SetSpecialValue();
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.Equal(4, collection.Count);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
collection.Clear();
Assert.Equal(0, collection.Count);
Assert.False(collection.IsSpecialValueSet, "Special value was removed by Clear().");
}
[Fact]
public void Contains_CallWithNullValue_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Assert.Throws<ArgumentNullException>(() => { collection.Contains(null); });
}
[Fact]
public void Contains_AddValuesThenCallContains_ReturnsTrueForExistingItemsFalseOtherwise()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.True(collection.Contains(new Uri("http://www.example.org/2/")), "Expected true for existing item.");
Assert.False(collection.Contains(new Uri("http://www.example.org/4/")),
"Expected false for non-existing item.");
}
[Fact]
public void Contains_UseSpecialValueWhenEmpty_False()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void Contains_UseSpecialValueWithProperty_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncodingChunked = true;
Assert.True(headers.TransferEncoding.Contains(specialChunked));
headers.TransferEncodingChunked = false;
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void Contains_UseSpecialValueWhenSpecilValueIsPresent_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncoding.Add(specialChunked);
Assert.True(headers.TransferEncoding.Contains(specialChunked));
headers.TransferEncoding.Remove(specialChunked);
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void CopyTo_CallWithStartIndexPlusElementCountGreaterArrayLength_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
Uri[] array = new Uri[2];
// startIndex + Count = 1 + 2 > array.Length
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 1); });
}
[Fact]
public void CopyTo_EmptyToEmpty_Success()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Uri[] array = new Uri[0];
collection.CopyTo(array, 0);
}
[Fact]
public void CopyTo_NoValues_DoesNotChangeArray()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Uri[] array = new Uri[4];
collection.CopyTo(array, 0);
for (int i = 0; i < array.Length; i++)
{
Assert.Null(array[i]);
}
}
[Fact]
public void CopyTo_AddSingleValue_ContainsSingleValue()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/"));
Uri[] array = new Uri[1];
collection.CopyTo(array, 0);
Assert.Equal(new Uri("http://www.example.org/"), array[0]);
// Now only set the special value: nothing should be added to the array.
headers.Clear();
headers.Add(knownUriHeader, specialValue.ToString());
array[0] = null;
collection.CopyTo(array, 0);
Assert.Equal(specialValue, array[0]);
}
[Fact]
public void CopyTo_AddMultipleValues_ContainsAllValuesInTheRightOrder()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Uri[] array = new Uri[5];
collection.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new Uri("http://www.example.org/1/"), array[1]);
Assert.Equal(new Uri("http://www.example.org/2/"), array[2]);
Assert.Equal(new Uri("http://www.example.org/3/"), array[3]);
Assert.Null(array[4]);
}
[Fact]
public void CopyTo_AddValuesAndSpecialValue_AllValuesCopied()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.SetSpecialValue();
collection.Add(new Uri("http://www.example.org/3/"));
Uri[] array = new Uri[5];
collection.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new Uri("http://www.example.org/1/"), array[1]);
Assert.Equal(new Uri("http://www.example.org/2/"), array[2]);
Assert.Equal(specialValue, array[3]);
Assert.Equal(new Uri("http://www.example.org/3/"), array[4]);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void CopyTo_OnlySpecialValue_Copied()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.SetSpecialValue();
headers.Add(knownUriHeader, specialValue.ToString());
headers.Add(knownUriHeader, specialValue.ToString());
headers.Add(knownUriHeader, specialValue.ToString());
Uri[] array = new Uri[4];
array[0] = null;
collection.CopyTo(array, 0);
Assert.Equal(specialValue, array[0]);
Assert.Equal(specialValue, array[1]);
Assert.Equal(specialValue, array[2]);
Assert.Equal(specialValue, array[3]);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void CopyTo_OnlySpecialValueEmptyDestination_Copied()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.SetSpecialValue();
headers.Add(knownUriHeader, specialValue.ToString());
Uri[] array = new Uri[2];
collection.CopyTo(array, 0);
Assert.Equal(specialValue, array[0]);
Assert.Equal(specialValue, array[1]);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void CopyTo_ArrayTooSmall_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownStringHeader, headers,
"special");
string[] array = new string[1];
array[0] = null;
collection.CopyTo(array, 0); // no exception
Assert.Null(array[0]);
Assert.Throws<ArgumentNullException>(() => { collection.CopyTo(null, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, -1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, 2); });
headers.Add(knownStringHeader, "special");
array = new string[0];
AssertExtensions.Throws<ArgumentException>(null, () => { collection.CopyTo(array, 0); });
headers.Add(knownStringHeader, "special");
headers.Add(knownStringHeader, "special");
array = new string[1];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 0); });
headers.Add(knownStringHeader, "value1");
array = new string[0];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 0); });
headers.Add(knownStringHeader, "value2");
array = new string[1];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 0); });
array = new string[2];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 1); });
}
[Fact]
public void Remove_CallWithNullValue_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Assert.Throws<ArgumentNullException>(() => { collection.Remove(null); });
}
[Fact]
public void Remove_AddValuesThenCallRemove_ReturnsTrueWhenRemovingExistingValuesFalseOtherwise()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.True(collection.Remove(new Uri("http://www.example.org/2/")), "Expected true for existing item.");
Assert.False(collection.Remove(new Uri("http://www.example.org/4/")),
"Expected false for non-existing item.");
}
[Fact]
public void Remove_UseSpecialValue_FalseWhenEmpty()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.TransferEncoding.Remove(specialChunked));
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
}
[Fact]
public void Remove_UseSpecialValueWhenSetWithProperty_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncodingChunked = true;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.True(headers.TransferEncoding.Contains(specialChunked));
Assert.True(headers.TransferEncoding.Remove(specialChunked));
Assert.False((bool)headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void Remove_UseSpecialValueWhenAdded_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncoding.Add(specialChunked);
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.True(headers.TransferEncoding.Contains(specialChunked));
Assert.True(headers.TransferEncoding.Remove(specialChunked));
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void GetEnumerator_AddSingleValueAndGetEnumerator_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/"));
bool started = false;
foreach (var item in collection)
{
Assert.False(started, "We have more than one element returned by the enumerator.");
Assert.Equal(new Uri("http://www.example.org/"), item);
}
}
[Fact]
public void GetEnumerator_AddValuesAndGetEnumerator_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
int i = 1;
foreach (var item in collection)
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
[Fact]
public void GetEnumerator_NoValues_EmptyEnumerator()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
IEnumerator<Uri> enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext(), "No items expected in enumerator.");
}
[Fact]
public void GetEnumerator_AddValuesAndGetEnumeratorFromInterface_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
System.Collections.IEnumerable enumerable = collection;
int i = 1;
foreach (var item in enumerable)
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
[Fact]
public void GetEnumerator_AddValuesAndSpecialValueAndGetEnumeratorFromInterface_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
collection.SetSpecialValue();
System.Collections.IEnumerable enumerable = collection;
// The "special value" should be ignored and not part of the resulting collection.
int i = 1;
bool specialFound = false;
foreach (var item in enumerable)
{
if (item.Equals(specialValue))
{
specialFound = true;
}
else
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
Assert.True(specialFound);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void GetEnumerator_AddValuesAndSpecialValue_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.SetSpecialValue();
collection.Add(new Uri("http://www.example.org/3/"));
System.Collections.IEnumerable enumerable = collection;
// The special value we added above, must be part of the collection returned by GetEnumerator().
int i = 1;
bool specialFound = false;
foreach (var item in enumerable)
{
if (item.Equals(specialValue))
{
specialFound = true;
}
else
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
Assert.True(specialFound);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void IsSpecialValueSet_NoSpecialValueUsed_ReturnsFalse()
{
// Create a new collection _without_ specifying a special value.
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
null, null);
Assert.False(collection.IsSpecialValueSet,
"Special value is set even though collection doesn't define a special value.");
}
[Fact]
public void RemoveSpecialValue_AddRemoveSpecialValue_SpecialValueGetsRemoved()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.SetSpecialValue();
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
Assert.Equal(1, headers.GetValues(knownUriHeader).Count());
collection.RemoveSpecialValue();
Assert.False(collection.IsSpecialValueSet, "Special value is set.");
// Since the only header value was the "special value", removing it will remove the whole header
// from the collection.
Assert.False(headers.Contains(knownUriHeader));
}
[Fact]
public void RemoveSpecialValue_AddValueAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/"));
collection.SetSpecialValue();
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
Assert.Equal(2, headers.GetValues(knownUriHeader).Count());
collection.RemoveSpecialValue();
Assert.False(collection.IsSpecialValueSet, "Special value is set.");
Assert.Equal(1, headers.GetValues(knownUriHeader).Count());
}
[Fact]
public void RemoveSpecialValue_AddTwoValuesAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.SetSpecialValue();
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
Assert.Equal(3, headers.GetValues(knownUriHeader).Count());
// The difference between this test and the previous one is that HttpHeaders in this case will use
// a List<T> to store the two remaining values, whereas in the previous case it will just store
// the remaining value (no list).
collection.RemoveSpecialValue();
Assert.False(collection.IsSpecialValueSet, "Special value is set.");
Assert.Equal(2, headers.GetValues(knownUriHeader).Count());
}
[Fact]
public void Ctor_ProvideValidator_ValidatorIsUsedWhenAddingValues()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
MockValidator);
// Adding an arbitrary Uri should not throw.
collection.Add(new Uri("http://some/"));
// When we add 'invalidValue' our MockValidator will throw.
Assert.Throws<MockException>(() => { collection.Add(invalidValue); });
}
[Fact]
public void Ctor_ProvideValidator_ValidatorIsUsedWhenRemovingValues()
{
// Use different ctor overload than in previous test to make sure all ctor overloads work correctly.
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue, MockValidator);
// When we remove 'invalidValue' our MockValidator will throw.
Assert.Throws<MockException>(() => { collection.Remove(invalidValue); });
}
[Fact]
public void ToString_SpecialValues_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
request.Headers.TransferEncodingChunked = true;
string result = request.Headers.TransferEncoding.ToString();
Assert.Equal("chunked", result);
request.Headers.ExpectContinue = true;
result = request.Headers.Expect.ToString();
Assert.Equal("100-continue", result);
request.Headers.ConnectionClose = true;
result = request.Headers.Connection.ToString();
Assert.Equal("close", result);
}
[Fact]
public void ToString_SpecialValueAndExtra_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
request.Headers.Add(HttpKnownHeaderNames.TransferEncoding, "bla1");
request.Headers.TransferEncodingChunked = true;
request.Headers.Add(HttpKnownHeaderNames.TransferEncoding, "bla2");
string result = request.Headers.TransferEncoding.ToString();
Assert.Equal("bla1, chunked, bla2", result);
}
[Fact]
public void ToString_SingleValue_Success()
{
using (var response = new HttpResponseMessage())
{
string input = "Basic";
response.Headers.Add(HttpKnownHeaderNames.WWWAuthenticate, input);
string result = response.Headers.WwwAuthenticate.ToString();
Assert.Equal(input, result);
}
}
[Fact]
public void ToString_MultipleValue_Success()
{
using (var response = new HttpResponseMessage())
{
string input = "Basic, NTLM, Negotiate, Custom";
response.Headers.Add(HttpKnownHeaderNames.WWWAuthenticate, input);
string result = response.Headers.WwwAuthenticate.ToString();
Assert.Equal(input, result);
}
}
[Fact]
public void ToString_EmptyValue_Success()
{
using (var response = new HttpResponseMessage())
{
string result = response.Headers.WwwAuthenticate.ToString();
Assert.Equal(string.Empty, result);
}
}
#region Helper methods
private static void MockValidator(HttpHeaderValueCollection<Uri> collection, Uri value)
{
if (value == invalidValue)
{
throw new MockException();
}
}
public class MockException : Exception
{
public MockException() { }
public MockException(string message) : base(message) { }
public MockException(string message, Exception inner) : base(message, inner) { }
}
private class MockHeaders : HttpHeaders
{
public MockHeaders()
{
}
}
private class MockHeaderParser : HttpHeaderParser
{
private static MockComparer comparer = new MockComparer();
private Type valueType;
public override IEqualityComparer Comparer
{
get { return comparer; }
}
public MockHeaderParser(Type valueType)
: base(true)
{
Assert.Contains(valueType, new[] { typeof(string), typeof(Uri) });
this.valueType = valueType;
}
public override bool TryParseValue(string value, object storeValue, ref int index, out object parsedValue)
{
parsedValue = null;
if (value == null)
{
return true;
}
index = value.Length;
// Just return the raw string (as string or Uri depending on the value type)
parsedValue = (valueType == typeof(Uri) ? (object)new Uri(value) : value);
return true;
}
}
private class MockComparer : IEqualityComparer
{
public int EqualsCount { get; private set; }
public int GetHashCodeCount { get; private set; }
#region IEqualityComparer Members
public new bool Equals(object x, object y)
{
EqualsCount++;
return x.Equals(y);
}
public int GetHashCode(object obj)
{
GetHashCodeCount++;
return obj.GetHashCode();
}
#endregion
}
#endregion
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
// James Driscoll, mailto:jamesdriscoll@btinternet.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id$")]
namespace Elmah
{
#region Imports
using System;
using System.Configuration;
using System.Data.Common;
using System.IO;
using System.Runtime.CompilerServices;
using IDictionary = System.Collections.IDictionary;
#endregion
/// <summary>
/// Helper class for resolving connection strings.
/// </summary>
internal class ConnectionStringHelper
{
/// <summary>
/// Gets the connection string from the given configuration
/// dictionary.
/// </summary>
public static string GetConnectionString(IDictionary config)
{
Debug.Assert(config != null);
#if !NET_1_1 && !NET_1_0
//
// First look for a connection string name that can be
// subsequently indexed into the <connectionStrings> section of
// the configuration to get the actual connection string.
//
string connectionStringName = (string)config["connectionStringName"] ?? string.Empty;
if (connectionStringName.Length > 0)
{
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[connectionStringName];
if (settings == null)
return string.Empty;
return settings.ConnectionString ?? string.Empty;
}
#endif
//
// Connection string name not found so see if a connection
// string was given directly.
//
string connectionString = Mask.NullString((string)config["connectionString"]);
if (connectionString.Length > 0)
return connectionString;
//
// As a last resort, check for another setting called
// connectionStringAppKey. The specifies the key in
// <appSettings> that contains the actual connection string to
// be used.
//
string connectionStringAppKey = Mask.NullString((string)config["connectionStringAppKey"]);
if (connectionStringAppKey.Length == 0)
return string.Empty;
return Configuration.AppSettings[connectionStringAppKey];
}
#if NET_1_1 || NET_1_0
/// <summary>
/// Extracts the Data Source file path from a connection string
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <returns>File path to the Data Source element of a connection string</returns>
public static string GetDataSourceFilePath(string connectionString)
{
Debug.AssertStringNotEmpty(connectionString);
string result = string.Empty;
string loweredConnectionString = connectionString.ToLower();
int dataSourcePosition = loweredConnectionString.IndexOf("data source");
if (dataSourcePosition >= 0)
{
int equalsPosition = loweredConnectionString.IndexOf('=', dataSourcePosition);
if (equalsPosition >= 0)
{
int semiColonPosition = loweredConnectionString.IndexOf(';', equalsPosition);
if (semiColonPosition < equalsPosition)
result = connectionString.Substring(equalsPosition + 1);
else
result = connectionString.Substring(equalsPosition + 1, semiColonPosition - equalsPosition - 1);
result = result.Trim();
char firstChar = result[0];
char lastChar = result[result.Length - 1];
if (firstChar == lastChar && (firstChar == '\'' || firstChar == '\"') && result.Length > 1)
{
result = result.Substring(1, result.Length - 2);
}
}
}
return result;
}
#else
/// <summary>
/// Extracts the Data Source file path from a connection string
/// ~/ gets resolved as does |DataDirectory|
/// </summary>
public static string GetDataSourceFilePath(string connectionString)
{
Debug.AssertStringNotEmpty(connectionString);
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
return GetDataSourceFilePath(builder, connectionString);
}
/// <summary>
/// Gets the connection string from the given configuration,
/// resolving ~/ and DataDirectory if necessary.
/// </summary>
public static string GetConnectionString(IDictionary config, bool resolveDataSource)
{
string connectionString = GetConnectionString(config);
return resolveDataSource ? GetResolvedConnectionString(connectionString) : connectionString;
}
/// <summary>
/// Converts the supplied connection string so that the Data Source
/// specification contains the full path and not ~/ or DataDirectory.
/// </summary>
public static string GetResolvedConnectionString(string connectionString)
{
Debug.AssertStringNotEmpty(connectionString);
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
builder["Data Source"] = GetDataSourceFilePath(builder, connectionString);
return builder.ToString();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static string MapPath(string path)
{
return System.Web.Hosting.HostingEnvironment.MapPath(path);
}
private static string GetDataSourceFilePath(DbConnectionStringBuilder builder, string connectionString)
{
builder.ConnectionString = connectionString;
if (!builder.ContainsKey("Data Source"))
throw new ArgumentException("A 'Data Source' parameter was expected in the supplied connection string, but it was not found.");
string dataSource = builder["Data Source"].ToString();
return ResolveDataSourceFilePath(dataSource);
}
private static readonly char[] _dirSeparators = new char[] { Path.DirectorySeparatorChar };
private static string ResolveDataSourceFilePath(string path)
{
const string dataDirectoryMacroString = "|DataDirectory|";
//
// Check to see if it starts with a ~/ and if so map it and return it.
//
if (path.StartsWith("~/"))
return MapPath(path);
//
// Else see if it uses the DataDirectory macro/substitution
// string, and if so perform the appropriate substitution.
//
if (!path.StartsWith(dataDirectoryMacroString, StringComparison.OrdinalIgnoreCase))
return path;
//
// Look-up the data directory from the current AppDomain.
// See "Working with local databases" for more:
// http://blogs.msdn.com/smartclientdata/archive/2005/08/26/456886.aspx
//
string baseDirectory = AppDomain.CurrentDomain.GetData("DataDirectory") as string;
//
// If not, try the current AppDomain's base directory.
//
if (string.IsNullOrEmpty(baseDirectory))
baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
//
// Piece the file path back together, taking leading and
// trailing backslashes into account to avoid duplication.
//
return Mask.NullString(baseDirectory).TrimEnd(_dirSeparators)
+ Path.DirectorySeparatorChar
+ path.Substring(dataDirectoryMacroString.Length).TrimStart(_dirSeparators);
}
#endif
private ConnectionStringHelper() {}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Redshift.Model
{
/// <summary>
/// Container for the parameters to the DescribeClusterSnapshots operation.
/// Returns one or more snapshot objects, which contain metadata about your cluster snapshots.
/// By default, this operation returns information about all snapshots of all clusters
/// that are owned by you AWS customer account. No information is returned for snapshots
/// owned by inactive AWS customer accounts.
///
///
/// <para>
/// If you specify both tag keys and tag values in the same request, Amazon Redshift returns
/// all snapshots that match any combination of the specified keys and values. For example,
/// if you have <code>owner</code> and <code>environment</code> for tag keys, and <code>admin</code>
/// and <code>test</code> for tag values, all snapshots that have any combination of those
/// values are returned. Only snapshots that you own are returned in the response; shared
/// snapshots are not returned with the tag key and tag value request parameters.
/// </para>
///
/// <para>
/// If both tag keys and values are omitted from the request, snapshots are returned regardless
/// of whether they have tag keys or values associated with them.
/// </para>
/// </summary>
public partial class DescribeClusterSnapshotsRequest : AmazonRedshiftRequest
{
private string _clusterIdentifier;
private DateTime? _endTime;
private string _marker;
private int? _maxRecords;
private string _ownerAccount;
private string _snapshotIdentifier;
private string _snapshotType;
private DateTime? _startTime;
private List<string> _tagKeys = new List<string>();
private List<string> _tagValues = new List<string>();
/// <summary>
/// Gets and sets the property ClusterIdentifier.
/// <para>
/// The identifier of the cluster for which information about snapshots is requested.
///
/// </para>
/// </summary>
public string ClusterIdentifier
{
get { return this._clusterIdentifier; }
set { this._clusterIdentifier = value; }
}
// Check to see if ClusterIdentifier property is set
internal bool IsSetClusterIdentifier()
{
return this._clusterIdentifier != null;
}
/// <summary>
/// Gets and sets the property EndTime.
/// <para>
/// A time value that requests only snapshots created at or before the specified time.
/// The time value is specified in ISO 8601 format. For more information about ISO 8601,
/// go to the <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO8601 Wikipedia page.</a>
///
/// </para>
///
/// <para>
/// Example: <code>2012-07-16T18:00:00Z</code>
/// </para>
/// </summary>
public DateTime EndTime
{
get { return this._endTime.GetValueOrDefault(); }
set { this._endTime = value; }
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this._endTime.HasValue;
}
/// <summary>
/// Gets and sets the property Marker.
/// <para>
/// An optional parameter that specifies the starting point to return a set of response
/// records. When the results of a <a>DescribeClusterSnapshots</a> request exceed the
/// value specified in <code>MaxRecords</code>, AWS returns a value in the <code>Marker</code>
/// field of the response. You can retrieve the next set of response records by providing
/// the returned marker value in the <code>Marker</code> parameter and retrying the request.
///
/// </para>
/// </summary>
public string Marker
{
get { return this._marker; }
set { this._marker = value; }
}
// Check to see if Marker property is set
internal bool IsSetMarker()
{
return this._marker != null;
}
/// <summary>
/// Gets and sets the property MaxRecords.
/// <para>
/// The maximum number of response records to return in each call. If the number of remaining
/// response records exceeds the specified <code>MaxRecords</code> value, a value is returned
/// in a <code>marker</code> field of the response. You can retrieve the next set of records
/// by retrying the command with the returned marker value.
/// </para>
///
/// <para>
/// Default: <code>100</code>
/// </para>
///
/// <para>
/// Constraints: minimum 20, maximum 100.
/// </para>
/// </summary>
public int MaxRecords
{
get { return this._maxRecords.GetValueOrDefault(); }
set { this._maxRecords = value; }
}
// Check to see if MaxRecords property is set
internal bool IsSetMaxRecords()
{
return this._maxRecords.HasValue;
}
/// <summary>
/// Gets and sets the property OwnerAccount.
/// <para>
/// The AWS customer account used to create or copy the snapshot. Use this field to filter
/// the results to snapshots owned by a particular account. To describe snapshots you
/// own, either specify your AWS customer account, or do not specify the parameter.
/// </para>
/// </summary>
public string OwnerAccount
{
get { return this._ownerAccount; }
set { this._ownerAccount = value; }
}
// Check to see if OwnerAccount property is set
internal bool IsSetOwnerAccount()
{
return this._ownerAccount != null;
}
/// <summary>
/// Gets and sets the property SnapshotIdentifier.
/// <para>
/// The snapshot identifier of the snapshot about which to return information.
/// </para>
/// </summary>
public string SnapshotIdentifier
{
get { return this._snapshotIdentifier; }
set { this._snapshotIdentifier = value; }
}
// Check to see if SnapshotIdentifier property is set
internal bool IsSetSnapshotIdentifier()
{
return this._snapshotIdentifier != null;
}
/// <summary>
/// Gets and sets the property SnapshotType.
/// <para>
/// The type of snapshots for which you are requesting information. By default, snapshots
/// of all types are returned.
/// </para>
///
/// <para>
/// Valid Values: <code>automated</code> | <code>manual</code>
/// </para>
/// </summary>
public string SnapshotType
{
get { return this._snapshotType; }
set { this._snapshotType = value; }
}
// Check to see if SnapshotType property is set
internal bool IsSetSnapshotType()
{
return this._snapshotType != null;
}
/// <summary>
/// Gets and sets the property StartTime.
/// <para>
/// A value that requests only snapshots created at or after the specified time. The
/// time value is specified in ISO 8601 format. For more information about ISO 8601, go
/// to the <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO8601 Wikipedia page.</a>
///
/// </para>
///
/// <para>
/// Example: <code>2012-07-16T18:00:00Z</code>
/// </para>
/// </summary>
public DateTime StartTime
{
get { return this._startTime.GetValueOrDefault(); }
set { this._startTime = value; }
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this._startTime.HasValue;
}
/// <summary>
/// Gets and sets the property TagKeys.
/// <para>
/// A tag key or keys for which you want to return all matching cluster snapshots that
/// are associated with the specified key or keys. For example, suppose that you have
/// snapshots that are tagged with keys called <code>owner</code> and <code>environment</code>.
/// If you specify both of these tag keys in the request, Amazon Redshift returns a response
/// with the snapshots that have either or both of these tag keys associated with them.
/// </para>
/// </summary>
public List<string> TagKeys
{
get { return this._tagKeys; }
set { this._tagKeys = value; }
}
// Check to see if TagKeys property is set
internal bool IsSetTagKeys()
{
return this._tagKeys != null && this._tagKeys.Count > 0;
}
/// <summary>
/// Gets and sets the property TagValues.
/// <para>
/// A tag value or values for which you want to return all matching cluster snapshots
/// that are associated with the specified tag value or values. For example, suppose that
/// you have snapshots that are tagged with values called <code>admin</code> and <code>test</code>.
/// If you specify both of these tag values in the request, Amazon Redshift returns a
/// response with the snapshots that have either or both of these tag values associated
/// with them.
/// </para>
/// </summary>
public List<string> TagValues
{
get { return this._tagValues; }
set { this._tagValues = value; }
}
// Check to see if TagValues property is set
internal bool IsSetTagValues()
{
return this._tagValues != null && this._tagValues.Count > 0;
}
}
}
| |
using MonoMod.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection.Emit;
namespace HarmonyLib
{
/// <summary>An abstract wrapper around OpCode and their operands. Used by transpilers</summary>
///
public class CodeInstruction
{
internal static class State
{
internal static readonly Dictionary<int, Delegate> closureCache = new Dictionary<int, Delegate>();
}
/// <summary>The opcode</summary>
///
public OpCode opcode;
/// <summary>The operand</summary>
///
public object operand;
/// <summary>All labels defined on this instruction</summary>
///
public List<Label> labels = new List<Label>();
/// <summary>All exception block boundaries defined on this instruction</summary>
///
public List<ExceptionBlock> blocks = new List<ExceptionBlock>();
// Internal parameterless constructor that AccessTools.CreateInstance can use, ensuring that labels/blocks are initialized.
internal CodeInstruction()
{
}
/// <summary>Creates a new CodeInstruction with a given opcode and optional operand</summary>
/// <param name="opcode">The opcode</param>
/// <param name="operand">The operand</param>
///
public CodeInstruction(OpCode opcode, object operand = null)
{
this.opcode = opcode;
this.operand = operand;
}
/// <summary>Create a full copy (including labels and exception blocks) of a CodeInstruction</summary>
/// <param name="instruction">The <see cref="CodeInstruction"/> to copy</param>
///
public CodeInstruction(CodeInstruction instruction)
{
opcode = instruction.opcode;
operand = instruction.operand;
labels = instruction.labels.ToList();
blocks = instruction.blocks.ToList();
}
// --- CLONING
/// <summary>Clones a CodeInstruction and resets its labels and exception blocks</summary>
/// <returns>A lightweight copy of this code instruction</returns>
///
public CodeInstruction Clone()
{
return new CodeInstruction(this)
{
labels = new List<Label>(),
blocks = new List<ExceptionBlock>()
};
}
/// <summary>Clones a CodeInstruction, resets labels and exception blocks and sets its opcode</summary>
/// <param name="opcode">The opcode</param>
/// <returns>A copy of this CodeInstruction with a new opcode</returns>
///
public CodeInstruction Clone(OpCode opcode)
{
var instruction = Clone();
instruction.opcode = opcode;
return instruction;
}
/// <summary>Clones a CodeInstruction, resets labels and exception blocks and sets its operand</summary>
/// <param name="operand">The operand</param>
/// <returns>A copy of this CodeInstruction with a new operand</returns>
///
public CodeInstruction Clone(object operand)
{
var instruction = Clone();
instruction.operand = operand;
return instruction;
}
// --- CALLING
/// <summary>Creates a CodeInstruction calling a method (CALL)</summary>
/// <param name="type">The class/type where the method is declared</param>
/// <param name="name">The name of the method (case sensitive)</param>
/// <param name="parameters">Optional parameters to target a specific overload of the method</param>
/// <param name="generics">Optional list of types that define the generic version of the method</param>
/// <returns>A code instruction that calls the method matching the arguments</returns>
///
public static CodeInstruction Call(Type type, string name, Type[] parameters = null, Type[] generics = null)
{
var method = AccessTools.Method(type, name, parameters, generics);
if (method is null) throw new ArgumentException($"No method found for type={type}, name={name}, parameters={parameters.Description()}, generics={generics.Description()}");
return new CodeInstruction(OpCodes.Call, method);
}
/// <summary>Creates a CodeInstruction calling a method (CALL)</summary>
/// <param name="typeColonMethodname">The target method in the form <c>TypeFullName:MethodName</c>, where the type name matches a form recognized by <a href="https://docs.microsoft.com/en-us/dotnet/api/system.type.gettype">Type.GetType</a> like <c>Some.Namespace.Type</c>.</param>
/// <param name="parameters">Optional parameters to target a specific overload of the method</param>
/// <param name="generics">Optional list of types that define the generic version of the method</param>
/// <returns>A code instruction that calls the method matching the arguments</returns>
///
public static CodeInstruction Call(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
{
var method = AccessTools.Method(typeColonMethodname, parameters, generics);
if (method is null) throw new ArgumentException($"No method found for {typeColonMethodname}, parameters={parameters.Description()}, generics={generics.Description()}");
return new CodeInstruction(OpCodes.Call, method);
}
/// <summary>Creates a CodeInstruction calling a method (CALL)</summary>
/// <param name="expression">The lambda expression using the method</param>
/// <returns></returns>
///
public static CodeInstruction Call(Expression<Action> expression)
{
return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
}
/// <summary>Creates a CodeInstruction calling a method (CALL)</summary>
/// <param name="expression">The lambda expression using the method</param>
/// <returns></returns>
///
public static CodeInstruction Call<T>(Expression<Action<T>> expression)
{
return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
}
/// <summary>Creates a CodeInstruction calling a method (CALL)</summary>
/// <param name="expression">The lambda expression using the method</param>
/// <returns></returns>
///
public static CodeInstruction Call<T, TResult>(Expression<Func<T, TResult>> expression)
{
return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
}
/// <summary>Creates a CodeInstruction calling a method (CALL)</summary>
/// <param name="expression">The lambda expression using the method</param>
/// <returns></returns>
///
public static CodeInstruction Call(LambdaExpression expression)
{
return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
}
/// <summary>Returns an instruction to call the specified closure</summary>
/// <typeparam name="T">The delegate type to emit</typeparam>
/// <param name="closure">The closure that defines the method to call</param>
/// <returns>A <see cref="CodeInstruction"/> that calls the closure as a method</returns>
///
public static CodeInstruction CallClosure<T>(T closure) where T : Delegate
{
if (closure.Method.IsStatic && closure.Target == null)
return new CodeInstruction(OpCodes.Call, closure.Method);
var parameters = closure.Method.GetParameters().Select(x => x.ParameterType).ToArray();
var closureMethod = new DynamicMethodDefinition(closure.Method.Name, closure.Method.ReturnType, parameters);
var il = closureMethod.GetILGenerator();
var targetType = closure.Target.GetType();
var preserveContext = closure.Target != null && targetType.GetFields().Any(x => !x.IsStatic);
if (preserveContext)
{
var n = State.closureCache.Count;
State.closureCache[n] = closure;
il.Emit(OpCodes.Ldsfld, AccessTools.Field(typeof(Transpilers), nameof(State.closureCache)));
il.Emit(OpCodes.Ldc_I4, n);
il.Emit(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Dictionary<int, Delegate>), "Item"));
}
else
{
if (closure.Target == null)
il.Emit(OpCodes.Ldnull);
else
il.Emit(OpCodes.Newobj, AccessTools.FirstConstructor(targetType, x => x.IsStatic == false && x.GetParameters().Length == 0));
il.Emit(OpCodes.Ldftn, closure.Method);
il.Emit(OpCodes.Newobj, AccessTools.Constructor(typeof(T), new[] { typeof(object), typeof(IntPtr) }));
}
for (var i = 0; i < parameters.Length; i++)
il.Emit(OpCodes.Ldarg, i);
il.Emit(OpCodes.Callvirt, AccessTools.Method(typeof(T), nameof(Action.Invoke)));
il.Emit(OpCodes.Ret);
return new CodeInstruction(OpCodes.Call, closureMethod.Generate());
}
// --- FIELDS
/// <summary>Creates a CodeInstruction loading a field (LD[S]FLD[A])</summary>
/// <param name="type">The class/type where the field is defined</param>
/// <param name="name">The name of the field (case sensitive)</param>
/// <param name="useAddress">Use address of field</param>
/// <returns></returns>
public static CodeInstruction LoadField(Type type, string name, bool useAddress = false)
{
var field = AccessTools.Field(type, name);
if (field is null) throw new ArgumentException($"No field found for {type} and {name}");
return new CodeInstruction(useAddress ? (field.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda) : (field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld), field);
}
/// <summary>Creates a CodeInstruction storing to a field (ST[S]FLD)</summary>
/// <param name="type">The class/type where the field is defined</param>
/// <param name="name">The name of the field (case sensitive)</param>
/// <returns></returns>
public static CodeInstruction StoreField(Type type, string name)
{
var field = AccessTools.Field(type, name);
if (field is null) throw new ArgumentException($"No field found for {type} and {name}");
return new CodeInstruction(field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, field);
}
// --- TOSTRING
/// <summary>Returns a string representation of the code instruction</summary>
/// <returns>A string representation of the code instruction</returns>
///
public override string ToString()
{
var list = new List<string>();
foreach (var label in labels)
list.Add($"Label{label.GetHashCode()}");
foreach (var block in blocks)
list.Add($"EX_{block.blockType.ToString().Replace("Block", "")}");
var extras = list.Count > 0 ? $" [{string.Join(", ", list.ToArray())}]" : "";
var operandStr = Emitter.FormatArgument(operand);
if (operandStr.Length > 0) operandStr = " " + operandStr;
return opcode + operandStr + extras;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworkPeeringsOperations operations.
/// </summary>
internal partial class VirtualNetworkPeeringsOperations : IServiceOperations<NetworkClient>, IVirtualNetworkPeeringsOperations
{
/// <summary>
/// Initializes a new instance of the VirtualNetworkPeeringsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VirtualNetworkPeeringsOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetworkPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetworkPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VirtualNetworkPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualNetworkPeering> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all virtual network peerings in a virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetworkPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetworkPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetworkPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetworkPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (virtualNetworkPeeringParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("virtualNetworkPeeringParameters", virtualNetworkPeeringParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(virtualNetworkPeeringParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(virtualNetworkPeeringParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetworkPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all virtual network peerings in a virtual network.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetworkPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetworkPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetworkPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace _1._3.Web_Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
namespace SwarmNLP
{
partial class ProblemForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProblemForm));
this.SetButton = new System.Windows.Forms.Button();
this.DimensionBox = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.ConstraintsList = new System.Windows.Forms.ListBox();
this.RemoveConstraintLink = new System.Windows.Forms.LinkLabel();
this.AddConstraintLink = new System.Windows.Forms.LinkLabel();
this.TimeLabel = new System.Windows.Forms.Label();
this.TimeBox = new System.Windows.Forms.TextBox();
this.EditConstraintLink = new System.Windows.Forms.LinkLabel();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.label4 = new System.Windows.Forms.Label();
this.EditFunctionLink = new System.Windows.Forms.LinkLabel();
this.AddFunctionLink = new System.Windows.Forms.LinkLabel();
this.FunctionList = new System.Windows.Forms.ListBox();
this.RemoveFunctionLink = new System.Windows.Forms.LinkLabel();
this.TimeCheckBox = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.DimensionBox)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// SetButton
//
this.SetButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.SetButton.Location = new System.Drawing.Point(310, 337);
this.SetButton.Name = "SetButton";
this.SetButton.Size = new System.Drawing.Size(75, 23);
this.SetButton.TabIndex = 1;
this.SetButton.Text = "Set";
this.SetButton.UseVisualStyleBackColor = true;
this.SetButton.Click += new System.EventHandler(this.SetButton_Click);
//
// DimensionBox
//
this.DimensionBox.Location = new System.Drawing.Point(189, 12);
this.DimensionBox.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.DimensionBox.Name = "DimensionBox";
this.DimensionBox.Size = new System.Drawing.Size(57, 20);
this.DimensionBox.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(17, 14);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(169, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Number of Dimensions x1, x2 .. xN";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(3, 10);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(62, 13);
this.label3.TabIndex = 6;
this.label3.Text = "Constraints:";
//
// ConstraintsList
//
this.ConstraintsList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ConstraintsList.FormattingEnabled = true;
this.ConstraintsList.IntegralHeight = false;
this.ConstraintsList.Location = new System.Drawing.Point(6, 26);
this.ConstraintsList.Name = "ConstraintsList";
this.ConstraintsList.Size = new System.Drawing.Size(364, 88);
this.ConstraintsList.TabIndex = 7;
this.ConstraintsList.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.ConstraintsList_MouseDoubleClick);
//
// RemoveConstraintLink
//
this.RemoveConstraintLink.AutoSize = true;
this.RemoveConstraintLink.Location = new System.Drawing.Point(131, 10);
this.RemoveConstraintLink.Name = "RemoveConstraintLink";
this.RemoveConstraintLink.Size = new System.Drawing.Size(92, 13);
this.RemoveConstraintLink.TabIndex = 11;
this.RemoveConstraintLink.TabStop = true;
this.RemoveConstraintLink.Text = "Remove Selected";
this.RemoveConstraintLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.RemoveLink_LinkClicked);
//
// AddConstraintLink
//
this.AddConstraintLink.AutoSize = true;
this.AddConstraintLink.Location = new System.Drawing.Point(68, 10);
this.AddConstraintLink.Name = "AddConstraintLink";
this.AddConstraintLink.Size = new System.Drawing.Size(26, 13);
this.AddConstraintLink.TabIndex = 12;
this.AddConstraintLink.TabStop = true;
this.AddConstraintLink.Text = "Add";
this.AddConstraintLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.AddLink_LinkClicked);
//
// TimeLabel
//
this.TimeLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.TimeLabel.AutoSize = true;
this.TimeLabel.Location = new System.Drawing.Point(37, 315);
this.TimeLabel.Name = "TimeLabel";
this.TimeLabel.Size = new System.Drawing.Size(138, 13);
this.TimeLabel.TabIndex = 14;
this.TimeLabel.Text = "Increment t per run cycle by";
//
// TimeBox
//
this.TimeBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.TimeBox.Location = new System.Drawing.Point(181, 312);
this.TimeBox.Name = "TimeBox";
this.TimeBox.Size = new System.Drawing.Size(60, 20);
this.TimeBox.TabIndex = 15;
//
// EditConstraintLink
//
this.EditConstraintLink.AutoSize = true;
this.EditConstraintLink.Location = new System.Drawing.Point(100, 10);
this.EditConstraintLink.Name = "EditConstraintLink";
this.EditConstraintLink.Size = new System.Drawing.Size(25, 13);
this.EditConstraintLink.TabIndex = 16;
this.EditConstraintLink.TabStop = true;
this.EditConstraintLink.Text = "Edit";
this.EditConstraintLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.EditLink_LinkClicked);
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.Location = new System.Drawing.Point(12, 38);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.label4);
this.splitContainer1.Panel1.Controls.Add(this.EditFunctionLink);
this.splitContainer1.Panel1.Controls.Add(this.AddFunctionLink);
this.splitContainer1.Panel1.Controls.Add(this.FunctionList);
this.splitContainer1.Panel1.Controls.Add(this.RemoveFunctionLink);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.label3);
this.splitContainer1.Panel2.Controls.Add(this.EditConstraintLink);
this.splitContainer1.Panel2.Controls.Add(this.ConstraintsList);
this.splitContainer1.Panel2.Controls.Add(this.RemoveConstraintLink);
this.splitContainer1.Panel2.Controls.Add(this.AddConstraintLink);
this.splitContainer1.Size = new System.Drawing.Size(373, 236);
this.splitContainer1.SplitterDistance = 114;
this.splitContainer1.TabIndex = 17;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(5, 10);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(60, 13);
this.label4.TabIndex = 17;
this.label4.Text = "Objectives:";
//
// EditFunctionLink
//
this.EditFunctionLink.AutoSize = true;
this.EditFunctionLink.Location = new System.Drawing.Point(102, 10);
this.EditFunctionLink.Name = "EditFunctionLink";
this.EditFunctionLink.Size = new System.Drawing.Size(25, 13);
this.EditFunctionLink.TabIndex = 21;
this.EditFunctionLink.TabStop = true;
this.EditFunctionLink.Text = "Edit";
this.EditFunctionLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.EditFunctionLink_LinkClicked);
//
// AddFunctionLink
//
this.AddFunctionLink.AutoSize = true;
this.AddFunctionLink.Location = new System.Drawing.Point(70, 10);
this.AddFunctionLink.Name = "AddFunctionLink";
this.AddFunctionLink.Size = new System.Drawing.Size(26, 13);
this.AddFunctionLink.TabIndex = 20;
this.AddFunctionLink.TabStop = true;
this.AddFunctionLink.Text = "Add";
this.AddFunctionLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.AddFunctionLink_LinkClicked);
//
// FunctionList
//
this.FunctionList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FunctionList.FormattingEnabled = true;
this.FunctionList.IntegralHeight = false;
this.FunctionList.Location = new System.Drawing.Point(6, 26);
this.FunctionList.Name = "FunctionList";
this.FunctionList.Size = new System.Drawing.Size(364, 85);
this.FunctionList.TabIndex = 18;
this.FunctionList.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.FunctionList_MouseDoubleClick);
//
// RemoveFunctionLink
//
this.RemoveFunctionLink.AutoSize = true;
this.RemoveFunctionLink.Location = new System.Drawing.Point(133, 10);
this.RemoveFunctionLink.Name = "RemoveFunctionLink";
this.RemoveFunctionLink.Size = new System.Drawing.Size(92, 13);
this.RemoveFunctionLink.TabIndex = 19;
this.RemoveFunctionLink.TabStop = true;
this.RemoveFunctionLink.Text = "Remove Selected";
this.RemoveFunctionLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.RemoveFunctionLink_LinkClicked);
//
// TimeCheckBox
//
this.TimeCheckBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.TimeCheckBox.AutoSize = true;
this.TimeCheckBox.Location = new System.Drawing.Point(18, 289);
this.TimeCheckBox.Name = "TimeCheckBox";
this.TimeCheckBox.Size = new System.Drawing.Size(202, 17);
this.TimeCheckBox.TabIndex = 18;
this.TimeCheckBox.Text = "Time var t used in objective functions";
this.TimeCheckBox.UseVisualStyleBackColor = true;
//
// ProblemForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(397, 372);
this.Controls.Add(this.TimeCheckBox);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.TimeBox);
this.Controls.Add(this.TimeLabel);
this.Controls.Add(this.label1);
this.Controls.Add(this.DimensionBox);
this.Controls.Add(this.SetButton);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ProblemForm";
this.Text = "Problem";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ProblemForm_FormClosing);
this.Load += new System.EventHandler(this.ProblemForm_Load);
((System.ComponentModel.ISupportInitialize)(this.DimensionBox)).EndInit();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button SetButton;
private System.Windows.Forms.NumericUpDown DimensionBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ListBox ConstraintsList;
private System.Windows.Forms.LinkLabel RemoveConstraintLink;
private System.Windows.Forms.LinkLabel AddConstraintLink;
private System.Windows.Forms.Label TimeLabel;
private System.Windows.Forms.TextBox TimeBox;
private System.Windows.Forms.LinkLabel EditConstraintLink;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.LinkLabel EditFunctionLink;
private System.Windows.Forms.LinkLabel AddFunctionLink;
private System.Windows.Forms.ListBox FunctionList;
private System.Windows.Forms.LinkLabel RemoveFunctionLink;
private System.Windows.Forms.CheckBox TimeCheckBox;
}
}
| |
using System;
using System.Messaging;
using System.Threading;
using System.Transactions;
using log4net;
using Rhino.ServiceBus.DataStructures;
using Rhino.ServiceBus.Exceptions;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.Messages;
using Rhino.ServiceBus.Msmq;
using Rhino.ServiceBus.Transport;
using MessageType = Rhino.ServiceBus.Transport.MessageType;
using System.Linq;
namespace Rhino.ServiceBus.LoadBalancer
{
public class MsmqLoadBalancer : AbstractMsmqListener
{
private readonly Uri secondaryLoadBalancer;
private readonly IQueueStrategy queueStrategy;
private readonly ILog logger = LogManager.GetLogger(typeof(MsmqLoadBalancer));
private readonly Queue<Uri> readyForWork = new Queue<Uri>();
private readonly Set<Uri> knownWorkers = new Set<Uri>();
private readonly Timer heartBeatTimer;
private readonly Set<Uri> knownEndpoints = new Set<Uri>();
private MsmqReadyForWorkListener _readyForWorkListener;
public event Action<Message> MessageBatchSentToAllWorkers;
public event Action SentNewWorkerPersisted;
public event Action SentNewEndpointPersisted;
public MsmqLoadBalancer(
IMessageSerializer serializer,
IQueueStrategy queueStrategy,
IEndpointRouter endpointRouter,
Uri endpoint,
int threadCount,
TransactionalOptions transactional)
: base(queueStrategy, endpoint, threadCount, serializer, endpointRouter, transactional)
{
heartBeatTimer = new Timer(SendHeartBeatToSecondaryServer);
this.queueStrategy = queueStrategy;
}
public MsmqLoadBalancer(
IMessageSerializer serializer,
IQueueStrategy queueStrategy,
IEndpointRouter endpointRouter,
Uri endpoint,
int threadCount,
Uri secondaryLoadBalancer,
TransactionalOptions transactional)
: this(serializer, queueStrategy, endpointRouter, endpoint, threadCount, transactional)
{
this.secondaryLoadBalancer = secondaryLoadBalancer;
}
protected void SendHeartBeatToSecondaryServer(object ignored)
{
SendToQueue(secondaryLoadBalancer, new Heartbeat
{
From = Endpoint.Uri,
At = DateTime.Now,
});
}
public Set<Uri> KnownWorkers
{
get { return knownWorkers; }
}
public Set<Uri> KnownEndpoints
{
get { return knownEndpoints; }
}
public int NumberOfWorkersReadyToHandleMessages
{
get { return readyForWork.TotalCount; }
}
protected override void BeforeStart(OpenedQueue queue)
{
try
{
queueStrategy.InitializeQueue(Endpoint, QueueType.LoadBalancer);
}
catch (Exception e)
{
throw new TransportException(
"Could not open queue for load balancer: " + Endpoint + Environment.NewLine +
"Queue path: " + MsmqUtil.GetQueuePath(Endpoint), e);
}
try
{
ReadUrisFromSubQueue(KnownWorkers, SubQueue.Workers);
}
catch (Exception e)
{
throw new InvalidOperationException("Could not read workers subqueue", e);
}
try
{
ReadUrisFromSubQueue(KnownEndpoints, SubQueue.Endpoints);
}
catch (Exception e)
{
throw new InvalidOperationException("Could not read endpoints subqueue", e);
}
RemoveAllReadyToWorkMessages();
}
private void ReadUrisFromSubQueue(Set<Uri> set, SubQueue subQueue)
{
using (var q = MsmqUtil.GetQueuePath(Endpoint).Open(QueueAccessMode.Receive))
using (var sq = q.OpenSubQueue(subQueue, QueueAccessMode.SendAndReceive))
{
var messages = sq.GetAllMessagesWithStringFormatter();
foreach (var message in messages)
{
var uriString = message.Body.ToString();
set.Add(new Uri(uriString));
}
}
}
private void RemoveAllReadyToWorkMessages()
{
using (var tx = new TransactionScope())
using (var readyForWorkQueue = MsmqUtil.GetQueuePath(Endpoint).Open(QueueAccessMode.SendAndReceive))
using (var enumerator = readyForWorkQueue.GetMessageEnumerator2())
{
try
{
while (enumerator.MoveNext())
{
while (
enumerator.Current != null &&
enumerator.Current.Label == typeof(ReadyToWork).FullName)
{
var current = enumerator.RemoveCurrent(readyForWorkQueue.GetTransactionType());
HandleLoadBalancerMessage(readyForWorkQueue, current);
}
}
}
catch (MessageQueueException e)
{
if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
throw;
}
readyForWork.Clear();
tx.Complete();
}
}
protected override void AfterStart(OpenedQueue queue)
{
if (_readyForWorkListener != null)
{
_readyForWorkListener.ReadyToWorkMessageArrived += readyForWorkMessage => HandleReadyForWork(queue, readyForWorkMessage);
_readyForWorkListener.Start();
}
if (secondaryLoadBalancer != null)
{
foreach (var queueUri in KnownEndpoints.GetValues())
{
logger.InfoFormat("Notifying {0} that primary load balancer {1} is taking over from secondary",
queueUri,
Endpoint.Uri
);
SendToQueue(queueUri, new Reroute
{
NewEndPoint = Endpoint.Uri,
OriginalEndPoint = Endpoint.Uri
});
}
SendHeartBeatToSecondaryServer(null);
heartBeatTimer.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
Reroute reroute;
if (_readyForWorkListener != null)
reroute = new Reroute
{
NewEndPoint = _readyForWorkListener.Endpoint.Uri,
OriginalEndPoint = _readyForWorkListener.Endpoint.Uri
};
else
reroute = new Reroute
{
NewEndPoint = Endpoint.Uri,
OriginalEndPoint = Endpoint.Uri
};
SendToAllWorkers(
GenerateMsmqMessageFromMessageBatch(reroute),
"Rerouting {1} back to {0}"
);
}
if (ShouldNotifyWorkersLoaderIsReadyToAcceptWorkOnStartup)
NotifyWorkersThatLoaderIsReadyToAcceptWork();
}
protected virtual bool ShouldNotifyWorkersLoaderIsReadyToAcceptWorkOnStartup
{
get
{
return true;
}
}
public MsmqReadyForWorkListener ReadyForWorkListener
{
get { return _readyForWorkListener; }
set { _readyForWorkListener = value; }
}
protected void NotifyWorkersThatLoaderIsReadyToAcceptWork()
{
var acceptingWork = new AcceptingWork { Endpoint = Endpoint.Uri };
SendToAllWorkers(
GenerateMsmqMessageFromMessageBatch(acceptingWork),
"Notifing {1} that {0} is accepting work"
);
}
protected override void OnStop()
{
if(_readyForWorkListener !=null)
_readyForWorkListener.Dispose();
heartBeatTimer.Dispose();
}
protected override void HandlePeekedMessage(OpenedQueue queue, Message message)
{
try
{
using (var tx = new TransactionScope(TransactionScopeOption.Required, TransportUtil.GetTransactionTimeout()))
{
message = queue.TryGetMessageFromQueue(message.Id);
if (message == null)
return;
PersistEndpoint(queue, message);
switch ((MessageType)message.AppSpecific)
{
case MessageType.ShutDownMessageMarker:
//silently cnsume the message
break;
case MessageType.LoadBalancerMessageMarker:
HandleLoadBalancerMessage(queue, message);
break;
case MessageType.AdministrativeMessageMarker:
SendToAllWorkers(message, "Dispatching administrative message from {0} to load balancer {1}");
break;
default:
HandleStandardMessage(queue, message);
break;
}
tx.Complete();
}
}
catch (Exception e)
{
logger.Error("Fail to process load balanced message properly", e);
}
}
private void PersistEndpoint(OpenedQueue queue, Message message)
{
var queueUri = MsmqUtil.GetQueueUri(message.ResponseQueue);
if (queueUri == null)
return;
bool needToPersist = knownEndpoints.Add(queueUri);
if (needToPersist == false)
return;
logger.InfoFormat("Adding new endpoint: {0}", queueUri);
var persistedEndPoint = new Message
{
Formatter = new XmlMessageFormatter(new[] { typeof(string) }),
Body = queueUri.ToString(),
Label = ("Known end point: " + queueUri).EnsureLabelLength()
};
queue.Send(persistedEndPoint.SetSubQueueToSendTo(SubQueue.Endpoints));
SendToQueue(secondaryLoadBalancer, new NewEndpointPersisted
{
PersistedEndpoint = queueUri
});
Raise(SentNewEndpointPersisted);
}
protected void SendToQueue(Uri queueUri, params object[] msgs)
{
if (queueUri == null)
return;
try
{
var queueInfo = MsmqUtil.GetQueuePath(new Endpoint { Uri = queueUri });
using (var secondaryLoadBalancerQueue = queueInfo.Open(QueueAccessMode.Send))
{
secondaryLoadBalancerQueue.Send(GenerateMsmqMessageFromMessageBatch(msgs));
}
}
catch (Exception e)
{
throw new LoadBalancerException("Could not send message to queue: " + queueUri, e);
}
}
private void HandleStandardMessage(OpenedQueue queue, Message message)
{
var worker = readyForWork.Dequeue();
if (worker == null) // handle message later
{
queue.Send(message);
}
else
{
var workerEndpoint = endpointRouter.GetRoutedEndpoint(worker);
using (var workerQueue = MsmqUtil.GetQueuePath(workerEndpoint).Open(QueueAccessMode.Send))
{
logger.DebugFormat("Dispatching message '{0}' to {1}", message.Id, workerEndpoint.Uri);
workerQueue.Send(message);
}
}
}
private void SendToAllWorkers(Message message, string logMessage)
{
var values = KnownWorkers.GetValues();
foreach (var worker in values)
{
var workerEndpoint = endpointRouter.GetRoutedEndpoint(worker);
using (var workerQueue = MsmqUtil.GetQueuePath(workerEndpoint).Open(QueueAccessMode.Send))
{
logger.DebugFormat(logMessage, Endpoint.Uri, worker);
workerQueue.Send(message);
}
}
if (values.Length == 0)
return;
var copy = MessageBatchSentToAllWorkers;
if (copy != null)
copy(message);
}
private void HandleLoadBalancerMessage(OpenedQueue queue, Message message)
{
foreach (var msg in DeserializeMessages(queue, message, null))
{
var query = msg as QueryForAllKnownWorkersAndEndpoints;
if (query != null)
{
SendKnownWorkersAndKnownEndpoints(message.ResponseQueue);
continue;
}
var queryReadyForWorkQueueUri = msg as QueryReadyForWorkQueueUri;
if (queryReadyForWorkQueueUri != null)
{
SendReadyForWorkQueueUri(message.ResponseQueue);
continue;
}
var work = msg as ReadyToWork;
if (work != null)
{
HandleReadyForWork(queue, work);
}
HandleLoadBalancerMessages(msg);
}
}
private void HandleReadyForWork(OpenedQueue queue, ReadyToWork work)
{
logger.DebugFormat("{0} is ready to work", work.Endpoint);
var needToAddToQueue = KnownWorkers.Add(work.Endpoint);
if (needToAddToQueue)
AddWorkerToQueue(queue, work);
readyForWork.Enqueue(work.Endpoint);
}
private void SendReadyForWorkQueueUri(MessageQueue responseQueue)
{
if (responseQueue == null)
return;
try
{
var transactionType = MessageQueueTransactionType.None;
if (Endpoint.Transactional.GetValueOrDefault())
transactionType = Transaction.Current == null ? MessageQueueTransactionType.Single : MessageQueueTransactionType.Automatic;
var newEndpoint = ReadyForWorkListener != null ? ReadyForWorkListener.Endpoint.Uri : Endpoint.Uri;
var message = new ReadyForWorkQueueUri {Endpoint = newEndpoint};
responseQueue.Send(GenerateMsmqMessageFromMessageBatch(message), transactionType);
}
catch (Exception e)
{
logger.Error("Failed to send known ready for work queue uri", e);
}
}
private void SendKnownWorkersAndKnownEndpoints(MessageQueue responseQueue)
{
if (responseQueue == null)
return;
try
{
var endpoints = KnownEndpoints.GetValues();
var workers = KnownWorkers.GetValues();
var transactionType = MessageQueueTransactionType.None;
if (Endpoint.Transactional.GetValueOrDefault())
transactionType = Transaction.Current == null ? MessageQueueTransactionType.Single : MessageQueueTransactionType.Automatic;
var index = 0;
while (index < endpoints.Length)
{
var endpointsBatch = endpoints
.Skip(index)
.Take(256)
.Select(x => new NewEndpointPersisted { PersistedEndpoint = x })
.ToArray();
index += endpointsBatch.Length;
responseQueue.Send(GenerateMsmqMessageFromMessageBatch(endpointsBatch), transactionType);
}
index = 0;
while (index < workers.Length)
{
var workersBatch = workers
.Skip(index)
.Take(256)
.Select(x => new NewWorkerPersisted { Endpoint = x })
.ToArray();
index += workersBatch.Length;
responseQueue.Send(GenerateMsmqMessageFromMessageBatch(workersBatch), transactionType);
}
}
catch (Exception e)
{
logger.Error("Failed to send known endpoints and known workers", e);
}
}
protected virtual void HandleLoadBalancerMessages(object msg)
{
}
private void AddWorkerToQueue(OpenedQueue queue, ReadyToWork work)
{
var persistedWorker = new Message
{
Formatter = new XmlMessageFormatter(new[] { typeof(string) }),
Body = work.Endpoint.ToString(),
Label = ("Known worker: " + work.Endpoint).EnsureLabelLength()
};
logger.DebugFormat("New worker: {0}", work.Endpoint);
queue.Send(persistedWorker.SetSubQueueToSendTo(SubQueue.Workers));
SendToQueue(secondaryLoadBalancer, new NewWorkerPersisted
{
Endpoint = work.Endpoint
});
Raise(SentNewWorkerPersisted);
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of XNA StockEffects http://xbox.create.msdn.com/en-US/education/catalog/sample/stock_effects
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
//-----------------------------------------------------------------------------
// EnvironmentMapEffect.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Built-in effect that supports environment mapping.
/// </summary>
public partial class EnvironmentMapEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog
{
#region Effect Parameters
EffectParameter textureParam;
EffectParameter environmentMapParam;
EffectParameter environmentMapAmountParam;
EffectParameter environmentMapSpecularParam;
EffectParameter fresnelFactorParam;
EffectParameter diffuseColorParam;
EffectParameter emissiveColorParam;
EffectParameter eyePositionParam;
EffectParameter fogColorParam;
EffectParameter fogVectorParam;
EffectParameter worldParam;
EffectParameter worldInverseTransposeParam;
EffectParameter worldViewProjParam;
EffectPass shaderPass;
#endregion
#region Fields
bool oneLight;
bool fogEnabled;
bool fresnelEnabled;
bool specularEnabled;
Matrix world = Matrix.Identity;
Matrix view = Matrix.Identity;
Matrix projection = Matrix.Identity;
Matrix worldView;
Vector4 diffuseColor = Vector4.One;
Vector3 emissiveColor = Vector3.Zero;
Vector3 ambientLightColor = Vector3.Zero;
float alpha = 1;
DirectionalLight light0;
DirectionalLight light1;
DirectionalLight light2;
float fogStart = 0;
float fogEnd = 1;
EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the world matrix.
/// </summary>
public Matrix World
{
get { return world; }
set
{
world = value;
dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the view matrix.
/// </summary>
public Matrix View
{
get { return view; }
set
{
view = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the projection matrix.
/// </summary>
public Matrix Projection
{
get { return projection; }
set
{
projection = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj;
}
}
/// <summary>
/// Gets or sets the material diffuse color (range 0 to 1).
/// </summary>
public Vector4 DiffuseColor
{
get { return diffuseColor; }
set
{
diffuseColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material emissive color (range 0 to 1).
/// </summary>
public Vector3 EmissiveColor
{
get { return emissiveColor; }
set
{
emissiveColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material alpha.
/// </summary>
public float Alpha
{
get { return alpha; }
set
{
alpha = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the ambient light color (range 0 to 1).
/// </summary>
public Vector3 AmbientLightColor
{
get { return ambientLightColor; }
set
{
ambientLightColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets the first directional light.
/// </summary>
public DirectionalLight DirectionalLight0 { get { return light0; } }
/// <summary>
/// Gets the second directional light.
/// </summary>
public DirectionalLight DirectionalLight1 { get { return light1; } }
/// <summary>
/// Gets the third directional light.
/// </summary>
public DirectionalLight DirectionalLight2 { get { return light2; } }
/// <summary>
/// Gets or sets the fog enable flag.
/// </summary>
public bool FogEnabled
{
get { return fogEnabled; }
set
{
if (fogEnabled != value)
{
fogEnabled = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable;
}
}
}
/// <summary>
/// Gets or sets the fog start distance.
/// </summary>
public float FogStart
{
get { return fogStart; }
set
{
fogStart = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog end distance.
/// </summary>
public float FogEnd
{
get { return fogEnd; }
set
{
fogEnd = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog color.
/// </summary>
public Vector3 FogColor
{
get { return fogColorParam.GetValue<Vector3>(); }
set { fogColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the current texture.
/// </summary>
public Texture2D Texture
{
get { return textureParam.GetResource<Texture2D>(); }
set { textureParam.SetResource(value); }
}
/// <summary>
/// Gets or sets the current environment map texture.
/// </summary>
public TextureCube EnvironmentMap
{
get { return environmentMapParam.GetResource<TextureCube>(); }
set { environmentMapParam.SetResource(value); }
}
/// <summary>
/// Gets or sets the amount of the environment map RGB that will be blended over
/// the base texture. Range 0 to 1, default 1. If set to zero, the RGB channels
/// of the environment map will completely ignored (but the environment map alpha
/// may still be visible if EnvironmentMapSpecular is greater than zero).
/// </summary>
public float EnvironmentMapAmount
{
get { return environmentMapAmountParam.GetValue<float>(); }
set { environmentMapAmountParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the amount of the environment map alpha channel that will
/// be added to the base texture. Range 0 to 1, default 0. This can be used
/// to implement cheap specular lighting, by encoding one or more specular
/// highlight patterns into the environment map alpha channel, then setting
/// EnvironmentMapSpecular to the desired specular light color.
/// </summary>
public Vector3 EnvironmentMapSpecular
{
get { return environmentMapSpecularParam.GetValue<Vector3>(); }
set
{
environmentMapSpecularParam.SetValue(value);
bool enabled = (value != Vector3.Zero);
if (specularEnabled != enabled)
{
specularEnabled = enabled;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
/// <summary>
/// Gets or sets the Fresnel factor used for the environment map blending.
/// Higher values make the environment map only visible around the silhouette
/// edges of the object, while lower values make it visible everywhere.
/// Setting this property to 0 disables Fresnel entirely, making the
/// environment map equally visible regardless of view angle. The default is
/// 1. Fresnel only affects the environment map RGB (the intensity of which is
/// controlled by EnvironmentMapAmount). The alpha contribution (controlled by
/// EnvironmentMapSpecular) is not affected by the Fresnel setting.
/// </summary>
public float FresnelFactor
{
get { return fresnelFactorParam.GetValue<float>(); }
set
{
fresnelFactorParam.SetValue(value);
bool enabled = (value != 0);
if (fresnelEnabled != enabled)
{
fresnelEnabled = enabled;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
/// <summary>
/// This effect requires lighting, so we explicitly implement
/// IEffectLights.LightingEnabled, and do not allow turning it off.
/// </summary>
bool IEffectLights.LightingEnabled
{
get { return true; }
set { if (!value) throw new NotSupportedException("EnvironmentMapEffect does not support setting LightingEnabled to false."); }
}
#endregion
#region Methods
/// <summary>
/// Creates a new EnvironmentMapEffect with default parameter settings.
/// </summary>
public EnvironmentMapEffect(GraphicsDevice device) : this(device, device.DefaultEffectPool)
{
}
/// <summary>
/// Creates a new EnvironmentMapEffect with default parameter settings from a specified <see cref="EffectPool"/>.
/// </summary>
public EnvironmentMapEffect(GraphicsDevice device, EffectPool pool)
: base(device, effectBytecode, pool)
{
CacheEffectParameters(null);
DirectionalLight0.Enabled = true;
EnvironmentMapAmount = 1;
EnvironmentMapSpecular = Vector3.Zero;
FresnelFactor = 1;
}
protected override void Initialize()
{
Pool.RegisterBytecode(effectBytecode);
base.Initialize();
}
///// <summary>
///// Creates a new EnvironmentMapEffect by cloning parameter settings from an existing instance.
///// </summary>
//protected EnvironmentMapEffect(EnvironmentMapEffect cloneSource)
// : base(cloneSource)
//{
// CacheEffectParameters(cloneSource);
// fogEnabled = cloneSource.fogEnabled;
// fresnelEnabled = cloneSource.fresnelEnabled;
// specularEnabled = cloneSource.specularEnabled;
// world = cloneSource.world;
// view = cloneSource.view;
// projection = cloneSource.projection;
// diffuseColor = cloneSource.diffuseColor;
// emissiveColor = cloneSource.emissiveColor;
// ambientLightColor = cloneSource.ambientLightColor;
// alpha = cloneSource.alpha;
// fogStart = cloneSource.fogStart;
// fogEnd = cloneSource.fogEnd;
//}
///// <summary>
///// Creates a clone of the current EnvironmentMapEffect instance.
///// </summary>
//public override Effect Clone()
//{
// return new EnvironmentMapEffect(this);
//}
/// <summary>
/// Sets up the standard key/fill/back lighting rig.
/// </summary>
public void EnableDefaultLighting()
{
AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2);
}
/// <summary>
/// Looks up shortcut references to our effect parameters.
/// </summary>
void CacheEffectParameters(EnvironmentMapEffect cloneSource)
{
textureParam = Parameters["Texture"];
environmentMapParam = Parameters["EnvironmentMap"];
environmentMapAmountParam = Parameters["EnvironmentMapAmount"];
environmentMapSpecularParam = Parameters["EnvironmentMapSpecular"];
fresnelFactorParam = Parameters["FresnelFactor"];
diffuseColorParam = Parameters["DiffuseColor"];
emissiveColorParam = Parameters["EmissiveColor"];
eyePositionParam = Parameters["EyePosition"];
fogColorParam = Parameters["FogColor"];
fogVectorParam = Parameters["FogVector"];
worldParam = Parameters["World"];
worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
worldViewProjParam = Parameters["WorldViewProj"];
light0 = new DirectionalLight(Parameters["DirLight0Direction"],
Parameters["DirLight0DiffuseColor"],
null,
(cloneSource != null) ? cloneSource.light0 : null);
light1 = new DirectionalLight(Parameters["DirLight1Direction"],
Parameters["DirLight1DiffuseColor"],
null,
(cloneSource != null) ? cloneSource.light1 : null);
light2 = new DirectionalLight(Parameters["DirLight2Direction"],
Parameters["DirLight2DiffuseColor"],
null,
(cloneSource != null) ? cloneSource.light2 : null);
}
/// <summary>
/// Lazily computes derived parameter values immediately before applying the effect.
/// </summary>
protected internal override EffectPass OnApply(EffectPass pass)
{
// Recompute the world+view+projection matrix or fog vector?
dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam);
// Recompute the world inverse transpose and eye position?
dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam);
// Recompute the diffuse/emissive/alpha material color parameters?
if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0)
{
EffectHelpers.SetMaterialColor(true, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam);
dirtyFlags &= ~EffectDirtyFlags.MaterialColor;
}
// Check if we can use the only-bother-with-the-first-light shader optimization.
bool newOneLight = !light1.Enabled && !light2.Enabled;
if (oneLight != newOneLight)
{
oneLight = newOneLight;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
// Recompute the shader index?
if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0)
{
int shaderIndex = 0;
if (!fogEnabled)
shaderIndex += 1;
if (fresnelEnabled)
shaderIndex += 2;
if (specularEnabled)
shaderIndex += 4;
if (oneLight)
shaderIndex += 8;
shaderPass = pass.SubPasses[shaderIndex];
dirtyFlags &= ~EffectDirtyFlags.ShaderIndex;
}
return base.OnApply(shaderPass);
}
#endregion
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using TimePunchAPI.Models;
namespace TimePunchAPI.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20160509121445_AddUserForeignKeyToTimespans")]
partial class AddUserForeignKeyToTimespans
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<long>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<long>("RoleId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<long>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<long>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<long>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<long>", b =>
{
b.Property<long>("UserId");
b.Property<long>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("TimePunchAPI.Models.ApplicationRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("TimePunchAPI.Models.ApplicationUser", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("TimePunchAPI.Models.Issue", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<long>("OriginalEstimate");
b.Property<int>("Priority");
b.Property<long>("ProjectId");
b.Property<string>("Summary");
b.Property<string>("Tag");
b.Property<int>("Type");
b.HasKey("Id");
});
modelBuilder.Entity("TimePunchAPI.Models.Project", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Key");
b.Property<long>("LeaderId");
b.Property<string>("Name");
b.Property<string>("Summary");
b.HasKey("Id");
});
modelBuilder.Entity("TimePunchAPI.Models.Timespan", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("IssueId");
b.Property<DateTime?>("StartTime");
b.Property<DateTime?>("StopTime");
b.Property<string>("Tag");
b.Property<long>("TimeSpent");
b.Property<long>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("TimePunchAPI.Models.UserProject", b =>
{
b.Property<long>("UserId");
b.Property<long>("ProjectId");
b.HasKey("UserId", "ProjectId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<long>", b =>
{
b.HasOne("TimePunchAPI.Models.ApplicationRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<long>", b =>
{
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<long>", b =>
{
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<long>", b =>
{
b.HasOne("TimePunchAPI.Models.ApplicationRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("TimePunchAPI.Models.Issue", b =>
{
b.HasOne("TimePunchAPI.Models.Project")
.WithMany()
.HasForeignKey("ProjectId");
});
modelBuilder.Entity("TimePunchAPI.Models.Timespan", b =>
{
b.HasOne("TimePunchAPI.Models.Issue")
.WithMany()
.HasForeignKey("IssueId");
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("TimePunchAPI.Models.UserProject", b =>
{
b.HasOne("TimePunchAPI.Models.Project")
.WithMany()
.HasForeignKey("ProjectId");
b.HasOne("TimePunchAPI.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using metahub.Properties;
using imperative;
using imperative.schema;
using metahub.jackolantern;
using metahub.jackolantern.code;
using metahub.logic;
using metahub.render;
using metahub.schema;
using parser;
using Regex = System.Text.RegularExpressions.Regex;
namespace metahub.main
{
public delegate void Empty_Delegate();
public class Hub
{
public static Regex remove_comments = new Regex("#[^\n]*");
public Schema root;
public Schema metahub_schema;
public int max_steps = 100;
public Dictionary<string, string> core_schemas = new Dictionary<string, string>();
static List<Hub> instances = new List<Hub>();
public Hub()
{
instances.Add(this);
root = new Schema();
metahub_schema = root.add_namespace("metahub");
core_schemas["piecemaker"] = Resources.piecemaker_json;
core_schemas["metahub"] = Resources.metahub_json;
}
public string find_schema(string schema_name, string root_path = null)
{
if (root_path != null)
{
var path = Path.Combine(root_path, schema_name + ".json").Replace("\\", "/");
if (File.Exists(path))
return File.ReadAllText(path);
}
var base_name = Path.GetFileNameWithoutExtension(schema_name);
if (core_schemas.ContainsKey(base_name))
return core_schemas[base_name];
throw new Exception("Could not find schema source for: " + schema_name);
}
public void load_schema(string schema_name, string root_path = null)
{
var source = find_schema(schema_name, root_path);
var space = this.root.add_namespace(Path.GetFileNameWithoutExtension(schema_name));
space.load_from_string(source);
}
// public void load_schema_from_file(string url, Schema space, bool auto_identity = false)
// {
// var data = JsonConvert.DeserializeObject<Schema_Source>(File.ReadAllText(url));
// load_schema_from_object(data, space, auto_identity);
// }
//
// public void load_schema_from_string(string json, Schema space, bool auto_identity = false)
// {
// var data = JsonConvert.DeserializeObject<Schema_Source>(json);
// load_schema_from_object(data, space, auto_identity);
// }
//
// public void load_schema_from_object(Schema_Source data, Schema space, bool auto_identity = false)
// {
// root.load_trellises(data.trellises, new Load_Settings(space, auto_identity));
// if (data.is_external.HasValue && data.is_external.Value)
// space.is_external = true;
// }
public void run_data(Pattern_Source source, Schema railway, Logician logician)
{
Coder coder = new Coder(railway, logician);
coder.convert_statement(source, null);
}
public void generate(Pattern_Source source, string target_name, string destination)
{
var overlord = new Overlord();
var logician = new Logician(root);
run_data(source, root, logician);
var target = Generator.create_target2(overlord, target_name);
logician.analyze();
var jack = new JackOLantern(logician, overlord, target);
jack.run();
var config = new Overlord_Configuration
{
output = destination
};
Generator.create_folder(config.output);
//Utility.clear_folder(output_folder);
target.run(config, new string[] {});
// Generator.run(target, config);
}
public void load_schema_files(MetaHub_Configuration config)
{
foreach (var schema_name in config.schemas)
{
var schema = root.add_namespace(schema_name);
// schema.load_from_string(find_schema(schema_name, root_path));
}
}
public static void run(Overlord_Configuration config)
{
var hub = new Hub();
hub.load_schema("metahub");
//hub.load_schema_files(config);
var files = Overlord.aggregate_files(config.input);
var overlord = new Overlord(config.target);
var logician = new Logician(hub.root);
var imp_files = files.Where(f => Path.GetExtension(f) == ".imp");
var metahub_files = files.Where(f => Path.GetExtension(f) == ".mh");
overlord.summon_many(imp_files);
var jack = new JackOLantern(logician, overlord, overlord.target);
dungeons_to_trellises(overlord.root, logician.schema, jack);
foreach (var clan in jack.clans.Values)
{
foreach (var portal in clan.dungeon.all_portals.Values)
{
clan.trellis.add_property(portal_to_property(portal, clan, jack));
}
}
hub.load_many(metahub_files, logician);
logician.analyze();
jack.run();
overlord.generate(config, new string[] {});
}
void load_many(IEnumerable<string> paths, Logician logician)
{
foreach (var file in paths)
{
load_file(file, logician);
}
}
void load_file(string path, Logician logician)
{
parse_code(File.ReadAllText(path), logician);
}
public void parse_code(string code, Logician logician)
{
var result = logician.parse_code(code);
if (!result.success)
{
Debug_Info.output(result);
throw new Exception("Syntax Error at " + result.end.y + ":" + result.end.x);
}
var match = (Match)result;
run_data(match.get_data(), root, logician);
}
static public void dungeons_to_trellises(Dungeon realm, Schema schema, JackOLantern jack)
{
foreach (var dungeon in realm.dungeons.Values)
{
dungeon_to_trellis(dungeon, schema, jack);
}
foreach (var child in realm.dungeons.Values)
{
var child_schema = schema.get_namespace(new List<string> { child.name })
?? schema.add_namespace(child.name);
dungeons_to_trellises(child, child_schema, jack);
}
}
static void dungeon_to_trellis(Dungeon dungeon, Schema schema, JackOLantern jack)
{
if (schema.trellises.ContainsKey(dungeon.name))
return;
var trellis = new Trellis(dungeon.name, schema);
trellis.is_value = dungeon.is_value;
trellis.is_abstract = dungeon.is_abstract;
jack.add_clan(dungeon, trellis);
}
static Kind profession_to_kind(Profession profession)
{
if (profession == Professions.Bool)
return Kind.Bool;
if (profession == Professions.String)
return Kind.String;
if (profession == Professions.Float)
return Kind.Float;
if (profession == Professions.Int)
return Kind.Int;
return Kind.reference;
}
public static Property portal_to_property(Portal portal, Dwarf_Clan clan, JackOLantern jack)
{
var kind = profession_to_kind(portal.profession);
Trellis other_trellis = null;
if (kind == Kind.reference)
{
var other_dungeon = portal.is_list
? portal.profession.children[0].dungeon
: portal.other_dungeon;
other_trellis = jack.clans[(Dungeon)other_dungeon].trellis;
}
var trellis = clan.trellis;
var property = new Property(portal.name, kind, trellis, other_trellis);
property.signature.is_list = portal.is_list;
if (other_trellis != null)
{
var other_properties = other_trellis.core_properties.Values
.Where(p => p.other_trellis == trellis).ToArray();
// throw new Exception("Could not find other property for " + this.trellis.name + "." + this.name + ".");
if (other_properties.Count() > 1)
{
throw new Exception("Multiple ambiguous other properties for " + trellis.name + "." + portal.name + ".");
// var direct = Lambda.filter(other_properties, (p)=>{ return p.other_property})
}
else if (other_properties.Count() == 1)
{
property.other_property = other_properties.First();
property.other_property.other_trellis = trellis.get_real();
property.other_property.other_property = property;
}
// else if (!other_trellis.is_value && !other_trellis.space.is_external)
// throw new Exception("Could not find other property for " + property.fullname);
}
return property;
}
}
}
| |
// Copyright (C) 2009-2017 Luca Piccioni
//
// 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.
// Preprocessor symbol for enabling function logging output
#undef DEBUG_VERBOSE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using DelegateList = System.Collections.Generic.List<System.Reflection.FieldInfo>;
namespace Khronos
{
/// <summary>
/// Base class for loading external routines.
/// </summary>
/// <remarks>
/// <para>
/// This class is used for basic operations of automatic generated classes Gl, Wgl, Glx and Egl. The main
/// functions of this class allows:
/// - To parse OpenGL extensions string
/// - To query import functions using reflection
/// - To query delegate functions using reflection
/// - To link imported functions into delegates functions.
/// </para>
/// <para>
/// Argument of the methods with 'internal' modifier are not checked.
/// </para>
/// </remarks>
public class KhronosApi
{
#region String Encoding
/// <summary>
/// Copies all characters up to the first null character from an
/// unmanaged UTF8 string.
/// </summary>
/// <param name="ptr">
/// The address of the first character of the unmanaged string.
/// </param>
/// <returns>
/// The <see cref="string"/> represented by <paramref name="ptr"/>.
/// </returns>
protected static string PtrToString(IntPtr ptr)
{
return PtrToStringUTF8(ptr);
}
/// <summary>
/// Copies all characters up to the first null character from an
/// unmanaged UTF8 string.
/// </summary>
/// <param name="ptr">
/// The address of the first character of the unmanaged string.
/// </param>
/// <returns>
/// The <see cref="string"/> represented by <paramref name="ptr"/>.
/// </returns>
protected static string PtrToStringUTF8(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return null;
List<byte> buff = new List<byte>();
int offset = 0;
for (; ; offset++) {
byte currentByte = Marshal.ReadByte(ptr, offset);
if (currentByte == 0)
break;
buff.Add(currentByte);
}
return Encoding.UTF8.GetString(buff.ToArray());
}
#endregion
#region Function Linkage
/// <summary>
/// Get the current location of the
/// </summary>
/// <returns></returns>
protected static string GetAssemblyLocation()
{
#if NETSTANDARD1_1
string assemblyPath = null; // XXX
#elif NETSTANDARD1_4 || NETCORE
string assemblyPath = Directory.GetCurrentDirectory();
#else
string assemblyPath = Assembly.GetAssembly(typeof(KhronosApi)).Location;
if (string.IsNullOrEmpty(assemblyPath) == false)
assemblyPath = Path.GetDirectoryName(assemblyPath);
else
assemblyPath = Directory.GetCurrentDirectory();
#endif
return assemblyPath;
}
/// <summary>
/// Delegate used for getting a procedure address.
/// </summary>
/// <param name="path">
/// A <see cref="string"/> that specifies the path of the library to load the procedure from.
/// </param>
/// <param name="function">
/// A <see cref="string"/> that specifies the name of the procedure to be loaded.
/// </param>
/// <returns>
/// It returns a <see cref="IntPtr"/> that specifies the function pointer. If not defined, it
/// returns <see cref="IntPtr.Zero"/>.
/// </returns>
public delegate IntPtr GetAddressDelegate(string path, string function);
/// <summary>
/// Utility for <see cref="GetAddressDelegate"/> for loading procedures using the OS loader.
/// </summary>
/// <param name="path">
/// A <see cref="string"/> that specifies the path of the library to load the procedure from.
/// </param>
/// <param name="function">
/// A <see cref="string"/> that specifies the name of the procedure to be loaded.
/// </param>
/// <returns>
/// It returns a <see cref="IntPtr"/> that specifies the function pointer. If not defined, it
/// returns <see cref="IntPtr.Zero"/>.
/// </returns>
protected static IntPtr GetProcAddressOS(string path, string function) { return Khronos.GetProcAddressOS.GetProcAddress(path, function); }
/// <summary>
/// Link delegates field using import declaration, using platform specific method for determining procedures address.
/// </summary>
internal static void BindAPIFunction<T>(string path, string functionName, GetAddressDelegate getProcAddress, KhronosVersion version, ExtensionsCollection extensions)
{
FunctionContext functionContext = GetFunctionContext(typeof(T));
Debug.Assert(functionContext != null);
BindAPIFunction(path, getProcAddress, functionContext.GetFunction(functionName), version, extensions);
}
/// <summary>
/// Link delegates fields using import declarations.
/// </summary>
/// <param name="path">
/// A <see cref="string"/> that specifies the assembly file path containing the import functions.
/// </param>
/// <param name="getAddress">
/// A <see cref="GetAddressDelegate"/> used for getting function pointers.
/// </param>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="path"/> or <paramref name="getAddress"/> is null.
/// </exception>
internal static void BindAPI<T>(string path, GetAddressDelegate getAddress, KhronosVersion version)
{
BindAPI<T>(path, getAddress, version, null);
}
/// <summary>
/// Link delegates fields using import declarations.
/// </summary>
/// <param name="path">
/// A <see cref="string"/> that specifies the assembly file path containing the import functions.
/// </param>
/// <param name="getAddress">
/// A <see cref="GetAddressDelegate"/> used for getting function pointers.
/// </param>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="path"/> or <paramref name="getAddress"/> is null.
/// </exception>
internal static void BindAPI<T>(string path, GetAddressDelegate getAddress, KhronosVersion version, ExtensionsCollection extensions)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (getAddress == null)
throw new ArgumentNullException(nameof(getAddress));
FunctionContext functionContext = GetFunctionContext(typeof(T));
Debug.Assert(functionContext != null);
foreach (FieldInfo fi in functionContext.Delegates)
BindAPIFunction(path, getAddress, fi, version, extensions);
}
/// <summary>
/// Link delegates fields using import declarations.
/// </summary>
/// <param name="path">
/// A <see cref="string"/> that specifies the assembly file path containing the import functions.
/// </param>
/// <param name="getAddress">
/// A <see cref="GetAddressDelegate"/> used for getting function pointers.
/// </param>
/// <param name="function">
/// A <see cref="FieldInfo"/> that specifies the underlying function field to be updated.
/// </param>
/// <param name="version"></param>
/// <param name="extensions"></param>
private static void BindAPIFunction(string path, GetAddressDelegate getAddress, FieldInfo function, KhronosVersion version, ExtensionsCollection extensions)
{
Debug.Assert(path != null);
Debug.Assert(getAddress != null);
Debug.Assert(function != null);
RequiredByFeatureAttribute requiredByFeature = null;
List<RequiredByFeatureAttribute> requiredByExtensions = new List<RequiredByFeatureAttribute>();
string defaultName = function.Name.Substring(1); // Delegate name always prefixes with 'p'
if (version != null || extensions != null) {
bool isRemoved = false;
#region Check Requirement
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE
IEnumerable<Attribute> attrRequired = new List<Attribute>(function.GetCustomAttributes(typeof(RequiredByFeatureAttribute)));
#else
IEnumerable<Attribute> attrRequired = Attribute.GetCustomAttributes(function, typeof(RequiredByFeatureAttribute));
#endif
// ReSharper disable once PossibleInvalidCastExceptionInForeachLoop
foreach (RequiredByFeatureAttribute attr in attrRequired) {
// Check for API support
if (attr.IsSupported(version, extensions) == false)
continue;
// Keep track of the features requiring this command
if (attr.FeatureVersion != null) {
// Version feature: keep track only of the maximum version
if (requiredByFeature == null || requiredByFeature.FeatureVersion < attr.FeatureVersion)
requiredByFeature = attr;
} else {
// Extension feature: collect every supporting extension
requiredByExtensions.Add(attr);
}
}
#endregion
#region Check Deprecation/Removal
if (requiredByFeature != null) {
// Note: indeed the feature could be supported; check whether it is removed; this is checked only if
// a non-extension feature is detected: extensions cannot remove commands
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE
Attribute[] attrRemoved = new List<Attribute>(function.GetCustomAttributes(typeof(RemovedByFeatureAttribute))).ToArray();
#else
Attribute[] attrRemoved = Attribute.GetCustomAttributes(function, typeof(RemovedByFeatureAttribute));
#endif
KhronosVersion maxRemovedVersion = null;
// ReSharper disable once PossibleInvalidCastExceptionInForeachLoop
foreach (RemovedByFeatureAttribute attr in attrRemoved) {
// Check for API support
if (attr.IsRemoved(version, extensions) == false)
continue;
// Removed!
isRemoved = true;
// Keep track of the maximum API version removing this command
if (maxRemovedVersion == null || maxRemovedVersion < attr.FeatureVersion)
maxRemovedVersion = attr.FeatureVersion;
}
// Check for resurrection
if (isRemoved) {
Debug.Assert(requiredByFeature != null);
Debug.Assert(maxRemovedVersion != null);
if (requiredByFeature.FeatureVersion > maxRemovedVersion)
isRemoved = false;
}
}
#endregion
// Do not check feature requirements in case of removal. Note: extensions are checked all the same
if (isRemoved)
requiredByFeature = null;
}
// Load function pointer
IntPtr importAddress;
if (requiredByFeature != null || version == null) {
// Load command address (version feature)
string functionName = defaultName;
if (requiredByFeature?.EntryPoint != null)
functionName = requiredByFeature.EntryPoint;
if ((importAddress = getAddress(path, functionName)) != IntPtr.Zero) {
BindAPIFunction(function, importAddress);
return;
}
}
// Load command address (extension features)
foreach (RequiredByFeatureAttribute extensionFeature in requiredByExtensions) {
string functionName = extensionFeature.EntryPoint ?? defaultName;
if ((importAddress = getAddress(path, functionName)) != IntPtr.Zero) {
BindAPIFunction(function, importAddress);
return;
}
}
// Function not implemented: reset
function.SetValue(null, null);
}
/// <summary>
/// Set fields using import declarations.
/// </summary>
/// <param name="function">
/// A <see cref="FieldInfo"/> that specifies the underlying function field to be updated.
/// </param>
/// <param name="importAddress">
/// A <see cref="IntPtr"/> that specifies the function pointer.
/// </param>
private static void BindAPIFunction(FieldInfo function, IntPtr importAddress)
{
Debug.Assert(function != null);
Debug.Assert(importAddress != IntPtr.Zero);
Delegate delegatePtr = Marshal.GetDelegateForFunctionPointer(importAddress, function.FieldType);
Debug.Assert(delegatePtr != null);
function.SetValue(null, delegatePtr);
}
/// <summary>
/// Determine whether an API command is compatible with the specific API version and extensions registry.
/// </summary>
/// <param name="function">
/// A <see cref="FieldInfo"/> that specifies the command delegate to set. This argument make avail attributes useful
/// to determine the actual support for this command.
/// </param>
/// <param name="version">
/// The <see cref="KhronosVersion"/> that specifies the API version.
/// </param>
/// <param name="extensions">
/// The <see cref="ExtensionsCollection"/> that specifies the API extensions registry.
/// </param>
/// <returns>
/// It returns a <see cref="Boolean"/> that specifies whether <paramref name="function"/> is supported by the
/// API having the version <paramref name="version"/> and the extensions registry <paramref name="extensions"/>.
/// </returns>
internal static bool IsCompatibleField(FieldInfo function, KhronosVersion version, ExtensionsCollection extensions)
{
Debug.Assert(function != null);
Debug.Assert(version != null);
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE
IEnumerable<Attribute> attrRequired = new List<Attribute>(function.GetCustomAttributes(typeof(RequiredByFeatureAttribute)));
#else
IEnumerable<Attribute> attrRequired = Attribute.GetCustomAttributes(function, typeof(RequiredByFeatureAttribute));
#endif
KhronosVersion maxRequiredVersion = null;
bool isRequired = false, isRemoved = false;
// ReSharper disable once PossibleInvalidCastExceptionInForeachLoop
foreach (RequiredByFeatureAttribute attr in attrRequired) {
// Check for API support
if (attr.IsSupported(version, extensions) == false)
continue;
// Supported!
isRequired = true;
// Keep track of the maximum API version supporting this command
// Note: useful for resurrected commands after deprecation
if (maxRequiredVersion == null || maxRequiredVersion < attr.FeatureVersion)
maxRequiredVersion = attr.FeatureVersion;
}
if (isRequired) {
// Note: indeed the feature could be supported; check whether it is removed
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE
IEnumerable<Attribute> attrRemoved = new List<Attribute>(function.GetCustomAttributes(typeof(RemovedByFeatureAttribute)));
#else
IEnumerable<Attribute> attrRemoved = Attribute.GetCustomAttributes(function, typeof(RemovedByFeatureAttribute));
#endif
KhronosVersion maxRemovedVersion = null;
// ReSharper disable once PossibleInvalidCastExceptionInForeachLoop
foreach (RemovedByFeatureAttribute attr in attrRemoved) {
if (attr.IsRemoved(version, extensions) == false)
continue;
// Removed!
isRemoved = true;
// Keep track of the maximum API version removing this command
if (maxRemovedVersion == null || maxRemovedVersion < attr.FeatureVersion)
maxRemovedVersion = attr.FeatureVersion;
}
// Check for resurrection
if (isRemoved) {
Debug.Assert(maxRequiredVersion != null);
Debug.Assert(maxRemovedVersion != null);
if (maxRequiredVersion > maxRemovedVersion)
isRemoved = false;
}
return isRemoved == false;
}
return false;
}
/// <summary>
/// Get the delegates methods for the specified type.
/// </summary>
/// <param name="type">
/// A <see cref="Type"/> that specifies the type used for detecting delegates declarations.
/// </param>
/// <returns>
/// It returns the <see cref="DelegateList"/> for <paramref name="type"/>.
/// </returns>
private static DelegateList GetDelegateList(Type type)
{
#if NETSTANDARD1_1 || NETSTANDARD1_4
TypeInfo delegatesClass = type.GetTypeInfo().GetDeclaredNestedType("Delegates");
Debug.Assert(delegatesClass != null);
return (new DelegateList(delegatesClass.DeclaredFields));
#else
Type delegatesClass = type.GetNestedType("Delegates", BindingFlags.Static | BindingFlags.NonPublic);
Debug.Assert(delegatesClass != null);
return new DelegateList(delegatesClass.GetFields(BindingFlags.Static | BindingFlags.NonPublic));
#endif
}
/// <summary>
/// Get the <see cref="FunctionContext"/> corresponding to a specific type.
/// </summary>
/// <param name="type">
/// A <see cref="Type"/> that specifies the type used for loading function pointers.
/// </param>
/// <returns></returns>
private static FunctionContext GetFunctionContext(Type type)
{
FunctionContext functionContext;
if (_FunctionContext.TryGetValue(type, out functionContext))
return functionContext;
functionContext = new FunctionContext(type);
_FunctionContext.Add(type, functionContext);
return functionContext;
}
/// <summary>
/// Information required for loading function pointers.
/// </summary>
private class FunctionContext
{
/// <summary>
/// Construct a FunctionContext on a specific <see cref="Type"/>.
/// </summary>
/// <param name="type">
/// The <see cref="Type"/> deriving from <see cref="KhronosApi"/>.
/// </param>
public FunctionContext(Type type)
{
#if NETSTANDARD1_1 || NETSTANDARD1_4
TypeInfo delegatesClass = type.GetTypeInfo().GetDeclaredNestedType("Delegates");
Debug.Assert(delegatesClass != null);
#else
Type delegatesClass = type.GetNestedType("Delegates", BindingFlags.Static | BindingFlags.NonPublic);
Debug.Assert(delegatesClass != null);
#endif
_DelegateType = delegatesClass;
Delegates = GetDelegateList(type);
}
/// <summary>
/// Get the field representing the delegate for an API function.
/// </summary>
/// <param name="functionName">
/// A <see cref="string"/> that specifies the native function name.
/// </param>
/// <returns>
/// It returns the <see cref="FieldInfo"/> for the function.
/// </returns>
public FieldInfo GetFunction(string functionName)
{
if (functionName == null)
throw new ArgumentNullException(nameof(functionName));
#if NETSTANDARD1_1 || NETSTANDARD1_4
FieldInfo functionField = _DelegateType.GetDeclaredField("p" + functionName);
Debug.Assert(functionField != null);
#else
FieldInfo functionField = _DelegateType.GetField("p" + functionName, BindingFlags.Static | BindingFlags.NonPublic);
Debug.Assert(functionField != null);
#endif
return functionField;
}
#if NETSTANDARD1_1 || NETSTANDARD1_4
// <summary>
/// Type containing all delegates.
/// </summary>
private readonly TypeInfo _DelegateType;
#else
/// <summary>
/// Type containing all delegates.
/// </summary>
private readonly Type _DelegateType;
#endif
/// <summary>
/// The delegate fields list for the underlying type.
/// </summary>
public readonly DelegateList Delegates;
}
/// <summary>
/// Mapping between <see cref="FunctionContext"/> and the underlying <see cref="Type"/>.
/// </summary>
private static readonly Dictionary<Type, FunctionContext> _FunctionContext = new Dictionary<Type, FunctionContext>();
#endregion
#region Extension Support
/// <summary>
/// Attribute asserting the extension requiring the underlying member.
/// </summary>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
public sealed class ExtensionAttribute : Attribute
{
/// <summary>
/// Construct a ExtensionAttribute, specifying the extension name.
/// </summary>
/// <param name="extensionName">
/// A <see cref="string"/> that specifies the name of the extension that requires the element.
/// </param>
/// <exception cref="ArgumentException">
/// Exception thrown if <paramref name="extensionName"/> is null or empty.
/// </exception>
public ExtensionAttribute(string extensionName)
{
ExtensionName = extensionName;
}
/// <summary>
/// The name of the extension.
/// </summary>
public readonly string ExtensionName;
/// <summary>
///
/// </summary>
public string Api;
}
/// <summary>
/// Attribute asserting the extension requiring the underlying member.
/// </summary>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
public sealed class CoreExtensionAttribute : Attribute
{
#region Constructors
/// <summary>
/// Construct a CoreExtensionAttribute specifying the version numbers.
/// </summary>
/// <param name="major">
/// A <see cref="Int32"/> that specifies that major version number.
/// </param>
/// <param name="minor">
/// A <see cref="Int32"/> that specifies that minor version number.
/// </param>
/// <param name="api">
/// A <see cref="string"/> that specifies the API name.
/// </param>
/// <exception cref="ArgumentException">
/// Exception thrown if <paramref name="major"/> is less or equals to 0, or if <paramref name="minor"/> is less than 0.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="api"/> is null.
/// </exception>
public CoreExtensionAttribute(int major, int minor, string api)
{
Version = new KhronosVersion(major, minor, 0, api);
}
/// <summary>
/// Construct a CoreExtensionAttribute specifying the version numbers.
/// </summary>
/// <param name="major">
/// A <see cref="Int32"/> that specifies that major version number.
/// </param>
/// <param name="minor">
/// A <see cref="Int32"/> that specifies that minor version number.
/// </param>
/// <exception cref="ArgumentException">
/// Exception thrown if <paramref name="major"/> is less or equals to 0, or if <paramref name="minor"/> is less than 0.
/// </exception>
public CoreExtensionAttribute(int major, int minor) :
this(major, minor, KhronosVersion.ApiGl)
{
}
#endregion
#region Required API Version
/// <summary>
/// The required major OpenGL version for supporting the extension.
/// </summary>
public readonly KhronosVersion Version;
#endregion
}
/// <summary>
/// Base class for managing OpenGL extensions.
/// </summary>
public abstract class ExtensionsCollection
{
/// <summary>
/// Check whether the specified extension is supported by current platform.
/// </summary>
/// <param name="extensionName">
/// A <see cref="string"/> that specifies the extension name.
/// </param>
/// <returns>
/// It returns a boolean value indicating whether the extension identified with <paramref name="extensionName"/>
/// is supported or not by the current platform.
/// </returns>
public bool HasExtensions(string extensionName)
{
if (extensionName == null)
throw new ArgumentNullException(nameof(extensionName));
return _ExtensionsRegistry.ContainsKey(extensionName);
}
/// <summary>
/// Force extension support.
/// </summary>
/// <param name="extensionName">
/// A <see cref="string"/> that specifies the extension name.
/// </param>
internal void EnableExtension(string extensionName)
{
if (extensionName == null)
throw new ArgumentNullException(nameof(extensionName));
_ExtensionsRegistry[extensionName] = true;
}
/// <summary>
/// Query the supported extensions.
/// </summary>
/// <param name="version">
/// The <see cref="KhronosVersion"/> that specifies the version of the API context.
/// </param>
/// <param name="extensionsString">
/// A string that specifies the supported extensions, those names are separated by spaces.
/// </param>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="extensionsString"/> is null.
/// </exception>
protected void Query(KhronosVersion version, string extensionsString)
{
if (extensionsString == null)
throw new ArgumentNullException(nameof(extensionsString));
Query(version, extensionsString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
}
/// <summary>
/// Query the supported extensions.
/// </summary>
/// <param name="version">
/// The <see cref="KhronosVersion"/> that specifies the version of the API context.
/// </param>
/// <param name="extensions">
/// An array of strings that specifies the supported extensions.
/// </param>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="extensions"/> is null.
/// </exception>
protected void Query(KhronosVersion version, string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException(nameof(extensions));
// Cache extension names in registry
_ExtensionsRegistry.Clear();
foreach (string extension in extensions)
if (!_ExtensionsRegistry.ContainsKey(extension))
_ExtensionsRegistry.Add(extension, true);
// Sync fields
SyncMembers(version);
}
/// <summary>
/// Set all fields of this ExtensionsCollection, depending on current extensions.
/// </summary>
/// <param name="version">
/// The <see cref="KhronosVersion"/> that specifies the context version/API. It can be null.
/// </param>
protected internal void SyncMembers(KhronosVersion version)
{
Type thisType = GetType();
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE
IEnumerable<FieldInfo> thisTypeFields = thisType.GetTypeInfo().DeclaredFields;
#else
IEnumerable<FieldInfo> thisTypeFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public);
#endif
foreach (FieldInfo fieldInfo in thisTypeFields) {
// Check boolean field (defensive)
// Debug.Assert(fieldInfo.FieldType == typeof(bool));
if (fieldInfo.FieldType != typeof(bool))
continue;
bool support = false;
// Support by extension
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE
IEnumerable<Attribute> extensionAttributes = fieldInfo.GetCustomAttributes(typeof(ExtensionAttribute));
#else
IEnumerable<Attribute> extensionAttributes = Attribute.GetCustomAttributes(fieldInfo, typeof(ExtensionAttribute));
#endif
// ReSharper disable once PossibleInvalidCastExceptionInForeachLoop
foreach (ExtensionAttribute extensionAttribute in extensionAttributes) {
if (!_ExtensionsRegistry.ContainsKey(extensionAttribute.ExtensionName))
continue;
if (version != null && version.Api != null && extensionAttribute.Api != null && !Regex.IsMatch(version.Api, "^" + extensionAttribute.Api + "$"))
continue;
support = true;
break;
}
// Support by version
if (version != null && support == false) {
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE
IEnumerable<Attribute> coreAttributes = fieldInfo.GetCustomAttributes(typeof(CoreExtensionAttribute));
#else
IEnumerable<Attribute> coreAttributes = Attribute.GetCustomAttributes(fieldInfo, typeof(CoreExtensionAttribute));
#endif
// ReSharper disable once PossibleInvalidCastExceptionInForeachLoop
foreach (CoreExtensionAttribute coreAttribute in coreAttributes) {
if (version.Api != coreAttribute.Version.Api || version < coreAttribute.Version)
continue;
support = true;
break;
}
}
fieldInfo.SetValue(this, support);
}
}
/// <summary>
/// Registry of supported extensions.
/// </summary>
private readonly Dictionary<string, bool> _ExtensionsRegistry = new Dictionary<string, bool>();
}
#endregion
#region Command Checking
/// <summary>
/// Check whether commands implemented by the current driver have a corresponding extension declaring the
/// support of them.
/// </summary>
/// <typeparam name="T">
/// The type of the KhronosApi to inspect for commands.
/// </typeparam>
/// <param name="version">
/// The <see cref="KhronosVersion"/> currently implemented by the current context on this thread.
/// </param>
/// <param name="extensions">
/// The <see cref="ExtensionsCollection"/> that specifies the extensions supported by the driver.
/// </param>
protected static void CheckExtensionCommands<T>(KhronosVersion version, ExtensionsCollection extensions, bool enableExtensions) where T : KhronosApi
{
if (version == null)
throw new ArgumentNullException(nameof(version));
if (extensions == null)
throw new ArgumentNullException(nameof(extensions));
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETCORE
throw new NotImplementedException();
#else
FunctionContext functionContext = GetFunctionContext(typeof(T));
Debug.Assert(functionContext != null);
LogComment($"Checking commands for {version}");
Dictionary<string, List<Type>> hiddenVersions = new Dictionary<string, List<Type>>();
Dictionary<string, bool> hiddenExtensions = new Dictionary<string, bool>();
foreach (FieldInfo fi in functionContext.Delegates) {
Delegate fiDelegateType = (Delegate)fi.GetValue(null);
bool commandDefined = fiDelegateType != null;
bool supportedByFeature = false;
#if DEBUG_VERBOSE
string commandName = fi.Name.Substring(3);
#endif
// Get the delegate type
Type delegateType = fi.DeclaringType?.GetNestedType(fi.Name.Substring(1), BindingFlags.Public | BindingFlags.NonPublic);
if (delegateType == null)
continue; // Support fields names not in sync with delegate types
// TODO Why not use 'fi' directly for getting attributes? They should be in sync
IEnumerable<object> requiredByFeatureAttributes = delegateType.GetCustomAttributes(typeof(RequiredByFeatureAttribute), false);
foreach (RequiredByFeatureAttribute requiredByFeatureAttribute in requiredByFeatureAttributes)
supportedByFeature |= requiredByFeatureAttribute.IsSupported(version, extensions);
// Find the underlying extension
RequiredByFeatureAttribute hiddenVersionAttrib = null;
RequiredByFeatureAttribute hiddenExtensionAttrib = null;
foreach (RequiredByFeatureAttribute requiredByFeatureAttribute in requiredByFeatureAttributes) {
if (requiredByFeatureAttribute.IsSupportedApi(version.Api) == false) {
// Version attribute
if (hiddenVersionAttrib == null)
hiddenVersionAttrib = requiredByFeatureAttribute;
} else {
// Extension attribute
if (hiddenExtensionAttrib == null)
hiddenExtensionAttrib = requiredByFeatureAttribute;
}
}
if (commandDefined != supportedByFeature) {
#if DEBUG_VERBOSE
string supportString = "any feature";
if (hiddenVersionAttrib != null) {
supportString = hiddenVersionAttrib.FeatureName;
if (hiddenExtensionAttrib != null)
supportString += " or ";
}
if (hiddenExtensionAttrib != null) {
if (hiddenVersionAttrib == null)
supportString = string.Empty;
supportString += hiddenExtensionAttrib.FeatureName;
}
#endif
if (commandDefined) {
#if DEBUG_VERBOSE
LogComment("The command {0} is defined, but {1} support is not advertised.", commandName, supportString);
#endif
if (hiddenVersionAttrib != null && hiddenExtensionAttrib == null) {
List<Type> versionDelegates;
if (hiddenVersions.TryGetValue(hiddenVersionAttrib.FeatureName, out versionDelegates) == false)
hiddenVersions.Add(hiddenVersionAttrib.FeatureName, versionDelegates = new List<Type>());
versionDelegates.Add(delegateType);
}
if (hiddenExtensionAttrib != null) {
// Eventually leave to false for incomplete extensions
if (hiddenExtensions.ContainsKey(hiddenExtensionAttrib.FeatureName) == false)
hiddenExtensions.Add(hiddenExtensionAttrib.FeatureName, true);
}
} else {
#if DEBUG_VERBOSE
LogComment("The command {0} is not defined, but required by some feature.", commandName);
#endif
}
}
// Partial extensions are not supported
if (hiddenExtensionAttrib != null && commandDefined == false && hiddenExtensions.ContainsKey(hiddenExtensionAttrib.FeatureName))
hiddenExtensions[hiddenExtensionAttrib.FeatureName] = false;
}
if (hiddenExtensions.Count > 0) {
LogComment($"Found {hiddenExtensions.Count} experimental extensions:");
foreach (KeyValuePair<string, bool> hiddenExtension in hiddenExtensions)
LogComment(string.Format($"- {0}: {1}", hiddenExtension.Key, hiddenExtension.Value ? "experimental" : "experimental (partial, unsupported)"));
}
if (hiddenVersions.Count > 0) {
LogComment($"Found {hiddenVersions.Count} experimental version commands:");
foreach (KeyValuePair<string, List<Type>> hiddenVersion in hiddenVersions) {
LogComment($"- {hiddenVersion.Key}");
foreach (Type delegateType in hiddenVersion.Value)
LogComment($" > {delegateType.Name}");
}
}
if (enableExtensions) {
bool sync = false;
foreach (KeyValuePair<string, bool> hiddenExtension in hiddenExtensions) {
if (hiddenExtension.Value == false)
continue; // Do not enable partial extension
extensions.EnableExtension(hiddenExtension.Key);
sync = true;
}
if (sync)
extensions.SyncMembers(version);
}
#endif
}
#endregion
#region Command Logging
/// <summary>
/// Get whether assembly is compiled with debug logging support (GL command logging).
/// </summary>
public static bool HasdDebugLogging
{
#if GL_DEBUG
get { return true; }
#else
get { return false; }
#endif
}
/// <summary>
/// Flag used for enabling/disabling procedure logging. Default is false.
/// </summary>
public static bool LogEnabled { get; set; }
/// <summary>
/// Event raised whenever an API command is called.
/// </summary>
public static event EventHandler<KhronosLogEventArgs> Log;
/// <summary>
/// Utility route for raising <see cref="Log"/> event.
/// </summary>
/// <param name="args">
/// The <see cref="KhronosLogEventArgs"/> passed to the event handlers.
/// </param>
protected internal static void RaiseLog(KhronosLogEventArgs args)
{
if (args == null)
throw new ArgumentNullException(nameof(args));
if (!LogEnabled || Log == null)
return;
foreach (Delegate @delegate in Log.GetInvocationList()) {
EventHandler<KhronosLogEventArgs> eventHandler = (EventHandler<KhronosLogEventArgs>) @delegate;
try {
eventHandler(null, args);
} catch { /* Fail-safe */ }
}
}
/// <summary>
/// Log a comment.
/// </summary>
/// <param name="comment">
/// A <see cref="string"/> that specifies the comment format string.
/// </param>
public static void LogComment(string comment)
{
if (comment == null)
throw new ArgumentNullException(nameof(comment));
if (LogEnabled)
RaiseLog(new KhronosLogEventArgs(comment));
}
/// <summary>
/// Load an API command call.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that specifies the name of the API command.
/// </param>
/// <param name="returnValue">
/// A <see cref="Object"/> that specifies the returned value, if any.
/// </param>
/// <param name="args">
/// A <see cref="T:Object[]"/> that specifies the API command arguments, if any.
/// </param>
[Conditional("GL_DEBUG")]
public static void LogCommand(string name, object returnValue, params object[] args)
{
if (LogEnabled)
RaiseLog(new KhronosLogEventArgs(null, name, args, returnValue));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using RogueSharp;
using RogueSharp.DiceNotation;
using UnityEngine;
public class MapGenerator
{
private readonly int _width;
private readonly int _height;
private readonly int _maxRooms;
private readonly int _roomMaxSize;
private readonly int _roomMinSize;
private readonly int _level;
private readonly DungeonMap _map;
private readonly EquipmentGenerator _equipmentGenerator;
public MapGenerator( int width, int height, int maxRooms, int roomMaxSize, int roomMinSize, int level )
{
_width = width;
_height = height;
_maxRooms = maxRooms;
_roomMaxSize = roomMaxSize;
_roomMinSize = roomMinSize;
_level = level;
_map = new DungeonMap();
_equipmentGenerator = new EquipmentGenerator( level );
}
public DungeonMap CreateMap()
{
Clean();
_map.Initialize(_width, _height);
for (int r = 0; r < _maxRooms; r++)
{
int roomWidth = Game.Random.Next(_roomMinSize, _roomMaxSize);
int roomHeight = Game.Random.Next(_roomMinSize, _roomMaxSize);
int roomXPosition = Game.Random.Next(0, _width - roomWidth - 1);
int roomYPosition = Game.Random.Next(0, _height - roomHeight - 1);
var newRoom = new Rectangle(roomXPosition, roomYPosition, roomWidth, roomHeight);
bool newRoomIntersects = _map.Rooms.Any(room => newRoom.Intersects(room));
if (!newRoomIntersects)
{
_map.Rooms.Add(newRoom);
}
}
foreach (Rectangle room in _map.Rooms)
{
CreateMap(room);
}
for (int r = 0; r < _map.Rooms.Count; r++)
{
if (r == 0)
{
continue;
}
int previousRoomCenterX = _map.Rooms[r - 1].Center.X;
int previousRoomCenterY = _map.Rooms[r - 1].Center.Y;
int currentRoomCenterX = _map.Rooms[r].Center.X;
int currentRoomCenterY = _map.Rooms[r].Center.Y;
if (Game.Random.Next(0, 2) == 0)
{
CreateHorizontalTunnel(previousRoomCenterX, currentRoomCenterX, previousRoomCenterY);
CreateVerticalTunnel(previousRoomCenterY, currentRoomCenterY, currentRoomCenterX);
}
else
{
CreateVerticalTunnel(previousRoomCenterY, currentRoomCenterY, previousRoomCenterX);
CreateHorizontalTunnel(previousRoomCenterX, currentRoomCenterX, currentRoomCenterY);
}
}
foreach (Rectangle room in _map.Rooms)
{
CreateDoors(room);
}
CreateStairs();
PlacePlayer();
PlaceMonsters();
PlaceEquipment();
PlaceItems();
PlaceAbility();
return _map;
}
private void CreateMap(Rectangle room)
{
for (int x = room.Left + 1; x < room.Right; x++)
{
for (int y = room.Top + 1; y < room.Bottom; y++)
{
_map.SetCellProperties(x, y, true, true);
}
}
}
private void CreateHorizontalTunnel( int xStart, int xEnd, int yPosition )
{
for ( int x = Math.Min( xStart, xEnd ); x <= Math.Max( xStart, xEnd ); x++ )
{
_map.SetCellProperties( x, yPosition, true, true );
}
}
private void CreateVerticalTunnel( int yStart, int yEnd, int xPosition )
{
for ( int y = Math.Min( yStart, yEnd ); y <= Math.Max( yStart, yEnd ); y++ )
{
_map.SetCellProperties( xPosition, y, true, true );
}
}
private void CreateDoors( Rectangle room )
{
int xMin = room.Left;
int xMax = room.Right;
int yMin = room.Top;
int yMax = room.Bottom;
List<RogueSharp.Cell> borderCells = _map.GetCellsAlongLine( xMin, yMin, xMax, yMin ).ToList();
borderCells.AddRange( _map.GetCellsAlongLine( xMin, yMin, xMin, yMax ) );
borderCells.AddRange( _map.GetCellsAlongLine( xMin, yMax, xMax, yMax ) );
borderCells.AddRange( _map.GetCellsAlongLine( xMax, yMin, xMax, yMax ) );
foreach (RogueSharp.Cell cell in borderCells )
{
if ( IsPotentialDoor( cell ) )
{
_map.SetCellProperties( cell.X, cell.Y, false, true );
_map.Doors.Add( new Door {
X = cell.X,
Y = cell.Y,
IsOpen = false
} );
}
}
}
private bool IsPotentialDoor(RogueSharp.Cell cell )
{
if ( !cell.IsWalkable )
{
return false;
}
RogueSharp.Cell right = _map.GetCell( cell.X + 1, cell.Y );
RogueSharp.Cell left = _map.GetCell( cell.X - 1, cell.Y );
RogueSharp.Cell top = _map.GetCell( cell.X, cell.Y - 1 );
RogueSharp.Cell bottom = _map.GetCell( cell.X, cell.Y + 1 );
if ( _map.GetDoor( cell.X, cell.Y ) != null ||
_map.GetDoor( right.X, right.Y ) != null ||
_map.GetDoor( left.X, left.Y ) != null ||
_map.GetDoor( top.X, top.Y ) != null ||
_map.GetDoor( bottom.X, bottom.Y ) != null )
{
return false;
}
if ( right.IsWalkable && left.IsWalkable && !top.IsWalkable && !bottom.IsWalkable )
{
return true;
}
if ( !right.IsWalkable && !left.IsWalkable && top.IsWalkable && bottom.IsWalkable )
{
return true;
}
return false;
}
private void CreateStairs()
{
_map.StairsUp = new Stairs {
X = _map.Rooms.First().Center.X + 1,
Y = _map.Rooms.First().Center.Y,
IsUp = true
};
_map.StairsDown = new Stairs {
X = _map.Rooms.Last().Center.X,
Y = _map.Rooms.Last().Center.Y,
IsUp = false
};
}
private void PlaceMonsters()
{
foreach ( var room in _map.Rooms )
{
if ( Dice.Roll( "1D10" ) < 7 )
{
var numberOfMonsters = Dice.Roll( "1D4" );
for ( int i = 0; i < numberOfMonsters; i++ )
{
if ( _map.DoesRoomHaveWalkableSpace( room ) )
{
Point randomRoomLocation = _map.GetRandomLocationInRoom( room );
if ( randomRoomLocation != null )
{
_map.AddMonster( ActorGenerator.CreateMonster( _level, _map.GetRandomLocationInRoom( room ) ) );
}
}
}
}
}
}
private void PlaceEquipment()
{
foreach ( var room in _map.Rooms )
{
if ( Dice.Roll( "1D10" ) < 3 )
{
if ( _map.DoesRoomHaveWalkableSpace( room ) )
{
Point randomRoomLocation = _map.GetRandomLocationInRoom( room );
if ( randomRoomLocation != null )
{
Equipment equipment;
try
{
equipment = _equipmentGenerator.CreateEquipment();
}
catch ( InvalidOperationException )
{
// no more equipment to generate so just quit adding to this level
return;
}
Point location = _map.GetRandomLocationInRoom( room );
_map.AddTreasure( location.X, location.Y, equipment );
}
}
}
}
}
private void PlaceItems()
{
foreach ( var room in _map.Rooms )
{
if ( Dice.Roll( "1D10" ) < 3 )
{
if ( _map.DoesRoomHaveWalkableSpace( room ) )
{
Point randomRoomLocation = _map.GetRandomLocationInRoom( room );
if ( randomRoomLocation != null )
{
Item item = ItemGenerator.CreateItem();
Point location = _map.GetRandomLocationInRoom( room );
_map.AddTreasure( location.X, location.Y, item );
}
}
}
}
}
private void PlacePlayer()
{
Player player = ActorGenerator.CreatePlayer();
player.X = _map.Rooms[0].Center.X;
player.Y = _map.Rooms[0].Center.Y;
_map.AddPlayer( player );
}
private void PlaceAbility()
{
if ( _level == 1 || _level % 3 == 0 )
{
try
{
var ability = AbilityGenerator.CreateAbility();
int roomIndex = Game.Random.Next( 0, _map.Rooms.Count - 1 );
Point location = _map.GetRandomLocationInRoom( _map.Rooms[roomIndex] );
_map.AddTreasure( location.X, location.Y, ability );
}
catch ( InvalidOperationException )
{
}
}
}
private void Clean()
{
for (int x = 0; x < _width; x++)
{
for (int y = 0; y < _height; y++)
{
Display.CellAt(0, x, y).SetContent(" ", Color.black, Color.black);
}
}
}
}
| |
/*
* Copyright (c) 2007-2009, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Interfaces;
using OpenMetaverse.Http;
namespace OpenMetaverse
{
/// <summary>
/// Capabilities is the name of the bi-directional HTTP REST protocol
/// used to communicate non real-time transactions such as teleporting or
/// group messaging
/// </summary>
public partial class Caps
{
/// <summary>
/// Triggered when an event is received via the EventQueueGet
/// capability
/// </summary>
/// <param name="capsKey">Event name</param>
/// <param name="message">Decoded event data</param>
/// <param name="simulator">The simulator that generated the event</param>
//public delegate void EventQueueCallback(string message, StructuredData.OSD body, Simulator simulator);
public delegate void EventQueueCallback(string capsKey, IMessage message, Simulator simulator);
/// <summary>Reference to the simulator this system is connected to</summary>
public Simulator Simulator;
internal string _SeedCapsURI;
internal Dictionary<string, Uri> _Caps = new Dictionary<string, Uri>();
private CapsClient _SeedRequest;
private EventQueueClient _EventQueueCap = null;
/// <summary>Capabilities URI this system was initialized with</summary>
public string SeedCapsURI { get { return _SeedCapsURI; } }
/// <summary>Whether the capabilities event queue is connected and
/// listening for incoming events</summary>
public bool IsEventQueueRunning
{
get
{
if (_EventQueueCap != null)
return _EventQueueCap.Running;
else
return false;
}
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="simulator"></param>
/// <param name="seedcaps"></param>
internal Caps(Simulator simulator, string seedcaps)
{
Simulator = simulator;
_SeedCapsURI = seedcaps;
MakeSeedRequest();
}
public void Disconnect(bool immediate)
{
Logger.Log(String.Format("Caps system for {0} is {1}", Simulator,
(immediate ? "aborting" : "disconnecting")), Helpers.LogLevel.Info, Simulator.Client);
if (_SeedRequest != null)
_SeedRequest.Cancel();
if (_EventQueueCap != null)
_EventQueueCap.Stop(immediate);
}
/// <summary>
/// Request the URI of a named capability
/// </summary>
/// <param name="capability">Name of the capability to request</param>
/// <returns>The URI of the requested capability, or String.Empty if
/// the capability does not exist</returns>
public Uri CapabilityURI(string capability)
{
Uri cap;
if (_Caps.TryGetValue(capability, out cap))
return cap;
else
return null;
}
private void MakeSeedRequest()
{
if (Simulator == null || !Simulator.Client.Network.Connected)
return;
// Create a request list
OSDArray req = new OSDArray();
// This list can be updated by using the following command to obtain a current list of capabilities the official linden viewer supports:
// wget -q -O - https://bitbucket.org/lindenlab/viewer-development/raw/default/indra/newview/llviewerregion.cpp | grep 'capabilityNames.append' | sed 's/^[ \t]*//;s/capabilityNames.append("/req.Add("/'
req.Add("AgentState");
req.Add("AttachmentResources");
req.Add("AvatarPickerSearch");
req.Add("CharacterProperties");
req.Add("ChatSessionRequest");
req.Add("CopyInventoryFromNotecard");
req.Add("CreateInventoryCategory");
req.Add("DispatchRegionInfo");
req.Add("EnvironmentSettings");
req.Add("EstateChangeInfo");
req.Add("EventQueueGet");
req.Add("FetchInventory2");
req.Add("FetchInventoryDescendents2");
req.Add("FetchLib2");
req.Add("FetchLibDescendents2");
req.Add("FetchInventory2");
req.Add("FetchInventoryDescendents2");
req.Add("GetDisplayNames");
req.Add("GetTexture");
req.Add("GetMesh");
req.Add("GetObjectCost");
req.Add("GetObjectPhysicsData");
req.Add("GetTexture");
req.Add("GroupMemberData");
req.Add("GroupProposalBallot");
req.Add("HomeLocation");
req.Add("LandResources");
req.Add("MapLayer");
req.Add("MapLayerGod");
req.Add("MeshUploadFlag");
req.Add("NavMeshGenerationStatus");
req.Add("NewFileAgentInventory");
req.Add("NewFileAgentInventoryVariablePrice");
req.Add("ObjectMedia");
req.Add("ObjectMediaNavigate");
req.Add("ObjectNavMeshProperties");
req.Add("ParcelPropertiesUpdate");
req.Add("ParcelMediaURLFilterList");
req.Add("ParcelNavigateMedia");
req.Add("ParcelVoiceInfoRequest");
req.Add("ProductInfoRequest");
req.Add("ProvisionVoiceAccountRequest");
req.Add("RemoteParcelRequest");
req.Add("RenderMaterials");
req.Add("RequestTextureDownload");
req.Add("ResourceCostSelected");
req.Add("RetrieveNavMeshSrc");
req.Add("SearchStatRequest");
req.Add("SearchStatTracking");
req.Add("SendPostcard");
req.Add("SendUserReport");
req.Add("SendUserReportWithScreenshot");
req.Add("ServerReleaseNotes");
req.Add("SimConsole");
req.Add("SimulatorFeatures");
req.Add("SetDisplayName");
req.Add("SimConsoleAsync");
req.Add("SimulatorFeatures");
req.Add("StartGroupProposal");
req.Add("TerrainNavMeshProperties");
req.Add("TextureStats");
req.Add("UntrustedSimulatorMessage");
req.Add("UpdateAgentInformation");
req.Add("UpdateAgentLanguage");
req.Add("UpdateAvatarAppearance");
req.Add("UpdateGestureAgentInventory");
req.Add("UpdateGestureTaskInventory");
req.Add("UpdateNotecardAgentInventory");
req.Add("UpdateNotecardTaskInventory");
req.Add("UpdateScriptAgent");
req.Add("UpdateGestureTaskInventory");
req.Add("UpdateNotecardTaskInventory");
req.Add("UpdateScriptTask");
req.Add("UploadBakedTexture");
req.Add("UploadObjectAsset");
req.Add("ViewerMetrics");
req.Add("ViewerStartAuction");
req.Add("ViewerStats");
_SeedRequest = new CapsClient(new Uri(_SeedCapsURI));
_SeedRequest.OnComplete += new CapsClient.CompleteCallback(SeedRequestCompleteHandler);
_SeedRequest.BeginGetResponse(req, OSDFormat.Xml, Simulator.Client.Settings.CAPS_TIMEOUT);
}
private void SeedRequestCompleteHandler(CapsClient client, OSD result, Exception error)
{
if (result != null && result.Type == OSDType.Map)
{
OSDMap respTable = (OSDMap)result;
foreach (string cap in respTable.Keys)
{
_Caps[cap] = respTable[cap].AsUri();
}
if (_Caps.ContainsKey("EventQueueGet"))
{
Logger.DebugLog("Starting event queue for " + Simulator.ToString(), Simulator.Client);
_EventQueueCap = new EventQueueClient(_Caps["EventQueueGet"]);
_EventQueueCap.OnConnected += EventQueueConnectedHandler;
_EventQueueCap.OnEvent += EventQueueEventHandler;
_EventQueueCap.Start();
}
}
else if (
error != null &&
error is WebException &&
((WebException)error).Response != null &&
((HttpWebResponse)((WebException)error).Response).StatusCode == HttpStatusCode.NotFound)
{
// 404 error
Logger.Log("Seed capability returned a 404, capability system is aborting", Helpers.LogLevel.Error);
}
else
{
// The initial CAPS connection failed, try again
MakeSeedRequest();
}
}
private void EventQueueConnectedHandler()
{
Simulator.Client.Network.RaiseConnectedEvent(Simulator);
}
/// <summary>
/// Process any incoming events, check to see if we have a message created for the event,
/// </summary>
/// <param name="eventName"></param>
/// <param name="body"></param>
private void EventQueueEventHandler(string eventName, OSDMap body)
{
IMessage message = Messages.MessageUtils.DecodeEvent(eventName, body);
if (message != null)
{
Simulator.Client.Network.CapsEvents.BeginRaiseEvent(eventName, message, Simulator);
#region Stats Tracking
if (Simulator.Client.Settings.TRACK_UTILIZATION)
{
Simulator.Client.Stats.Update(eventName, OpenMetaverse.Stats.Type.Message, 0, body.ToString().Length);
}
#endregion
}
else
{
Logger.Log("No Message handler exists for event " + eventName + ". Unable to decode. Will try Generic Handler next", Helpers.LogLevel.Warning);
Logger.Log("Please report this information to http://jira.openmetaverse.org/: \n" + body, Helpers.LogLevel.Debug);
// try generic decoder next which takes a caps event and tries to match it to an existing packet
if (body.Type == OSDType.Map)
{
OSDMap map = (OSDMap)body;
Packet packet = Packet.BuildPacket(eventName, map);
if (packet != null)
{
NetworkManager.IncomingPacket incomingPacket;
incomingPacket.Simulator = Simulator;
incomingPacket.Packet = packet;
Logger.DebugLog("Serializing " + packet.Type.ToString() + " capability with generic handler", Simulator.Client);
Simulator.Client.Network.PacketInbox.Enqueue(incomingPacket);
}
else
{
Logger.Log("No Packet or Message handler exists for " + eventName, Helpers.LogLevel.Warning);
}
}
}
}
}
}
| |
/************************************************************************************
Filename : OVRLipSyncContext.cs
Content : Interface to Oculus Lip-Sync engine
Created : August 6th, 2015
Copyright : Copyright Facebook Technologies, LLC and its affiliates.
All rights reserved.
Licensed under the Oculus Audio SDK License Version 3.3 (the "License");
you may not use the Oculus Audio SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/audio-3.3/
Unless required by applicable law or agreed to in writing, the Oculus Audio SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
//-------------------------------------------------------------------------------------
// ***** OVRLipSyncContext
//
/// <summary>
/// OVRLipSyncContext interfaces into the Oculus phoneme recognizer.
/// This component should be added into the scene once for each Audio Source.
///
/// </summary>
public class OVRLipSyncContext : OVRLipSyncContextBase
{
// * * * * * * * * * * * * *
// Public members
[Tooltip("Allow capturing of keyboard input to control operation.")]
public bool enableKeyboardInput = false;
[Tooltip("Register a mouse/touch callback to control loopback and gain (requires script restart).")]
public bool enableTouchInput = false;
[Tooltip("Play input audio back through audio output.")]
public bool audioLoopback = false;
[Tooltip("Key to toggle audio loopback.")]
public KeyCode loopbackKey = KeyCode.L;
[Tooltip("Show viseme scores in an OVRLipSyncDebugConsole display.")]
public bool showVisemes = false;
[Tooltip("Key to toggle viseme score display.")]
public KeyCode debugVisemesKey = KeyCode.D;
[Tooltip("Skip data from the Audio Source. Use if you intend to pass audio data in manually.")]
public bool skipAudioSource = false;
[Tooltip("Adjust the linear audio gain multiplier before processing lipsync")]
public float gain = 1.0f;
private bool hasDebugConsole = false;
public KeyCode debugLaughterKey = KeyCode.H;
public bool showLaughter = false;
public float laughterScore = 0.0f;
// * * * * * * * * * * * * *
// Private members
/// <summary>
/// Start this instance.
/// Note: make sure to always have a Start function for classes that have editor scripts.
/// </summary>
void Start()
{
// Add a listener to the OVRTouchpad for touch events
if (enableTouchInput)
{
OVRTouchpad.AddListener(LocalTouchEventCallback);
}
// Find console
OVRLipSyncDebugConsole[] consoles = FindObjectsOfType<OVRLipSyncDebugConsole>();
if (consoles.Length > 0)
{
hasDebugConsole = consoles[0];
}
}
/// <summary>
/// Handle keyboard input
/// </summary>
void HandleKeyboard()
{
// Turn loopback on/off
if (Input.GetKeyDown(loopbackKey))
{
ToggleAudioLoopback();
}
else if (Input.GetKeyDown(debugVisemesKey))
{
showVisemes = !showVisemes;
if (showVisemes)
{
if (hasDebugConsole)
{
Debug.Log("DEBUG SHOW VISEMES: ENABLED");
}
else
{
Debug.LogWarning("Warning: No OVRLipSyncDebugConsole in the scene!");
showVisemes = false;
}
}
else
{
if (hasDebugConsole)
{
OVRLipSyncDebugConsole.Clear();
}
Debug.Log("DEBUG SHOW VISEMES: DISABLED");
}
}
else if (Input.GetKeyDown(debugLaughterKey))
{
showLaughter = !showLaughter;
if (showLaughter)
{
if (hasDebugConsole)
{
Debug.Log("DEBUG SHOW LAUGHTER: ENABLED");
}
else
{
Debug.LogWarning("Warning: No OVRLipSyncDebugConsole in the scene!");
showLaughter = false;
}
}
else
{
if (hasDebugConsole)
{
OVRLipSyncDebugConsole.Clear();
}
Debug.Log("DEBUG SHOW LAUGHTER: DISABLED");
}
}
else if (Input.GetKeyDown(KeyCode.LeftArrow))
{
gain -= 1.0f;
if (gain < 1.0f) gain = 1.0f;
string g = "LINEAR GAIN: ";
g += gain;
if (hasDebugConsole)
{
OVRLipSyncDebugConsole.Clear();
OVRLipSyncDebugConsole.Log(g);
OVRLipSyncDebugConsole.ClearTimeout(1.5f);
}
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
gain += 1.0f;
if (gain > 15.0f)
gain = 15.0f;
string g = "LINEAR GAIN: ";
g += gain;
if (hasDebugConsole)
{
OVRLipSyncDebugConsole.Clear();
OVRLipSyncDebugConsole.Log(g);
OVRLipSyncDebugConsole.ClearTimeout(1.5f);
}
}
}
/// <summary>
/// Run processes that need to be updated in our game thread
/// </summary>
void Update()
{
if (enableKeyboardInput)
{
HandleKeyboard();
}
laughterScore = this.Frame.laughterScore;
DebugShowVisemesAndLaughter();
}
/// <summary>
/// Preprocess F32 PCM audio buffer
/// </summary>
/// <param name="data">Data.</param>
/// <param name="channels">Channels.</param>
public void PreprocessAudioSamples(float[] data, int channels)
{
// Increase the gain of the input
for (int i = 0; i < data.Length; ++i)
{
data[i] = data[i] * gain;
}
}
/// <summary>
/// Postprocess F32 PCM audio buffer
/// </summary>
/// <param name="data">Data.</param>
/// <param name="channels">Channels.</param>
public void PostprocessAudioSamples(float[] data, int channels)
{
// Turn off output (so that we don't get feedback from mics too close to speakers)
if (!audioLoopback)
{
for (int i = 0; i < data.Length; ++i)
data[i] = data[i] * 0.0f;
}
}
/// <summary>
/// Pass F32 PCM audio buffer to the lip sync module
/// </summary>
/// <param name="data">Data.</param>
/// <param name="channels">Channels.</param>
public void ProcessAudioSamplesRaw(float[] data, int channels)
{
// Send data into Phoneme context for processing (if context is not 0)
lock (this)
{
if (Context == 0 || OVRLipSync.IsInitialized() != OVRLipSync.Result.Success)
{
return;
}
var frame = this.Frame;
OVRLipSync.ProcessFrame(Context, data, frame, channels == 2);
}
}
/// <summary>
/// Pass S16 PCM audio buffer to the lip sync module
/// </summary>
/// <param name="data">Data.</param>
/// <param name="channels">Channels.</param>
public void ProcessAudioSamplesRaw(short[] data, int channels)
{
// Send data into Phoneme context for processing (if context is not 0)
lock (this)
{
if (Context == 0 || OVRLipSync.IsInitialized() != OVRLipSync.Result.Success)
{
return;
}
var frame = this.Frame;
OVRLipSync.ProcessFrame(Context, data, frame, channels == 2);
}
}
/// <summary>
/// Process F32 audio sample and pass it to the lip sync module for computation
/// </summary>
/// <param name="data">Data.</param>
/// <param name="channels">Channels.</param>
public void ProcessAudioSamples(float[] data, int channels)
{
// Do not process if we are not initialized, or if there is no
// audio source attached to game object
if ((OVRLipSync.IsInitialized() != OVRLipSync.Result.Success) || audioSource == null)
{
return;
}
PreprocessAudioSamples(data, channels);
ProcessAudioSamplesRaw(data, channels);
PostprocessAudioSamples(data, channels);
}
/// <summary>
/// Raises the audio filter read event.
/// </summary>
/// <param name="data">Data.</param>
/// <param name="channels">Channels.</param>
void OnAudioFilterRead(float[] data, int channels)
{
if (!skipAudioSource)
{
ProcessAudioSamples(data, channels);
}
}
/// <summary>
/// Print the visemes and laughter score to game window
/// </summary>
void DebugShowVisemesAndLaughter()
{
if (hasDebugConsole)
{
string seq = "";
if (showLaughter)
{
seq += "Laughter:";
int count = (int)(50.0f * this.Frame.laughterScore);
for (int c = 0; c < count; c++)
seq += "*";
seq += "\n";
}
if (showVisemes)
{
for (int i = 0; i < this.Frame.Visemes.Length; i++)
{
seq += ((OVRLipSync.Viseme)i).ToString();
seq += ":";
int count = (int)(50.0f * this.Frame.Visemes[i]);
for (int c = 0; c < count; c++)
seq += "*";
seq += "\n";
}
}
OVRLipSyncDebugConsole.Clear();
if (seq != "")
{
OVRLipSyncDebugConsole.Log(seq);
}
}
}
void ToggleAudioLoopback()
{
audioLoopback = !audioLoopback;
if (hasDebugConsole)
{
OVRLipSyncDebugConsole.Clear();
OVRLipSyncDebugConsole.ClearTimeout(1.5f);
if (audioLoopback)
OVRLipSyncDebugConsole.Log("LOOPBACK MODE: ENABLED");
else
OVRLipSyncDebugConsole.Log("LOOPBACK MODE: DISABLED");
}
}
// LocalTouchEventCallback
void LocalTouchEventCallback(OVRTouchpad.TouchEvent touchEvent)
{
string g = "LINEAR GAIN: ";
switch (touchEvent)
{
case (OVRTouchpad.TouchEvent.SingleTap):
ToggleAudioLoopback();
break;
case (OVRTouchpad.TouchEvent.Up):
gain += 1.0f;
if (gain > 15.0f)
gain = 15.0f;
g += gain;
if (hasDebugConsole)
{
OVRLipSyncDebugConsole.Clear();
OVRLipSyncDebugConsole.Log(g);
OVRLipSyncDebugConsole.ClearTimeout(1.5f);
}
break;
case (OVRTouchpad.TouchEvent.Down):
gain -= 1.0f;
if (gain < 1.0f) gain = 1.0f;
g += gain;
if (hasDebugConsole)
{
OVRLipSyncDebugConsole.Clear();
OVRLipSyncDebugConsole.Log(g);
OVRLipSyncDebugConsole.ClearTimeout(1.5f);
}
break;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using EarLab.ReaderWriters;
using EarLab.ColorBars;
namespace EarLab.Viewers.Panels
{
/// <summary>
/// This control inherits from System.Windows.Forms.Panel and can be used to visualize 2-dimensional data from a file.
/// </summary>
public class PanelBarWaveform : System.Windows.Forms.Panel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private bool normalOrientation = true;
double minValue = double.MinValue;
double maxValue = double.MaxValue;
private Color drawColor = Color.Red;
private System.Drawing.Bitmap viewerBitmap;
private double[] dataArray;
/// <summary>
/// Creates a new MultiChannel2DViewerPanel.
/// </summary>
public PanelBarWaveform()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// We set up double buffering so that there isn't too much flicker (yeah, this is brilliant)
this.SetStyle(ControlStyles.UserPaint|ControlStyles.AllPaintingInWmPaint|ControlStyles.DoubleBuffer, true);
this.UpdateStyles();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
#region Overriden Events Handlers
/// <summary>
/// This event handler paints the viewer panel if the status is not Uninitialized.
/// </summary>
/// <param name="pe">Graphics object for this control.</param>
protected override void OnPaint(PaintEventArgs pe)
{
// we use this overload of DrawImage because of an edge effect seen when scaling the bitmap to fit the viewer.
if (this.dataArray != null)
pe.Graphics.DrawImageUnscaled(this.viewerBitmap, 0, 0);
// Calling base class OnPaint
base.OnPaint(pe);
}
protected override void OnResize(EventArgs e)
{
// if we have resized this panel, we need to recreate bitmap (for sharpness)
if (this.dataArray != null && this.ClientSize.Height > 0 && this.ClientSize.Width > 0)
{
this.CreateBitmap();
this.Invalidate();
}
// Calling base class OnResize
base.OnResize (e);
}
#endregion
#region Methods
private void Initialize()
{
double[] tempArray = (double[])this.dataArray.Clone();
Array.Sort(tempArray, 0, tempArray.Length);
this.minValue = 0;
this.maxValue = tempArray[tempArray.Length-1];
//for (int i=0; i<this.dataArray.Length; i++)
// this.dataArray[i] -= minValue;
}
private void CreateBitmap()
{
// we create the correct sized bitmap and draw to it, instead of stretching a data-sized bitmap to fit. This makes it sharp.
if (this.normalOrientation)
this.viewerBitmap = new Bitmap(this.ClientSize.Width, this.ClientSize.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
else
this.viewerBitmap = new Bitmap(this.ClientSize.Height, this.ClientSize.Width, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
double scale;
int offset;
double stretch = this.viewerBitmap.Width / ((double)this.dataArray.Length-1);
if (this.minValue == this.maxValue)
{
scale = 1;
offset = this.viewerBitmap.Height / 1;
}
else
{
scale = this.viewerBitmap.Height / Math.Abs(maxValue-minValue);
offset = 0;
}
System.Drawing.Graphics bitmapGraphics = Graphics.FromImage(this.viewerBitmap);
bitmapGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
bitmapGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
System.Drawing.Pen drawPen = new System.Drawing.Pen(new SolidBrush(this.drawColor), 2);
// we draw some nice background to make this thing look cool (white with some grid)
System.Drawing.Brush backBrush = System.Drawing.SystemBrushes.Control;
bitmapGraphics.FillRectangle(backBrush, -1, -1, this.viewerBitmap.Width+1, this.viewerBitmap.Height+1);
// draw the actual line graph (yeah, like this is at all accurate...)
for (int i=0;i<this.dataArray.Length;i++)
bitmapGraphics.DrawLine(drawPen, (float)(i*stretch), 0,(float)(i*stretch), (float)(this.dataArray[i]*scale+offset));
if (this.normalOrientation)
this.viewerBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
else
this.viewerBitmap.RotateFlip(RotateFlipType.Rotate270FlipX);
bitmapGraphics.Dispose();
drawPen.Dispose();
}
public void Close()
{
if (this.ClientRectangle.Width != 0 && this.ClientRectangle.Height !=0)
{
this.dataArray = null;
this.viewerBitmap = null;
}
this.Invalidate();
}
#endregion
#region Properties
public double[] DataSource
{
set
{
if (value != null)
{
this.dataArray = value;
this.Initialize();
this.CreateBitmap();
this.Invalidate();
}
else
this.Close();
}
}
public bool NormalOrientation
{
get { return this.normalOrientation; }
set { this.normalOrientation = value; }
}
public double Min
{
get { return this.minValue; }
}
public double Max
{
get { return this.maxValue; }
}
public Color DrawColor { get { return this.drawColor; } set { this.drawColor = value; } }
#endregion
}
}
| |
namespace GitTools
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
public static class ProcessHelper
{
static volatile object lockObject = new object();
// http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f6069441-4ab1-4299-ad6a-b8bb9ed36be3
public static Process Start(ProcessStartInfo startInfo)
{
Process process;
lock (lockObject)
{
using (new ChangeErrorMode(ErrorModes.FailCriticalErrors | ErrorModes.NoGpFaultErrorBox))
{
try
{
process = Process.Start(startInfo);
}
catch (Win32Exception exception)
{
switch ((NativeErrorCode)exception.NativeErrorCode)
{
case NativeErrorCode.Success:
// Success is not a failure.
break;
case NativeErrorCode.FileNotFound:
throw new FileNotFoundException(string.Format("The executable file '{0}' could not be found.",
startInfo.FileName),
startInfo.FileName,
exception);
case NativeErrorCode.PathNotFound:
throw new DirectoryNotFoundException(string.Format("The path to the executable file '{0}' could not be found.",
startInfo.FileName),
exception);
}
throw;
}
try
{
if (process != null)
{
process.PriorityClass = ProcessPriorityClass.Idle;
}
}
catch
{
// NOTE: It seems like in some situations, setting the priority class will throw a Win32Exception
// with the error code set to "Success", which I think we can safely interpret as a success and
// not an exception.
//
// See: https://travis-ci.org/GitTools/GitVersion/jobs/171288284#L2026
// And: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx
//
// There's also the case where the process might be killed before we try to adjust its priority
// class, in which case it will throw an InvalidOperationException. What we ideally should do
// is start the process in a "suspended" state, adjust the priority class, then resume it, but
// that's not possible in pure .NET.
//
// See: https://travis-ci.org/GitTools/GitVersion/jobs/166709203#L2278
// And: http://www.codeproject.com/Articles/230005/Launch-a-process-suspended
//
// -- @asbjornu
}
}
}
return process;
}
// http://csharptest.net/532/using-processstart-to-capture-console-output/
public static int Run(Action<string> output, Action<string> errorOutput, TextReader input, string exe, string args, string workingDirectory, params KeyValuePair<string, string>[] environmentalVariables)
{
if (String.IsNullOrEmpty(exe))
throw new ArgumentNullException("exe");
if (output == null)
throw new ArgumentNullException("output");
workingDirectory = workingDirectory ?? Environment.CurrentDirectory;
var psi = new ProcessStartInfo
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
ErrorDialog = false,
WorkingDirectory = workingDirectory,
FileName = exe,
Arguments = args
};
foreach (var environmentalVariable in environmentalVariables)
{
if (psi.EnvironmentVariables.ContainsKey(environmentalVariable.Key))
{
psi.EnvironmentVariables[environmentalVariable.Key] = environmentalVariable.Value;
}
else
{
psi.EnvironmentVariables.Add(environmentalVariable.Key, environmentalVariable.Value);
}
if (psi.EnvironmentVariables.ContainsKey(environmentalVariable.Key) && environmentalVariable.Value == null)
psi.EnvironmentVariables.Remove(environmentalVariable.Key);
}
using (var process = Start(psi))
using (var mreOut = new ManualResetEvent(false))
using (var mreErr = new ManualResetEvent(false))
{
process.EnableRaisingEvents = true;
process.OutputDataReceived += (o, e) =>
{
// ReSharper disable once AccessToDisposedClosure
if (e.Data == null)
mreOut.Set();
else
output(e.Data);
};
process.BeginOutputReadLine();
process.ErrorDataReceived += (o, e) =>
{
// ReSharper disable once AccessToDisposedClosure
if (e.Data == null)
mreErr.Set();
else
errorOutput(e.Data);
};
process.BeginErrorReadLine();
string line;
while (input != null && null != (line = input.ReadLine()))
process.StandardInput.WriteLine(line);
process.StandardInput.Close();
process.WaitForExit();
mreOut.WaitOne();
mreErr.WaitOne();
return process.ExitCode;
}
}
/// <summary>
/// System error codes.
/// See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx
/// </summary>
private enum NativeErrorCode
{
Success = 0x0,
FileNotFound = 0x2,
PathNotFound = 0x3
}
[Flags]
public enum ErrorModes
{
Default = 0x0,
FailCriticalErrors = 0x1,
NoGpFaultErrorBox = 0x2,
NoAlignmentFaultExcept = 0x4,
NoOpenFileErrorBox = 0x8000
}
public struct ChangeErrorMode : IDisposable
{
readonly int oldMode;
public ChangeErrorMode(ErrorModes mode)
{
try
{
oldMode = SetErrorMode((int)mode);
}
catch (EntryPointNotFoundException)
{
oldMode = (int)mode;
}
}
void IDisposable.Dispose()
{
try
{
SetErrorMode(oldMode);
}
catch (EntryPointNotFoundException)
{
// NOTE: Mono doesn't support DllImport("kernel32.dll") and its SetErrorMode method, obviously. @asbjornu
}
}
[DllImport("kernel32.dll")]
static extern int SetErrorMode(int newMode);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kemel.Orm.Data;
using Kemel.Orm.Providers;
using Kemel.Orm.Entity;
using Kemel.Orm.Schema;
namespace Kemel.Orm.QueryDef
{
public class Executer
{
public Query Parent { get; set; }
public OrmTransaction Transaction { get; set; }
public Executer(Query parent)
{
this.Parent = parent;
}
public Executer(Query parent, OrmTransaction transaction)
{
this.Parent = parent;
this.Transaction = transaction;
}
private OrmCommand CreateCommand()
{
return this.Transaction == null ?
this.Parent.Provider.GetConnection().CreateCommand() :
this.Transaction.Connection.CreateCommand(this.Transaction);
}
public List<TEtt> List<TEtt>()
where TEtt: EntityBase, new()
{
OrmCommand command = this.CreateCommand();
this.Parent.WriteQuery(command);
return command.ExecuteList<TEtt>();
}
public List<TEtt> List<TEtt>(bool useExtendProperties)
where TEtt : EntityBase, new()
{
OrmCommand command = this.CreateCommand();
this.Parent.WriteQuery(command);
return command.ExecuteList<TEtt>(useExtendProperties);
}
public System.Data.DataTable DataTable()
{
OrmCommand command = this.CreateCommand();
this.Parent.WriteQuery(command);
return command.ExecuteDataTable();
}
public int NonQuery()
{
OrmCommand command = this.CreateCommand();
this.Parent.WriteQuery(command);
return command.ExecuteNonQuery();
}
public int NonQuery<TEtt>(List<TEtt> lstEntities)//, bool blockPK)
where TEtt: EntityBase
{
bool finalizeTransaction = false;
if (this.Transaction == null)
{
this.Transaction = this.Parent.Provider.GetConnection().CreateTransaction();
finalizeTransaction = true;
}
OrmConnection connection = this.Transaction.Connection;
OrmCommand command = this.CreateCommand();
this.Parent.WriteQuery(command);
bool ignoreIdentity = this.Parent.Type == QueryType.Insert;
int ret = 0;
if (finalizeTransaction)
this.Transaction.Begin();
try
{
ret = command.ExecuteNonQuery();
for (int i = 1; i < lstEntities.Count; i++)
{
//this.SetNewParameters<TEtt>(command, lstEntities[i]);//, blockPK);
SetParameters<TEtt>(command, this.Parent, lstEntities[i], ignoreIdentity);
ret += command.ExecuteNonQuery();
}
if(finalizeTransaction)
this.Transaction.Commit();
}
catch (Exception ex)
{
if (finalizeTransaction)
this.Transaction.Rollback();
throw new OrmException(ex.Message, ex);
}
finally
{
if (finalizeTransaction)
connection.Close();
}
return ret;
}
//private void SetNewParameters<TEtt>(OrmCommand command, TEtt ettEntity)//, bool blockPK)
//{
// TableSchema schema = this.Parent.IntoTable.TableSchema;
// string prefixParam = Provider.Instance.QueryBuilder.DataBasePrefixParameter;
// foreach (ColumnSchema column in schema.Columns)
// {
// if (column.IgnoreColumn)
// continue;
// if (column.IsIdentity)
// continue;
// Constraint columnConstraint = this.Parent.Constraints.FindByColumn(column);
// //(command.Parameters[string.Concat(prefixParam, column.Name)] as System.Data.IDbDataParameter).Value = column.GetValue(ettEntity);
// (command.Parameters[columnConstraint.Column.ParameterName] as System.Data.IDbDataParameter).Value = column.GetValue(ettEntity);
// }
//}
public object Scalar()
{
OrmCommand command = this.CreateCommand();
this.Parent.WriteQuery(command);
return command.ExecuteScalar();
}
public T Scalar<T>()
{
OrmCommand command = this.CreateCommand();
this.Parent.WriteQuery(command);
return command.ExecuteScalar<T>();
}
public static void Save<TEtt>(List<TEtt> lstEntity, OrmTransaction ormTransaction)
where TEtt : EntityBase, new()
{
Query qryInsert = null;
Query qrySelectIdentity = null;
Query qryUpdate = null;
Query qryDelete = null;
OrmCommand cmdInsert = null;
OrmCommand cmdSelectIdentity = null;
OrmCommand cmdUpdate = null;
OrmCommand cmdDelete = null;
bool createTransaction = false;
Provider provider = Provider.GetProvider<TEtt>();
if (ormTransaction == null)
{
createTransaction = true;
ormTransaction = provider.GetConnection().CreateTransaction();
ormTransaction.Begin();
}
qrySelectIdentity = provider.EntityCrudBuilder.GetSelectIdentity<TEtt>();
cmdSelectIdentity = ormTransaction.Connection.CreateCommand(ormTransaction);
qrySelectIdentity.WriteQuery(cmdSelectIdentity);
TableSchema schema = qrySelectIdentity.Tables[0].TableSchema;
try
{
foreach (TEtt ett in lstEntity)
{
switch (ett.EntityState)
{
#region case EntityItemState.Added
case EntityItemState.Added:
if (cmdInsert == null)
{
qryInsert = provider.EntityCrudBuilder.GetInsert<TEtt>(ett);
cmdInsert = ormTransaction.Connection.CreateCommand(ormTransaction);
qryInsert.WriteQuery(cmdInsert);
}
else
{
SetParameters<TEtt>(cmdInsert, qryInsert, ett, true);
}
cmdInsert.ExecuteNonQuery();
SetIdentityValues<TEtt>(ett, cmdSelectIdentity.ExecuteList<TEtt>().First(), schema);
break;
#endregion
#region case EntityItemState.Deleted
case EntityItemState.Deleted:
if (cmdDelete == null)
{
qryDelete = provider.EntityCrudBuilder.GetDeleteById<TEtt>(ett);
cmdDelete = ormTransaction.Connection.CreateCommand(ormTransaction);
qryDelete.WriteQuery(cmdDelete);
}
else
{
SetParameters<TEtt>(cmdDelete, qryDelete, ett, false);
}
cmdDelete.ExecuteNonQuery();
break;
#endregion
#region case EntityItemState.Modified
case EntityItemState.Modified:
if (cmdUpdate == null)
{
qryUpdate = provider.EntityCrudBuilder.GetUpdate<TEtt>(ett);
cmdUpdate = ormTransaction.Connection.CreateCommand(ormTransaction);
qryUpdate.WriteQuery(cmdUpdate);
}
else
{
SetParameters<TEtt>(cmdUpdate, qryUpdate, ett, false);
}
cmdUpdate.ExecuteNonQuery();
break;
#endregion
}
}
if (createTransaction)
ormTransaction.Commit();
}
catch (Exception ex)
{
if (createTransaction)
ormTransaction.Rollback();
throw ex;
}
}
public static void SetIdentityValues<TEtt>(TEtt ett, TEtt pIdentityValues, TableSchema schema)
where TEtt : EntityBase
{
foreach (ColumnSchema column in schema.IdentityColumns)
{
column.SetValue(ett,
column.GetValue(pIdentityValues));
}
}
public static void SetParameters<TEtt>(OrmCommand command, Query query, TEtt ett, bool ignoreIdentity)
where TEtt : EntityBase
{
Provider provider = Provider.GetProvider<TEtt>();
string prefixParam = provider.QueryBuilder.DataBasePrefixParameter;
foreach (Constraint constraint in query.Constraints)
{
ColumnQuery columnQuery = constraint.Column;
if (columnQuery != null && columnQuery.ColumnSchema != null)
{
if (columnQuery.ColumnSchema.IgnoreColumn || (ignoreIdentity && columnQuery.ColumnSchema.IsIdentity))
continue;
object value = columnQuery.ColumnSchema.GetValue(ett);
if (value == null)
value = DBNull.Value;
(command.Parameters[prefixParam + columnQuery.ParameterName] as System.Data.IDbDataParameter).Value
= value;
}
}
foreach (SetValue setValue in query.SetValues)
{
ColumnSchema colSchema = setValue.ColumnSchema;
if (colSchema != null)
{
if (colSchema.IgnoreColumn || colSchema.IsIdentity)
continue;
object value = colSchema.GetValue(ett);
if (value == null)
value = DBNull.Value;
(command.Parameters[prefixParam + setValue.ParameterName] as System.Data.IDbDataParameter).Value
= value;
}
}
}
public OrmCommand GetCommand()
{
OrmCommand command = this.CreateCommand();
this.Parent.WriteQuery(command);
return command;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public abstract class SendReceive : MemberDatas
{
private readonly ITestOutputHelper _log;
public SendReceive(ITestOutputHelper output)
{
_log = output;
}
public abstract Task<Socket> AcceptAsync(Socket s);
public abstract Task ConnectAsync(Socket s, EndPoint endPoint);
public abstract Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer);
public abstract Task<SocketReceiveFromResult> ReceiveFromAsync(
Socket s, ArraySegment<byte> buffer, EndPoint endPoint);
public abstract Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList);
public abstract Task<int> SendAsync(Socket s, ArraySegment<byte> buffer);
public abstract Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList);
public abstract Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endpoint);
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public async Task SendToRecvFrom_Datagram_UDP(IPAddress loopbackAddress)
{
IPAddress leftAddress = loopbackAddress, rightAddress = loopbackAddress;
// TODO #5185: Harden against packet loss
const int DatagramSize = 256;
const int DatagramsToSend = 256;
const int AckTimeout = 1000;
const int TestTimeout = 30000;
var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
left.BindToAnonymousPort(leftAddress);
var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
right.BindToAnonymousPort(rightAddress);
var leftEndpoint = (IPEndPoint)left.LocalEndPoint;
var rightEndpoint = (IPEndPoint)right.LocalEndPoint;
var receiverAck = new SemaphoreSlim(0);
var senderAck = new SemaphoreSlim(0);
var receivedChecksums = new uint?[DatagramsToSend];
Task leftThread = Task.Run(async () =>
{
using (left)
{
EndPoint remote = leftEndpoint.Create(leftEndpoint.Serialize());
var recvBuffer = new byte[DatagramSize];
for (int i = 0; i < DatagramsToSend; i++)
{
SocketReceiveFromResult result = await ReceiveFromAsync(
left, new ArraySegment<byte>(recvBuffer), remote);
Assert.Equal(DatagramSize, result.ReceivedBytes);
Assert.Equal(rightEndpoint, result.RemoteEndPoint);
int datagramId = recvBuffer[0];
Assert.Null(receivedChecksums[datagramId]);
receivedChecksums[datagramId] = Fletcher32.Checksum(recvBuffer, 0, result.ReceivedBytes);
receiverAck.Release();
Assert.True(await senderAck.WaitAsync(TestTimeout));
}
}
});
var sentChecksums = new uint[DatagramsToSend];
using (right)
{
var random = new Random();
var sendBuffer = new byte[DatagramSize];
for (int i = 0; i < DatagramsToSend; i++)
{
random.NextBytes(sendBuffer);
sendBuffer[0] = (byte)i;
int sent = await SendToAsync(right, new ArraySegment<byte>(sendBuffer), leftEndpoint);
Assert.True(await receiverAck.WaitAsync(AckTimeout));
senderAck.Release();
Assert.Equal(DatagramSize, sent);
sentChecksums[i] = Fletcher32.Checksum(sendBuffer, 0, sent);
}
}
await leftThread;
for (int i = 0; i < DatagramsToSend; i++)
{
Assert.NotNull(receivedChecksums[i]);
Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(LoopbacksAndBuffers))]
public async Task SendRecv_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers)
{
const int BytesToSend = 123456, ListenBacklog = 1, LingerTime = 1;
int bytesReceived = 0, bytesSent = 0;
Fletcher32 receivedChecksum = new Fletcher32(), sentChecksum = new Fletcher32();
using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
server.BindToAnonymousPort(listenAt);
server.Listen(ListenBacklog);
Task serverProcessingTask = Task.Run(async () =>
{
using (Socket remote = await AcceptAsync(server))
{
if (!useMultipleBuffers)
{
var recvBuffer = new byte[256];
for (;;)
{
int received = await ReceiveAsync(remote, new ArraySegment<byte>(recvBuffer));
if (received == 0)
{
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
}
else
{
var recvBuffers = new List<ArraySegment<byte>> {
new ArraySegment<byte>(new byte[123]),
new ArraySegment<byte>(new byte[256], 2, 100),
new ArraySegment<byte>(new byte[1], 0, 0),
new ArraySegment<byte>(new byte[64], 9, 33)};
for (;;)
{
int received = await ReceiveAsync(remote, recvBuffers);
if (received == 0)
{
break;
}
bytesReceived += received;
for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++)
{
ArraySegment<byte> buffer = recvBuffers[i];
int toAdd = Math.Min(buffer.Count, remaining);
receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd);
remaining -= toAdd;
}
}
}
}
});
EndPoint clientEndpoint = server.LocalEndPoint;
using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
await ConnectAsync(client, clientEndpoint);
var random = new Random();
if (!useMultipleBuffers)
{
var sendBuffer = new byte[512];
for (int sent = 0, remaining = BytesToSend; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer);
sent = await SendAsync(client, new ArraySegment<byte>(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining)));
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
}
else
{
var sendBuffers = new List<ArraySegment<byte>> {
new ArraySegment<byte>(new byte[23]),
new ArraySegment<byte>(new byte[256], 2, 100),
new ArraySegment<byte>(new byte[1], 0, 0),
new ArraySegment<byte>(new byte[64], 9, 9)};
for (int sent = 0, toSend = BytesToSend; toSend > 0; toSend -= sent)
{
for (int i = 0; i < sendBuffers.Count; i++)
{
random.NextBytes(sendBuffers[i].Array);
}
sent = await SendAsync(client, sendBuffers);
bytesSent += sent;
for (int i = 0, remaining = sent; i < sendBuffers.Count && remaining > 0; i++)
{
ArraySegment<byte> buffer = sendBuffers[i];
int toAdd = Math.Min(buffer.Count, remaining);
sentChecksum.Add(buffer.Array, buffer.Offset, toAdd);
remaining -= toAdd;
}
}
}
client.LingerState = new LingerOption(true, LingerTime);
client.Shutdown(SocketShutdown.Both);
await serverProcessingTask;
}
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(LoopbacksAndBuffers))]
public void SendRecvPollSync_TcpListener_Socket(IPAddress listenAt, bool pollBeforeOperation)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
const int TestTimeout = 30000;
var listener = new TcpListener(listenAt, 0);
listener.Start(ListenBacklog);
try
{
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
Task serverTask = Task.Run(async () =>
{
using (Socket remote = await listener.AcceptSocketAsync())
{
var recvBuffer = new byte[256];
while (true)
{
if (pollBeforeOperation)
{
Assert.True(remote.Poll(-1, SelectMode.SelectRead), "Read poll before completion should have succeeded");
}
int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None);
if (received == 0)
{
Assert.True(remote.Poll(0, SelectMode.SelectRead), "Read poll after completion should have succeeded");
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
}
});
int bytesSent = 0;
var sentChecksum = new Fletcher32();
Task clientTask = Task.Run(async () =>
{
var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;
using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);
if (pollBeforeOperation)
{
Assert.False(client.Poll(TestTimeout, SelectMode.SelectRead), "Expected writer's read poll to fail after timeout");
}
var random = new Random();
var sendBuffer = new byte[512];
for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer);
if (pollBeforeOperation)
{
Assert.True(client.Poll(-1, SelectMode.SelectWrite), "Write poll should have succeeded");
}
sent = client.Send(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None);
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
}
});
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), "Wait timed out");
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
finally
{
listener.Stop();
}
}
[ActiveIssue(13778, TestPlatforms.OSX)]
[Fact]
public async Task SendRecv_0ByteReceive_Success()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener);
await Task.WhenAll(
acceptTask,
ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
for (int i = 0; i < 3; i++)
{
// Have the client do a 0-byte receive. No data is available, so this should pend.
Task<int> receive = ReceiveAsync(client, new ArraySegment<byte>(Array.Empty<byte>()));
Assert.False(receive.IsCompleted);
Assert.Equal(0, client.Available);
// Have the server send 1 byte to the client.
Assert.Equal(1, server.Send(new byte[1], 0, 1, SocketFlags.None));
// The client should now wake up, getting 0 bytes with 1 byte available.
Assert.Equal(0, await receive);
Assert.Equal(1, client.Available); // Due to #13778, this sometimes fails on macOS
// Receive that byte
Assert.Equal(1, await ReceiveAsync(client, new ArraySegment<byte>(new byte[1])));
Assert.Equal(0, client.Available);
}
}
}
}
}
public sealed class SendReceiveUdpClient : MemberDatas
{
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public void SendToRecvFromAsync_Datagram_UDP_UdpClient(IPAddress loopbackAddress)
{
IPAddress leftAddress = loopbackAddress, rightAddress = loopbackAddress;
// TODO #5185: harden against packet loss
const int DatagramSize = 256;
const int DatagramsToSend = 256;
const int AckTimeout = 1000;
const int TestTimeout = 30000;
using (var left = new UdpClient(new IPEndPoint(leftAddress, 0)))
using (var right = new UdpClient(new IPEndPoint(rightAddress, 0)))
{
var leftEndpoint = (IPEndPoint)left.Client.LocalEndPoint;
var rightEndpoint = (IPEndPoint)right.Client.LocalEndPoint;
var receiverAck = new ManualResetEventSlim();
var senderAck = new ManualResetEventSlim();
var receivedChecksums = new uint?[DatagramsToSend];
int receivedDatagrams = 0;
Task receiverTask = Task.Run(async () =>
{
for (; receivedDatagrams < DatagramsToSend; receivedDatagrams++)
{
UdpReceiveResult result = await left.ReceiveAsync();
receiverAck.Set();
Assert.True(senderAck.Wait(AckTimeout));
senderAck.Reset();
Assert.Equal(DatagramSize, result.Buffer.Length);
Assert.Equal(rightEndpoint, result.RemoteEndPoint);
int datagramId = (int)result.Buffer[0];
Assert.Null(receivedChecksums[datagramId]);
receivedChecksums[datagramId] = Fletcher32.Checksum(result.Buffer, 0, result.Buffer.Length);
}
});
var sentChecksums = new uint[DatagramsToSend];
int sentDatagrams = 0;
Task senderTask = Task.Run(async () =>
{
var random = new Random();
var sendBuffer = new byte[DatagramSize];
for (; sentDatagrams < DatagramsToSend; sentDatagrams++)
{
random.NextBytes(sendBuffer);
sendBuffer[0] = (byte)sentDatagrams;
int sent = await right.SendAsync(sendBuffer, DatagramSize, leftEndpoint);
Assert.True(receiverAck.Wait(AckTimeout));
receiverAck.Reset();
senderAck.Set();
Assert.Equal(DatagramSize, sent);
sentChecksums[sentDatagrams] = Fletcher32.Checksum(sendBuffer, 0, sent);
}
});
Assert.True(Task.WaitAll(new[] { receiverTask, senderTask }, TestTimeout));
for (int i = 0; i < DatagramsToSend; i++)
{
Assert.NotNull(receivedChecksums[i]);
Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]);
}
}
}
}
public sealed class SendReceiveListener : MemberDatas
{
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public void SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
const int LingerTime = 10;
const int TestTimeout = 30000;
var listener = new TcpListener(listenAt, 0);
listener.Start(ListenBacklog);
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
Task serverTask = Task.Run(async () =>
{
using (TcpClient remote = await listener.AcceptTcpClientAsync())
using (NetworkStream stream = remote.GetStream())
{
var recvBuffer = new byte[256];
for (;;)
{
int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length);
if (received == 0)
{
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
}
});
int bytesSent = 0;
var sentChecksum = new Fletcher32();
Task clientTask = Task.Run(async () =>
{
var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;
using (var client = new TcpClient(clientEndpoint.AddressFamily))
{
await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);
using (NetworkStream stream = client.GetStream())
{
var random = new Random();
var sendBuffer = new byte[512];
for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer);
sent = Math.Min(sendBuffer.Length, remaining);
await stream.WriteAsync(sendBuffer, 0, sent);
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
client.LingerState = new LingerOption(true, LingerTime);
}
}
});
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout));
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
}
public sealed class SendReceiveSync : SendReceive
{
public SendReceiveSync(ITestOutputHelper output) : base(output) { }
public override Task<Socket> AcceptAsync(Socket s) =>
Task.Run(() => s.Accept());
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
Task.Run(() => s.Connect(endPoint));
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Run(() => s.Receive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None));
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Run(() => s.Receive(bufferList, SocketFlags.None));
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
Task.Run(() =>
{
int received = s.ReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint);
return new SocketReceiveFromResult
{
ReceivedBytes = received,
RemoteEndPoint = endPoint
};
});
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Run(() => s.Send(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None));
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Run(() => s.Send(bufferList, SocketFlags.None));
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
Task.Run(() => s.SendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint));
}
public sealed class SendReceiveApm : SendReceive
{
public SendReceiveApm(ITestOutputHelper output) : base(output) { }
public override Task<Socket> AcceptAsync(Socket s) =>
Task.Factory.FromAsync(s.BeginAccept, s.EndAccept, null);
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
Task.Factory.FromAsync(s.BeginConnect, s.EndConnect, endPoint, null);
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Factory.FromAsync((callback, state) =>
s.BeginReceive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state),
s.EndReceive, null);
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Factory.FromAsync(s.BeginReceive, s.EndReceive, bufferList, SocketFlags.None, null);
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint)
{
var tcs = new TaskCompletionSource<SocketReceiveFromResult>();
s.BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint, iar =>
{
try
{
int receivedBytes = s.EndReceiveFrom(iar, ref endPoint);
tcs.TrySetResult(new SocketReceiveFromResult
{
ReceivedBytes = receivedBytes,
RemoteEndPoint = endPoint
});
}
catch (Exception e) { tcs.TrySetException(e); }
}, null);
return tcs.Task;
}
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Factory.FromAsync((callback, state) =>
s.BeginSend(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state),
s.EndSend, null);
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Factory.FromAsync(s.BeginSend, s.EndSend, bufferList, SocketFlags.None, null);
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
Task.Factory.FromAsync(
(callback, state) => s.BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint, callback, state),
s.EndSendTo, null);
}
public sealed class SendReceiveTask : SendReceive
{
public SendReceiveTask(ITestOutputHelper output) : base(output) { }
public override Task<Socket> AcceptAsync(Socket s) =>
s.AcceptAsync();
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
s.ConnectAsync(endPoint);
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
s.ReceiveAsync(buffer, SocketFlags.None);
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
s.ReceiveAsync(bufferList, SocketFlags.None);
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
s.ReceiveFromAsync(buffer, SocketFlags.None, endPoint);
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
s.SendAsync(buffer, SocketFlags.None);
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
s.SendAsync(bufferList, SocketFlags.None);
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
s.SendToAsync(buffer, SocketFlags.None, endPoint);
}
public sealed class SendReceiveEap : SendReceive
{
public SendReceiveEap(ITestOutputHelper output) : base(output) { }
public override Task<Socket> AcceptAsync(Socket s) =>
InvokeAsync(s, e => e.AcceptSocket, e => s.AcceptAsync(e));
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
InvokeAsync(s, e => true, e =>
{
e.RemoteEndPoint = endPoint;
return s.ConnectAsync(e);
});
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
return s.ReceiveAsync(e);
});
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.BufferList = bufferList;
return s.ReceiveAsync(e);
});
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
InvokeAsync(s, e => new SocketReceiveFromResult { ReceivedBytes = e.BytesTransferred, RemoteEndPoint = e.RemoteEndPoint }, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
e.RemoteEndPoint = endPoint;
return s.ReceiveFromAsync(e);
});
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
return s.SendAsync(e);
});
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.BufferList = bufferList;
return s.SendAsync(e);
});
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
e.RemoteEndPoint = endPoint;
return s.SendToAsync(e);
});
private static Task<TResult> InvokeAsync<TResult>(
Socket s,
Func<SocketAsyncEventArgs, TResult> getResult,
Func<SocketAsyncEventArgs, bool> invoke)
{
var tcs = new TaskCompletionSource<TResult>();
var saea = new SocketAsyncEventArgs();
EventHandler<SocketAsyncEventArgs> handler = (_, e) =>
{
if (e.SocketError == SocketError.Success) tcs.SetResult(getResult(e));
else tcs.SetException(new SocketException((int)e.SocketError));
saea.Dispose();
};
saea.Completed += handler;
if (!invoke(saea)) handler(s, saea);
return tcs.Task;
}
}
public abstract class MemberDatas
{
public static readonly object[][] Loopbacks = new[]
{
new object[] { IPAddress.Loopback },
new object[] { IPAddress.IPv6Loopback },
};
public static readonly object[][] LoopbacksAndBuffers = new object[][]
{
new object[] { IPAddress.IPv6Loopback, true },
new object[] { IPAddress.IPv6Loopback, false },
new object[] { IPAddress.Loopback, true },
new object[] { IPAddress.Loopback, false },
};
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Osp;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.CoreModules.World.Archiver;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
public class InventoryArchiveReadRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected TarArchiveReader archive;
private CachedUserInfo m_userInfo;
private string m_invPath;
/// <value>
/// The stream from which the inventory archive will be loaded.
/// </value>
private Stream m_loadStream;
protected CommunicationsManager m_commsManager;
protected IAssetService m_assetService;
public InventoryArchiveReadRequest(
CachedUserInfo userInfo, string invPath, string loadPath, CommunicationsManager commsManager, IAssetService assetService)
: this(
userInfo,
invPath,
new GZipStream(new FileStream(loadPath, FileMode.Open), CompressionMode.Decompress),
commsManager, assetService)
{
}
public InventoryArchiveReadRequest(
CachedUserInfo userInfo, string invPath, Stream loadStream, CommunicationsManager commsManager, IAssetService assetService)
{
m_userInfo = userInfo;
m_invPath = invPath;
m_loadStream = loadStream;
m_commsManager = commsManager;
m_assetService = assetService;
}
/// <summary>
/// Execute the request
/// </summary>
/// <returns>
/// A list of the inventory nodes loaded. If folders were loaded then only the root folders are
/// returned
/// </returns>
public List<InventoryNodeBase> Execute()
{
string filePath = "ERROR";
int successfulAssetRestores = 0;
int failedAssetRestores = 0;
int successfulItemRestores = 0;
List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>();
if (!m_userInfo.HasReceivedInventory)
{
// If the region server has access to the user admin service (by which users are created),
// then we'll assume that it's okay to fiddle with the user's inventory even if they are not on the
// server.
//
// FIXME: FetchInventory should probably be assumed to by async anyway, since even standalones might
// use a remote inventory service, though this is vanishingly rare at the moment.
if (null == m_commsManager.UserAdminService)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Have not yet received inventory info for user {0} {1}",
m_userInfo.UserProfile.Name, m_userInfo.UserProfile.ID);
return nodesLoaded;
}
else
{
m_userInfo.FetchInventory();
for (int i = 0 ; i < 50 ; i++)
{
if (m_userInfo.HasReceivedInventory == true)
break;
Thread.Sleep(200);
}
}
}
InventoryFolderImpl rootDestinationFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath);
if (null == rootDestinationFolder)
{
// Possibly provide an option later on to automatically create this folder if it does not exist
m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath);
return nodesLoaded;
}
archive = new TarArchiveReader(m_loadStream);
// In order to load identically named folders, we need to keep track of the folders that we have already
// created
Dictionary <string, InventoryFolderImpl> foldersCreated = new Dictionary<string, InventoryFolderImpl>();
byte[] data;
TarArchiveReader.TarEntryType entryType;
while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
{
if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
{
if (LoadAsset(filePath, data))
successfulAssetRestores++;
else
failedAssetRestores++;
}
else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH))
{
InventoryFolderImpl foundFolder
= ReplicateArchivePathToUserInventory(
filePath, TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType,
rootDestinationFolder, foldersCreated, nodesLoaded);
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType)
{
InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data);
// Don't use the item ID that's in the file
item.ID = UUID.Random();
UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_commsManager);
if (UUID.Zero != ospResolvedId)
item.CreatorIdAsUuid = ospResolvedId;
item.Owner = m_userInfo.UserProfile.ID;
// Reset folder ID to the one in which we want to load it
item.Folder = foundFolder.ID;
m_userInfo.AddItem(item);
successfulItemRestores++;
// If we're loading an item directly into the given destination folder then we need to record
// it separately from any loaded root folders
if (rootDestinationFolder == foundFolder)
nodesLoaded.Add(item);
}
}
}
archive.Close();
m_log.DebugFormat("[INVENTORY ARCHIVER]: Restored {0} assets", successfulAssetRestores);
m_log.InfoFormat("[INVENTORY ARCHIVER]: Restored {0} items", successfulItemRestores);
return nodesLoaded;
}
/// <summary>
/// Replicate the inventory paths in the archive to the user's inventory as necessary.
/// </summary>
/// <param name="fsPath"></param>
/// <param name="isDir">Is the path we're dealing with a directory?</param>
/// <param name="rootDestinationFolder">The root folder for the inventory load</param>
/// <param name="foldersCreated">
/// The folders created so far. This method will add more folders if necessary
/// </param>
/// <param name="nodesLoaded">
/// Track the inventory nodes created. This is distinct from the folders created since for a particular folder
/// chain, only the root node needs to be recorded
/// </param>
/// <returns>The last user inventory folder created or found for the archive path</returns>
public InventoryFolderImpl ReplicateArchivePathToUserInventory(
string fsPath,
bool isDir,
InventoryFolderImpl rootDestinationFolder,
Dictionary <string, InventoryFolderImpl> foldersCreated,
List<InventoryNodeBase> nodesLoaded)
{
fsPath = fsPath.Substring(ArchiveConstants.INVENTORY_PATH.Length);
// Remove the file portion if we aren't already dealing with a directory path
if (!isDir)
fsPath = fsPath.Remove(fsPath.LastIndexOf("/") + 1);
string originalFsPath = fsPath;
m_log.DebugFormat("[INVENTORY ARCHIVER]: Loading to folder {0}", fsPath);
InventoryFolderImpl foundFolder = null;
// XXX: Nasty way of dealing with a path that has no directory component
if (fsPath.Length > 0)
{
while (null == foundFolder && fsPath.Length > 0)
{
if (foldersCreated.ContainsKey(fsPath))
{
m_log.DebugFormat("[INVENTORY ARCHIVER]: Found previously created fs path {0}", fsPath);
foundFolder = foldersCreated[fsPath];
}
else
{
// Don't include the last slash
int penultimateSlashIndex = fsPath.LastIndexOf("/", fsPath.Length - 2);
if (penultimateSlashIndex >= 0)
{
fsPath = fsPath.Remove(penultimateSlashIndex + 1);
}
else
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found no previously created fs path for {0}",
originalFsPath);
fsPath = string.Empty;
foundFolder = rootDestinationFolder;
}
}
}
}
else
{
foundFolder = rootDestinationFolder;
}
string fsPathSectionToCreate = originalFsPath.Substring(fsPath.Length);
string[] rawDirsToCreate
= fsPathSectionToCreate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
int i = 0;
while (i < rawDirsToCreate.Length)
{
m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0}", rawDirsToCreate[i]);
int identicalNameIdentifierIndex
= rawDirsToCreate[i].LastIndexOf(
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR);
string folderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex);
UUID newFolderId = UUID.Random();
m_userInfo.CreateFolder(
folderName, newFolderId, (ushort)AssetType.Folder, foundFolder.ID);
m_log.DebugFormat("[INVENTORY ARCHIVER]: Retrieving newly created folder {0}", folderName);
foundFolder = foundFolder.GetChildFolder(newFolderId);
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Retrieved newly created folder {0} with ID {1}",
foundFolder.Name, foundFolder.ID);
// Record that we have now created this folder
fsPath += rawDirsToCreate[i] + "/";
m_log.DebugFormat("[INVENTORY ARCHIVER]: Recording creation of fs path {0}", fsPath);
foldersCreated[fsPath] = foundFolder;
if (0 == i)
nodesLoaded.Add(foundFolder);
i++;
}
return foundFolder;
/*
string[] rawFolders = filePath.Split(new char[] { '/' });
// Find the folders that do exist along the path given
int i = 0;
bool noFolder = false;
InventoryFolderImpl foundFolder = rootDestinationFolder;
while (!noFolder && i < rawFolders.Length)
{
InventoryFolderImpl folder = foundFolder.FindFolderByPath(rawFolders[i]);
if (null != folder)
{
m_log.DebugFormat("[INVENTORY ARCHIVER]: Found folder {0}", folder.Name);
foundFolder = folder;
i++;
}
else
{
noFolder = true;
}
}
// Create any folders that did not previously exist
while (i < rawFolders.Length)
{
m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0}", rawFolders[i]);
UUID newFolderId = UUID.Random();
m_userInfo.CreateFolder(
rawFolders[i++], newFolderId, (ushort)AssetType.Folder, foundFolder.ID);
foundFolder = foundFolder.GetChildFolder(newFolderId);
}
*/
}
/// <summary>
/// Load an asset
/// </summary>
/// <param name="assetFilename"></param>
/// <param name="data"></param>
/// <returns>true if asset was successfully loaded, false otherwise</returns>
private bool LoadAsset(string assetPath, byte[] data)
{
//IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>();
// Right now we're nastily obtaining the UUID from the filename
string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
if (i == -1)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
return false;
}
string extension = filename.Substring(i);
string uuid = filename.Remove(filename.Length - extension.Length);
if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
{
sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
//m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
AssetBase asset = new AssetBase(new UUID(uuid), "RandomName");
asset.Type = assetType;
asset.Data = data;
m_assetService.Store(asset);
return true;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
assetPath, extension);
return false;
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Sql.Auditing.Model;
using Microsoft.Azure.Commands.Sql.Common;
using Microsoft.Azure.Commands.Sql.Services;
using System;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Sql.Auditing.Cmdlet
{
/// <summary>
/// Sets the auditing policy properties for a specific database.
/// </summary>
[Cmdlet(VerbsCommon.Set, "AzureRmSqlDatabaseAuditingPolicy", SupportsShouldProcess = true), OutputType(typeof(AuditingPolicyModel))]
[Obsolete("Note that Table auditing is deprecated and this command will be removed in a future release. Please use the 'Set-AzureRmSqlDatabaseAuditing' command to configure Blob auditing.", false)]
public class SetAzureSqlDatabaseAuditingPolicy : SqlDatabaseAuditingCmdletBase
{
/// <summary>
/// Gets or sets the name of the database server to use.
/// </summary>
[Parameter(Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The audit type.")]
public override AuditType AuditType { get; set; }
/// <summary>
/// Defines whether the cmdlets will output the model object at the end of its execution
/// </summary>
[Parameter(Mandatory = false)]
public SwitchParameter PassThru { get; set; }
/// <summary>
/// Defines the set of audit action groups that would be used by the auditing settings
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The set of the audit action groups")]
public AuditActionGroups[] AuditActionGroup { get; set; }
/// <summary>
/// Defines the set of audit actions that would be used by the auditing settings
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The set of the audit actions")]
public string[] AuditAction { get; set; }
/// <summary>
/// Gets or sets the names of the event types to use.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Event types to audit")]
[ValidateSet(SecurityConstants.PlainSQL_Success, SecurityConstants.PlainSQL_Failure, SecurityConstants.ParameterizedSQL_Success, SecurityConstants.ParameterizedSQL_Failure, SecurityConstants.StoredProcedure_Success, SecurityConstants.StoredProcedure_Failure, SecurityConstants.Login_Success, SecurityConstants.Login_Failure, SecurityConstants.TransactionManagement_Success, SecurityConstants.TransactionManagement_Failure, SecurityConstants.All, SecurityConstants.None, IgnoreCase = false)]
public string[] EventType { get; set; }
/// <summary>
/// Gets or sets the name of the storage account to use.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the storage account")]
[ValidateNotNullOrEmpty]
public string StorageAccountName { get; set; }
/// <summary>
/// Gets or sets the type of the storage key.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The type of the storage key")]
[ValidateSet(SecurityConstants.Primary, SecurityConstants.Secondary, IgnoreCase = false)]
[ValidateNotNullOrEmpty]
public string StorageKeyType { get; set; }
/// <summary>
/// Gets or sets the number of retention days for the audit logs table.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The number of retention days for the audit logs table")]
[ValidateNotNullOrEmpty]
public uint? RetentionInDays { get; internal set; }
/// <summary>
/// Gets or sets the name of the audit logs table.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the audit logs table")]
[ValidateNotNullOrEmpty]
public string TableIdentifier { get; internal set; }
/// <summary>
/// Returns true if the model object that was constructed by this cmdlet should be written out
/// </summary>
/// <returns>True if the model object should be written out, False otherwise</returns>
protected override bool WriteResult() { return PassThru; }
/// <summary>
/// Updates the given model element with the cmdlet specific operation
/// </summary>
/// <param name="baseModel">A model object</param>
protected override AuditingPolicyModel ApplyUserInputToModel(AuditingPolicyModel baseModel)
{
base.ApplyUserInputToModel(baseModel);
if (AuditType == AuditType.Table)
{
ApplyUserInputToTableAuditingModel(baseModel as DatabaseAuditingPolicyModel);
}
else
{
ApplyUserInputToBlobAuditingModel(baseModel as DatabaseBlobAuditingPolicyModel);
}
return baseModel;
}
private void ApplyUserInputToBlobAuditingModel(DatabaseBlobAuditingPolicyModel model)
{
model.AuditState = AuditStateType.Enabled;
if (RetentionInDays != null)
{
model.RetentionInDays = RetentionInDays;
}
if (StorageAccountName != null)
{
model.StorageAccountName = StorageAccountName;
}
if (MyInvocation.BoundParameters.ContainsKey(SecurityConstants.StorageKeyType))
{
// the user enter a key type - we use it (and override the previously defined key type)
model.StorageKeyType = (StorageKeyType == SecurityConstants.Primary)
? StorageKeyKind.Primary
: StorageKeyKind.Secondary;
}
if (AuditActionGroup != null && AuditActionGroup.Length != 0)
{
model.AuditActionGroup = AuditActionGroup;
}
if (AuditAction != null && AuditAction.Length != 0)
{
model.AuditAction = AuditAction;
}
}
private void ApplyUserInputToTableAuditingModel(DatabaseAuditingPolicyModel model)
{
var orgAuditStateType = model.AuditState;
model.AuditState = AuditStateType.Enabled;
model.UseServerDefault = UseServerDefaultOptions.Disabled;
if (StorageAccountName != null)
{
model.StorageAccountName = StorageAccountName;
ModelAdapter.ClearStorageDetailsCache();
}
if (MyInvocation.BoundParameters.ContainsKey(SecurityConstants.StorageKeyType))
{
// the user enter a key type - we use it (and override the previously defined key type)
model.StorageKeyType = (StorageKeyType == SecurityConstants.Primary)
? StorageKeyKind.Primary
: StorageKeyKind.Secondary;
}
EventType = Util.ProcessAuditEvents(EventType);
if (EventType != null) // the user provided Table auditing event types
{
model.EventType = EventType.Select(s => SecurityConstants.AuditEventsToAuditEventType[s]).ToArray();
}
if (RetentionInDays != null)
{
model.RetentionInDays = RetentionInDays;
}
if (TableIdentifier == null)
{
if ((orgAuditStateType == AuditStateType.New) && (model.RetentionInDays > 0))
{
// If retention days is greater than 0 and no audit table identifier is supplied , we throw exception giving the user hint on the recommended TableIdentifier we got from the CSM
throw new Exception(string.Format(Properties.Resources.InvalidRetentionTypeSet, model.TableIdentifier));
}
}
else
{
model.TableIdentifier = TableIdentifier;
}
}
protected override AuditingPolicyModel PersistChanges(AuditingPolicyModel model)
{
base.PersistChanges(model);
ModelAdapter.IgnoreStorage = true;
Action swapAuditType = () => { AuditType = AuditType == AuditType.Blob ? AuditType.Table : AuditType.Blob; };
swapAuditType();
var otherAuditingTypePolicyModel = GetEntity();
if (otherAuditingTypePolicyModel != null)
{
otherAuditingTypePolicyModel.AuditState = AuditStateType.Disabled;
base.PersistChanges(otherAuditingTypePolicyModel);
}
swapAuditType();
return model;
}
}
}
| |
// <copyright file="ArrayStatistics.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2015 Math.NET
//
// 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.
// </copyright>
using System;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.Statistics
{
/// <summary>
/// Statistics operating on arrays assumed to be unsorted.
/// WARNING: Methods with the Inplace-suffix may modify the data array by reordering its entries.
/// </summary>
/// <seealso cref="SortedArrayStatistics"/>
/// <seealso cref="StreamingStatistics"/>
/// <seealso cref="Statistics"/>
public static class ArrayStatistics
{
// TODO: Benchmark various options to find out the best approach (-> branch prediction)
// TODO: consider leveraging MKL
/// <summary>
/// Returns the smallest value from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double Minimum(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
var min = double.PositiveInfinity;
for (int i = 0; i < data.Length; i++)
{
if (data[i] < min || double.IsNaN(data[i]))
{
min = data[i];
}
}
return min;
}
/// <summary>
/// Returns the smallest value from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static float Minimum(float[] data)
{
if (data.Length == 0)
{
return float.NaN;
}
var min = float.PositiveInfinity;
for (int i = 0; i < data.Length; i++)
{
if (data[i] < min || float.IsNaN(data[i]))
{
min = data[i];
}
}
return min;
}
/// <summary>
/// Returns the largest value from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double Maximum(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
var max = double.NegativeInfinity;
for (int i = 0; i < data.Length; i++)
{
if (data[i] > max || double.IsNaN(data[i]))
{
max = data[i];
}
}
return max;
}
/// <summary>
/// Returns the smallest value from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static float Maximum(float[] data)
{
if (data.Length == 0)
{
return float.NaN;
}
var max = float.NegativeInfinity;
for (int i = 0; i < data.Length; i++)
{
if (data[i] > max || float.IsNaN(data[i]))
{
max = data[i];
}
}
return max;
}
/// <summary>
/// Estimates the arithmetic sample mean from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double Mean(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double mean = 0;
ulong m = 0;
for (int i = 0; i < data.Length; i++)
{
mean += (data[i] - mean)/++m;
}
return mean;
}
/// <summary>
/// Estimates the arithmetic sample mean from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double Mean(float[] data)
{
if (data.Length == 0)
{
return float.NaN;
}
double mean = 0;
ulong m = 0;
for (int i = 0; i < data.Length; i++)
{
mean += (data[i] - mean) / ++m;
}
return mean;
}
/// <summary>
/// Evaluates the geometric mean of the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double GeometricMean(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double sum = 0;
for (int i = 0; i < data.Length; i++)
{
sum += Math.Log(data[i]);
}
return Math.Exp(sum/data.Length);
}
/// <summary>
/// Evaluates the harmonic mean of the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double HarmonicMean(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double sum = 0;
for (int i = 0; i < data.Length; i++)
{
sum += 1.0/data[i];
}
return data.Length/sum;
}
/// <summary>
/// Estimates the unbiased population variance from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static double Variance(double[] samples)
{
if (samples.Length <= 1)
{
return double.NaN;
}
double variance = 0;
double t = samples[0];
for (int i = 1; i < samples.Length; i++)
{
t += samples[i];
double diff = ((i + 1)*samples[i]) - t;
variance += (diff*diff)/((i + 1.0)*i);
}
return variance/(samples.Length - 1);
}
/// <summary>
/// Estimates the unbiased population variance from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static double Variance(float[] samples)
{
if (samples.Length <= 1)
{
return float.NaN;
}
double variance = 0;
double t = samples[0];
for (int i = 1; i < samples.Length; i++)
{
t += samples[i];
double diff = ((i + 1) * samples[i]) - t;
variance += (diff * diff) / ((i + 1.0) * i);
}
return variance / (samples.Length - 1);
}
/// <summary>
/// Evaluates the population variance from the full population provided as unsorted array.
/// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
/// Returns NaN if data is empty or if any entry is NaN.
/// </summary>
/// <param name="population">Sample array, no sorting is assumed.</param>
public static double PopulationVariance(double[] population)
{
if (population.Length == 0)
{
return double.NaN;
}
double variance = 0;
double t = population[0];
for (int i = 1; i < population.Length; i++)
{
t += population[i];
double diff = ((i + 1)*population[i]) - t;
variance += (diff*diff)/((i + 1.0)*i);
}
return variance/population.Length;
}
/// <summary>
/// Evaluates the population variance from the full population provided as unsorted array.
/// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
/// Returns NaN if data is empty or if any entry is NaN.
/// </summary>
/// <param name="population">Sample array, no sorting is assumed.</param>
public static double PopulationVariance(float[] population)
{
if (population.Length == 0)
{
return float.NaN;
}
double variance = 0;
double t = population[0];
for (int i = 1; i < population.Length; i++)
{
t += population[i];
double diff = ((i + 1) * population[i]) - t;
variance += (diff * diff) / ((i + 1.0) * i);
}
return variance / population.Length;
}
/// <summary>
/// Estimates the unbiased population standard deviation from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static double StandardDeviation(double[] samples)
{
return Math.Sqrt(Variance(samples));
}
/// <summary>
/// Estimates the unbiased population standard deviation from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static double StandardDeviation(float[] samples)
{
return Math.Sqrt(Variance(samples));
}
/// <summary>
/// Evaluates the population standard deviation from the full population provided as unsorted array.
/// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
/// Returns NaN if data is empty or if any entry is NaN.
/// </summary>
/// <param name="population">Sample array, no sorting is assumed.</param>
public static double PopulationStandardDeviation(double[] population)
{
return Math.Sqrt(PopulationVariance(population));
}
/// <summary>
/// Evaluates the population standard deviation from the full population provided as unsorted array.
/// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
/// Returns NaN if data is empty or if any entry is NaN.
/// </summary>
/// <param name="population">Sample array, no sorting is assumed.</param>
public static double PopulationStandardDeviation(float[] population)
{
return Math.Sqrt(PopulationVariance(population));
}
/// <summary>
/// Estimates the arithmetic sample mean and the unbiased population variance from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN for mean if data is empty or any entry is NaN and NaN for variance if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static Tuple<double, double> MeanVariance(double[] samples)
{
return new Tuple<double, double>(Mean(samples), Variance(samples));
}
/// <summary>
/// Estimates the arithmetic sample mean and the unbiased population variance from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN for mean if data is empty or any entry is NaN and NaN for variance if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static Tuple<double, double> MeanVariance(float[] samples)
{
return new Tuple<double, double>(Mean(samples), Variance(samples));
}
/// <summary>
/// Estimates the arithmetic sample mean and the unbiased population standard deviation from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN for mean if data is empty or any entry is NaN and NaN for standard deviation if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static Tuple<double, double> MeanStandardDeviation(double[] samples)
{
return new Tuple<double, double>(Mean(samples), StandardDeviation(samples));
}
/// <summary>
/// Estimates the arithmetic sample mean and the unbiased population standard deviation from the provided samples as unsorted array.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN for mean if data is empty or any entry is NaN and NaN for standard deviation if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples">Sample array, no sorting is assumed.</param>
public static Tuple<double, double> MeanStandardDeviation(float[] samples)
{
return new Tuple<double, double>(Mean(samples), StandardDeviation(samples));
}
/// <summary>
/// Estimates the unbiased population covariance from the provided two sample arrays.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples1">First sample array.</param>
/// <param name="samples2">Second sample array.</param>
public static double Covariance(double[] samples1, double[] samples2)
{
if (samples1.Length != samples2.Length)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (samples1.Length <= 1)
{
return double.NaN;
}
double mean1 = Mean(samples1);
double mean2 = Mean(samples2);
double covariance = 0.0;
for (int i = 0; i < samples1.Length; i++)
{
covariance += (samples1[i] - mean1)*(samples2[i] - mean2);
}
return covariance/(samples1.Length - 1);
}
/// <summary>
/// Estimates the unbiased population covariance from the provided two sample arrays.
/// On a dataset of size N will use an N-1 normalizer (Bessel's correction).
/// Returns NaN if data has less than two entries or if any entry is NaN.
/// </summary>
/// <param name="samples1">First sample array.</param>
/// <param name="samples2">Second sample array.</param>
public static double Covariance(float[] samples1, float[] samples2)
{
if (samples1.Length != samples2.Length)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (samples1.Length <= 1)
{
return double.NaN;
}
double mean1 = Mean(samples1);
double mean2 = Mean(samples2);
double covariance = 0.0;
for (int i = 0; i < samples1.Length; i++)
{
covariance += (samples1[i] - mean1) * (samples2[i] - mean2);
}
return covariance / (samples1.Length - 1);
}
/// <summary>
/// Evaluates the population covariance from the full population provided as two arrays.
/// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
/// Returns NaN if data is empty or if any entry is NaN.
/// </summary>
/// <param name="population1">First population array.</param>
/// <param name="population2">Second population array.</param>
public static double PopulationCovariance(double[] population1, double[] population2)
{
if (population1.Length != population2.Length)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (population1.Length == 0)
{
return double.NaN;
}
double mean1 = Mean(population1);
double mean2 = Mean(population2);
double covariance = 0.0;
for (int i = 0; i < population1.Length; i++)
{
covariance += (population1[i] - mean1)*(population2[i] - mean2);
}
return covariance/population1.Length;
}
/// <summary>
/// Evaluates the population covariance from the full population provided as two arrays.
/// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset.
/// Returns NaN if data is empty or if any entry is NaN.
/// </summary>
/// <param name="population1">First population array.</param>
/// <param name="population2">Second population array.</param>
public static double PopulationCovariance(float[] population1, float[] population2)
{
if (population1.Length != population2.Length)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (population1.Length == 0)
{
return double.NaN;
}
double mean1 = Mean(population1);
double mean2 = Mean(population2);
double covariance = 0.0;
for (int i = 0; i < population1.Length; i++)
{
covariance += (population1[i] - mean1) * (population2[i] - mean2);
}
return covariance / population1.Length;
}
/// <summary>
/// Estimates the root mean square (RMS) also known as quadratic mean from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double RootMeanSquare(double[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double mean = 0;
ulong m = 0;
for (int i = 0; i < data.Length; i++)
{
mean += (data[i]*data[i] - mean)/++m;
}
return Math.Sqrt(mean);
}
/// <summary>
/// Estimates the root mean square (RMS) also known as quadratic mean from the unsorted data array.
/// Returns NaN if data is empty or any entry is NaN.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed.</param>
public static double RootMeanSquare(float[] data)
{
if (data.Length == 0)
{
return double.NaN;
}
double mean = 0;
ulong m = 0;
for (int i = 0; i < data.Length; i++)
{
mean += (data[i] * data[i] - mean) / ++m;
}
return Math.Sqrt(mean);
}
/// <summary>
/// Returns the order statistic (order 1..N) from the unsorted data array.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="order">One-based order of the statistic, must be between 1 and N (inclusive).</param>
public static double OrderStatisticInplace(double[] data, int order)
{
if (order < 1 || order > data.Length)
{
return double.NaN;
}
if (order == 1)
{
return Minimum(data);
}
if (order == data.Length)
{
return Maximum(data);
}
return SelectInplace(data, order - 1);
}
/// <summary>
/// Estimates the median value from the unsorted data array.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double MedianInplace(double[] data)
{
var k = data.Length/2;
return data.Length.IsOdd()
? SelectInplace(data, k)
: (SelectInplace(data, k - 1) + SelectInplace(data, k))/2.0;
}
/// <summary>
/// Estimates the p-Percentile value from the unsorted data array.
/// If a non-integer Percentile is needed, use Quantile instead.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="p">Percentile selector, between 0 and 100 (inclusive).</param>
public static double PercentileInplace(double[] data, int p)
{
return QuantileInplace(data, p/100d);
}
/// <summary>
/// Estimates the first quartile value from the unsorted data array.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double LowerQuartileInplace(double[] data)
{
return QuantileInplace(data, 0.25d);
}
/// <summary>
/// Estimates the third quartile value from the unsorted data array.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double UpperQuartileInplace(double[] data)
{
return QuantileInplace(data, 0.75d);
}
/// <summary>
/// Estimates the inter-quartile range from the unsorted data array.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double InterquartileRangeInplace(double[] data)
{
return QuantileInplace(data, 0.75d) - QuantileInplace(data, 0.25d);
}
/// <summary>
/// Estimates {min, lower-quantile, median, upper-quantile, max} from the unsorted data array.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
public static double[] FiveNumberSummaryInplace(double[] data)
{
if (data.Length == 0)
{
return new[] { double.NaN, double.NaN, double.NaN, double.NaN, double.NaN };
}
// TODO: Benchmark: is this still faster than sorting the array then using SortedArrayStatistics instead?
return new[] { Minimum(data), QuantileInplace(data, 0.25), QuantileInplace(data, 0.50), QuantileInplace(data, 0.75), Maximum(data) };
}
/// <summary>
/// Estimates the tau-th quantile from the unsorted data array.
/// The tau-th quantile is the data value where the cumulative distribution
/// function crosses tau.
/// Approximately median-unbiased regardless of the sample distribution (R8).
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="tau">Quantile selector, between 0.0 and 1.0 (inclusive).</param>
/// <remarks>
/// R-8, SciPy-(1/3,1/3):
/// Linear interpolation of the approximate medians for order statistics.
/// When tau < (2/3) / (N + 1/3), use x1. When tau >= (N - 1/3) / (N + 1/3), use xN.
/// </remarks>
public static double QuantileInplace(double[] data, double tau)
{
if (tau < 0d || tau > 1d || data.Length == 0)
{
return double.NaN;
}
double h = (data.Length + 1d/3d)*tau + 1d/3d;
var hf = (int)h;
if (hf <= 0 || tau == 0d)
{
return Minimum(data);
}
if (hf >= data.Length || tau == 1d)
{
return Maximum(data);
}
var a = SelectInplace(data, hf - 1);
var b = SelectInplace(data, hf);
return a + (h - hf)*(b - a);
}
/// <summary>
/// Estimates the tau-th quantile from the unsorted data array.
/// The tau-th quantile is the data value where the cumulative distribution
/// function crosses tau. The quantile defintion can be specified
/// by 4 parameters a, b, c and d, consistent with Mathematica.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="tau">Quantile selector, between 0.0 and 1.0 (inclusive)</param>
/// <param name="a">a-parameter</param>
/// <param name="b">b-parameter</param>
/// <param name="c">c-parameter</param>
/// <param name="d">d-parameter</param>
public static double QuantileCustomInplace(double[] data, double tau, double a, double b, double c, double d)
{
if (tau < 0d || tau > 1d || data.Length == 0)
{
return double.NaN;
}
var x = a + (data.Length + b)*tau - 1;
#if PORTABLE
var ip = (int)x;
#else
var ip = Math.Truncate(x);
#endif
var fp = x - ip;
if (Math.Abs(fp) < 1e-9)
{
return SelectInplace(data, (int)ip);
}
var lower = SelectInplace(data, (int)Math.Floor(x));
var upper = SelectInplace(data, (int)Math.Ceiling(x));
return lower + (upper - lower)*(c + d*fp);
}
/// <summary>
/// Estimates the tau-th quantile from the unsorted data array.
/// The tau-th quantile is the data value where the cumulative distribution
/// function crosses tau. The quantile definition can be specified to be compatible
/// with an existing system.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
/// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param>
/// <param name="tau">Quantile selector, between 0.0 and 1.0 (inclusive)</param>
/// <param name="definition">Quantile definition, to choose what product/definition it should be consistent with</param>
public static double QuantileCustomInplace(double[] data, double tau, QuantileDefinition definition)
{
if (tau < 0d || tau > 1d || data.Length == 0)
{
return double.NaN;
}
if (tau == 0d || data.Length == 1)
{
return Minimum(data);
}
if (tau == 1d)
{
return Maximum(data);
}
switch (definition)
{
case QuantileDefinition.R1:
{
double h = data.Length*tau + 0.5d;
return SelectInplace(data, (int)Math.Ceiling(h - 0.5d) - 1);
}
case QuantileDefinition.R2:
{
double h = data.Length*tau + 0.5d;
return (SelectInplace(data, (int)Math.Ceiling(h - 0.5d) - 1) + SelectInplace(data, (int)(h + 0.5d) - 1))*0.5d;
}
case QuantileDefinition.R3:
{
double h = data.Length*tau;
return SelectInplace(data, (int)Math.Round(h) - 1);
}
case QuantileDefinition.R4:
{
double h = data.Length*tau;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R5:
{
double h = data.Length*tau + 0.5d;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R6:
{
double h = (data.Length + 1)*tau;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R7:
{
double h = (data.Length - 1)*tau + 1d;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R8:
{
double h = (data.Length + 1/3d)*tau + 1/3d;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
case QuantileDefinition.R9:
{
double h = (data.Length + 0.25d)*tau + 0.375d;
var hf = (int)h;
var lower = SelectInplace(data, hf - 1);
var upper = SelectInplace(data, hf);
return lower + (h - hf)*(upper - lower);
}
default:
throw new NotSupportedException();
}
}
static double SelectInplace(double[] workingData, int rank)
{
// Numerical Recipes: select
// http://en.wikipedia.org/wiki/Selection_algorithm
if (rank <= 0)
{
return Minimum(workingData);
}
if (rank >= workingData.Length - 1)
{
return Maximum(workingData);
}
var a = workingData;
int low = 0;
int high = a.Length - 1;
while (true)
{
if (high <= low + 1)
{
if (high == low + 1 && a[high] < a[low])
{
var tmp = a[low];
a[low] = a[high];
a[high] = tmp;
}
return a[rank];
}
int middle = (low + high) >> 1;
var tmp1 = a[middle];
a[middle] = a[low + 1];
a[low + 1] = tmp1;
if (a[low] > a[high])
{
var tmp = a[low];
a[low] = a[high];
a[high] = tmp;
}
if (a[low + 1] > a[high])
{
var tmp = a[low + 1];
a[low + 1] = a[high];
a[high] = tmp;
}
if (a[low] > a[low + 1])
{
var tmp = a[low];
a[low] = a[low + 1];
a[low + 1] = tmp;
}
int begin = low + 1;
int end = high;
double pivot = a[begin];
while (true)
{
do
{
begin++;
}
while (a[begin] < pivot);
do
{
end--;
}
while (a[end] > pivot);
if (end < begin)
{
break;
}
var tmp = a[begin];
a[begin] = a[end];
a[end] = tmp;
}
a[low + 1] = a[end];
a[end] = pivot;
if (end >= rank)
{
high = end - 1;
}
if (end <= rank)
{
low = begin;
}
}
}
/// <summary>
/// Evaluates the rank of each entry of the unsorted data array.
/// The rank definition can be specified to be compatible
/// with an existing system.
/// WARNING: Works inplace and can thus causes the data array to be reordered.
/// </summary>
public static double[] RanksInplace(double[] data, RankDefinition definition = RankDefinition.Default)
{
var ranks = new double[data.Length];
var index = new int[data.Length];
for (int i = 0; i < index.Length; i++)
{
index[i] = i;
}
if (definition == RankDefinition.First)
{
Sorting.SortAll(data, index);
for (int i = 0; i < ranks.Length; i++)
{
ranks[index[i]] = i + 1;
}
return ranks;
}
Sorting.Sort(data, index);
int previousIndex = 0;
for (int i = 1; i < data.Length; i++)
{
if (Math.Abs(data[i] - data[previousIndex]) <= 0d)
{
continue;
}
if (i == previousIndex + 1)
{
ranks[index[previousIndex]] = i;
}
else
{
RanksTies(ranks, index, previousIndex, i, definition);
}
previousIndex = i;
}
RanksTies(ranks, index, previousIndex, data.Length, definition);
return ranks;
}
static void RanksTies(double[] ranks, int[] index, int a, int b, RankDefinition definition)
{
// TODO: potential for PERF optimization
double rank;
switch (definition)
{
case RankDefinition.Average:
{
rank = (b + a - 1)/2d + 1;
break;
}
case RankDefinition.Min:
{
rank = a + 1;
break;
}
case RankDefinition.Max:
{
rank = b;
break;
}
default:
throw new NotSupportedException();
}
for (int k = a; k < b; k++)
{
ranks[index[k]] = rank;
}
}
}
}
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.ActiveRecord.Generator.Dialogs
{
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using Castle.ActiveRecord.Generator.Components.CodeGenerator;
/// <summary>
/// Summary description for GenCodeDialog.
/// </summary>
public class GenCodeDialog : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox ns;
private System.Windows.Forms.TextBox outDir;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.CheckBox overwriteCheck;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.ComboBox languageCombo;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private ICodeProviderFactory codeproviderFactory;
private System.Windows.Forms.Button browseButton;
private System.Windows.Forms.Button generateButton;
private System.Windows.Forms.Button closeButton;
private Model _model;
protected GenCodeDialog()
{
codeproviderFactory =
ServiceRegistry.Instance[ typeof(ICodeProviderFactory) ] as ICodeProviderFactory;
//
// Required for Windows Form Designer support
//
InitializeComponent();
languageCombo.ValueMember = "Label";
foreach(CodeProviderInfo info in codeproviderFactory.GetAvailableProviders())
{
languageCombo.Items.Add(info);
}
languageCombo.SelectedIndex = 0;
}
public GenCodeDialog(Model model) : this()
{
_model = model;
ns.Text = model.CurrentProject.Namespace;
outDir.Text = model.CurrentProject.LastOutDir;
overwriteCheck.Checked = model.CurrentProject.OverwriteFiles;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.languageCombo = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.overwriteCheck = new System.Windows.Forms.CheckBox();
this.browseButton = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.outDir = new System.Windows.Forms.TextBox();
this.ns = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.generateButton = new System.Windows.Forms.Button();
this.closeButton = new System.Windows.Forms.Button();
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.languageCombo);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.overwriteCheck);
this.groupBox1.Controls.Add(this.browseButton);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.outDir);
this.groupBox1.Controls.Add(this.ns);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(16, 16);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(424, 184);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Options:";
//
// languageCombo
//
this.languageCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.languageCombo.Location = new System.Drawing.Point(104, 96);
this.languageCombo.Name = "languageCombo";
this.languageCombo.Size = new System.Drawing.Size(200, 21);
this.languageCombo.TabIndex = 7;
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 96);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(80, 23);
this.label3.TabIndex = 6;
this.label3.Text = "Language:";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// overwriteCheck
//
this.overwriteCheck.Location = new System.Drawing.Point(104, 136);
this.overwriteCheck.Name = "overwriteCheck";
this.overwriteCheck.Size = new System.Drawing.Size(208, 24);
this.overwriteCheck.TabIndex = 5;
this.overwriteCheck.Text = "Overwrite existing files";
//
// browseButton
//
this.browseButton.Location = new System.Drawing.Point(368, 64);
this.browseButton.Name = "browseButton";
this.browseButton.Size = new System.Drawing.Size(32, 24);
this.browseButton.TabIndex = 4;
this.browseButton.Text = "...";
this.browseButton.Click += new System.EventHandler(this.button3_Click);
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 23);
this.label2.TabIndex = 3;
this.label2.Text = "Output dir:";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// outDir
//
this.outDir.Location = new System.Drawing.Point(104, 64);
this.outDir.Name = "outDir";
this.outDir.Size = new System.Drawing.Size(256, 21);
this.outDir.TabIndex = 2;
this.outDir.Text = "";
//
// ns
//
this.ns.Location = new System.Drawing.Point(104, 32);
this.ns.Name = "ns";
this.ns.Size = new System.Drawing.Size(296, 21);
this.ns.TabIndex = 1;
this.ns.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Namespace:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// generateButton
//
this.generateButton.Location = new System.Drawing.Point(368, 216);
this.generateButton.Name = "generateButton";
this.generateButton.TabIndex = 1;
this.generateButton.Text = "Generate";
this.generateButton.Click += new System.EventHandler(this.button1_Click);
//
// closeButton
//
this.closeButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.closeButton.Location = new System.Drawing.Point(280, 216);
this.closeButton.Name = "closeButton";
this.closeButton.TabIndex = 2;
this.closeButton.Text = "Close";
this.closeButton.Click += new System.EventHandler(this.button2_Click);
//
// GenCodeDialog
//
this.AcceptButton = this.generateButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.CancelButton = this.closeButton;
this.ClientSize = new System.Drawing.Size(456, 250);
this.Controls.Add(this.closeButton);
this.Controls.Add(this.generateButton);
this.Controls.Add(this.groupBox1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.Name = "GenCodeDialog";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Generate Code Options";
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void button3_Click(object sender, System.EventArgs e)
{
folderBrowserDialog1.SelectedPath = outDir.Text;
if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
{
outDir.Text = folderBrowserDialog1.SelectedPath;
}
}
private void button2_Click(object sender, System.EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void button1_Click(object sender, System.EventArgs e)
{
DirectoryInfo dirInfo = new DirectoryInfo(outDir.Text);
if (outDir.Text == String.Empty)
{
MessageBox.Show(this, "You must specify an output directory.", "Field is required", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (!dirInfo.Exists)
{
if (MessageBox.Show(this, "Output directory does not exists. Create it?", "Question", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
{
dirInfo.Create();
}
else
{
return;
}
}
_model.CurrentProject.CodeInfo = languageCombo.SelectedItem as CodeProviderInfo;
_model.CurrentProject.LastOutDir = outDir.Text;
_model.CurrentProject.Namespace = ns.Text;
_model.CurrentProject.OverwriteFiles = overwriteCheck.Checked;
DialogResult = DialogResult.OK;
Close();
}
}
}
| |
using System;
using System.Data;
using System.Web.UI;
using Vevo;
using Vevo.Deluxe.Domain;
using Vevo.Deluxe.Domain.Products;
using Vevo.Domain;
using Vevo.Domain.Base;
using Vevo.Domain.Products;
using Vevo.Domain.Stores;
using Vevo.Shared.DataAccess;
using Vevo.Shared.Utilities;
public partial class AdminAdvanced_Components_ProductDetailsEdit : AdminAdvancedBaseUserControl
{
#region Private
private enum Mode { Add, Edit };
private Mode _mode = Mode.Edit;
private string Action
{
get
{
string value = MainContext.QueryString["action"];
if (!String.IsNullOrEmpty( value ))
{
return value;
}
else
{
return "0";
}
}
}
private int TabId
{
get
{
string value = MainContext.QueryString["TabName"];
if (!String.IsNullOrEmpty( value ))
{
switch (value)
{
case "Attribute": return 1;
case "Image": return 2;
case "Seo": return 3;
case "Other": return 4;
default: return 0;
}
}
else
return 0;
}
}
private void ClearInputFields()
{
uxProductInfo.ClearInputFields();
uxGiftCertificate.ClearInputFields();
uxProductLink.ClearInputFields();
uxProductAttributes.ClearInputFields();
uxDepartmentInfo.ClearInputFields();
uxProductSeo.ClearInputFields();
uxGiftCertificate.SetGiftCertificateControlsVisibility( IsEditMode() );
//Recurring Edit
uxRecurring.ClearInputFields();
uxProductSubscription.ClearInputFields();
uxProductKit.ClearInputFields();
}
private void PopulateControls()
{
PopulateLanguageSection();
if (ConvertUtilities.ToInt32( CurrentID ) > 0)
{
Product product =
DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, CurrentID, uxStoreList.CurrentSelected );
uxProductAttributes.PopulateControls( product, uxStoreList.CurrentSelected );
uxProductSeo.PopulateControls( product, uxStoreList.CurrentSelected );
uxGiftCertificate.PopulateControls( product );
if (product.IsGiftCertificate)
{
uxGiftCertificate.PopulateGiftData( (GiftCertificateProduct) product );
uxGiftCertificate.SetGiftCertificateControlsVisibility( IsEditMode() );
}
uxRecurring.PopulateControls( product );
if (KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName ))
{
uxProductSubscription.PopulateControls( product );
}
uxProductAttributes.IsFixPrice(
uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring, uxProductAttributes.IsCallForPrice );
uxProductKit.PopulateControls( product );
}
}
private void CopyVisible( bool value )
{
uxCopyButton.Visible = value;
if (value)
{
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
uxCopyConfirmButton.TargetControlID = "uxCopyButton";
uxConfirmModalPopup.TargetControlID = "uxCopyButton";
}
else
{
uxCopyConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
else
{
uxCopyConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
private void DisplayControlsByVersion()
{
uxProductAttributes.SetDisplayControls();
uxGiftCertificate.SetDisplayControl( DataAccessContext.Configurations.GetBoolValue( "GiftCertificateEnabled" ) );
if (IsEditMode())
{
CopyVisible( true );
}
}
protected void uxStoreList_RefreshHandler( object sender, EventArgs e )
{
PopulateControls();
}
private void Language_RefreshHandler( object sender, EventArgs e )
{
PopulateLanguageSection();
}
private string AddNew()
{
Product product = new Product( uxLanguageControl.CurrentCulture );
product = uxGiftCertificate.Setup( uxLanguageControl.CurrentCulture );
product = SetUpProduct( product );
ProductSubscription subscriptionItem = uxProductSubscription.Setup( product );
product = DataAccessContext.ProductRepository.Save( product );
DataAccessContextDeluxe.ProductSubscriptionRepository.SaveAll( product.ProductID, subscriptionItem.ProductSubscriptions );
uxMessage.DisplayMessage( Resources.ProductMessages.AddSuccess );
return product.ProductID;
}
private void Update()
{
try
{
if (Page.IsValid)
{
if (uxProductInfo.ConvertToCategoryIDs().Length <= 0)
{
uxMessage.DisplayError( Resources.ProductMessages.AddErrorCategoryEmpty );
return;
}
if (uxProductKit.IsProductKit)
{
if (uxProductKit.GetSelectedGroupID().Length <= 0)
{
uxMessage.DisplayError( Resources.ProductMessages.AddErrorProductKitEmpty );
return;
}
}
if (!uxProductAttributes.VerifyInputListOption())
{
DisplayErrorOption();
return;
}
string price;
string retailPrice;
string wholeSalePrice;
string wholeSalePrice2;
string wholeSalePrice3;
decimal giftAmount;
if (uxProductAttributes.IsFixPrice(
uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring, uxProductAttributes.IsCallForPrice ))
{
price = uxProductAttributes.Price;
retailPrice = uxProductAttributes.RetailPrice;
wholeSalePrice = uxProductAttributes.WholeSalePrice;
wholeSalePrice2 = uxProductAttributes.WholeSalePrice2;
wholeSalePrice3 = uxProductAttributes.WholeSalePrice3;
giftAmount = ConvertUtilities.ToDecimal( uxGiftCertificate.GiftAmount );
}
else
{
price = "0";
retailPrice = "0";
wholeSalePrice = "0";
wholeSalePrice2 = "0";
wholeSalePrice3 = "0";
giftAmount = 0m;
}
string storeID = new StoreRetriever().GetCurrentStoreID();
Product product = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, CurrentID, storeID );
product = SetUpProduct( product );
product = uxProductImageList.Update( product );
ProductSubscription subscriptionItem = uxProductSubscription.Setup( product );
if (product.ProductOptionGroups.Count > 0)
{
DataAccessContext.ProductKitGroupRepository.DeleteProductKitItemByProductID( product.ProductID );
}
product = DataAccessContext.ProductRepository.Save( product );
DataAccessContextDeluxe.ProductSubscriptionRepository.SaveAll( product.ProductID, subscriptionItem.ProductSubscriptions );
uxMessage.DisplayMessage( Resources.ProductMessages.UpdateSuccess );
AdminUtilities.ClearSiteMapCache();
PopulateControls();
}
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
}
private DataTable CurrentStockOption
{
get
{
if (ViewState["CurrentStockOption"] == null)
return null;
else
return (DataTable) ViewState["CurrentStockOption"];
}
set
{
ViewState["CurrentStockOption"] = value;
}
}
private void DisplayErrorOption()
{
uxMessage.DisplayError( Resources.ProductOptionMessages.InvalidInputList );
}
private void EnforcePermission()
{
if (!MainContext.IsPostBack &&
!IsAdminModifiable())
{
if (IsEditMode())
{
uxEditButton.Visible = false;
CopyVisible( false );
uxProductAttributes.HideUploadButton();
uxDeleteButton.Visible = false;
uxProductImageList.HideUploadImageButton();
}
}
}
private void PopulateLink()
{
uxReviewLink.Visible = true;
GetReviewLink();
}
private void GetReviewLink()
{
uxReviewLink.PageName = "ProductReviewList.ascx";
uxReviewLink.PageQueryString = "ProductID=" + CurrentID;
}
private void CopyRemainingProductLocales( Product originalProduct, string newProductID )
{
string storeID = new StoreRetriever().GetCurrentStoreID();
Product newProduct = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, newProductID, storeID );
newProduct.ImageSecondary = String.Empty;
foreach (ILocale locale in originalProduct.GetLocales())
{
if (locale.CultureID != newProduct.Locales[uxLanguageControl.CurrentCulture].CultureID)
{
ProductLocale newLocale = new ProductLocale();
newLocale.CultureID = originalProduct.Locales[locale.CultureID].CultureID;
newLocale.Name = originalProduct.Locales[locale.CultureID].Name;
newLocale.ShortDescription = originalProduct.Locales[locale.CultureID].ShortDescription;
newLocale.LongDescription = originalProduct.Locales[locale.CultureID].LongDescription;
newProduct.Locales.Add( newLocale );
}
}
DataAccessContext.ProductRepository.Save( newProduct );
}
private void CopyMetaInformation( Product originalProduct, string newProductID )
{
string storeID = new StoreRetriever().GetCurrentStoreID();
Product newProduct = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, newProductID, storeID );
foreach (ProductMetaInformation meta in originalProduct.GetMetaInformations())
{
Culture culture = DataAccessContext.CultureRepository.GetOne( meta.CultureID );
newProduct.SetMetaKeyword( culture, meta.StoreID, meta.MetaKeyword );
newProduct.SetMetaDescription( culture, meta.StoreID, meta.MetaDescription );
newProduct.SetUseDefaultValueMetaKeyword( culture, meta.StoreID, meta.UseDefaultMetaKeyword );
newProduct.SetUseDefaultValueMetaDescription( culture, meta.StoreID, meta.UseDefaultMetaDescription );
}
DataAccessContext.ProductRepository.Save( newProduct );
}
private void CopyProductPrice( Product originalProduct, string newProductID )
{
string storeID = new StoreRetriever().GetCurrentStoreID();
Product newProduct = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, newProductID, storeID );
newProduct.ProductPrices = originalProduct.ProductPrices;
DataAccessContext.ProductRepository.Save( newProduct );
}
private Product SetUpProduct( Product product )
{
product = uxProductInfo.Setup( product );
product = uxDepartmentInfo.Setup( product );
product = uxProductSeo.Setup( product, uxStoreList.CurrentSelected );
product = uxRecurring.Setup( product );
product = uxProductAttributes.Setup( product, uxStoreList.CurrentSelected );
product = uxProductKit.Setup( product );
product.ShippingCost = ConvertUtilities.ToDecimal( "0" );
product.IsGiftCertificate = uxGiftCertificate.IsGiftCertificate;
if (product.IsGiftCertificate)
product = uxGiftCertificate.Update( product );
product.IsFixedPrice = uxProductAttributes.IsFixPrice(
uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring, uxProductAttributes.IsCallForPrice );
product.ImageSecondary = uxProductImageList.SecondaryImage();
product.ProductStocks.Clear();
product.ProductOptionGroups.Clear();
product.ProductShippingCosts.Clear();
uxProductAttributes.AddOptionGroup( product );
uxProductAttributes.CreateStockOption( product );
uxProductAttributes.UpdateProductShippingCost( product );
uxProductAttributes.SetProductSpecifications( product );
return product;
}
private void ProductSubscriptionCondition()
{
if (uxProductSubscription.IsProductSubscription)
{
//set disable control
uxProductKit.DisableProductKitControl();
uxProductSubscription.ShowProductSubscription();
uxProductAttributes.SetEnabledControlsForProductSubscription( false );
}
else
{
//set enable control
uxProductKit.EnableProductKitControl();
uxProductSubscription.HideProductSubscription();
uxProductAttributes.SetEnabledControlsForProductSubscription( true );
}
}
private void RecurringCondition()
{
//Add code for Recurring.
if (uxRecurring.IsRecurring)
{
uxRecurring.ShowRecurring();
}
else
{
uxRecurring.HideRecurring();
}
}
private void GiftCertificateCondition()
{
if (uxGiftCertificate.IsGiftCertificate)
{
uxProductKit.DisableProductKitControl();
uxProductSubscription.DisableProductScuscriptionControl();
uxRecurring.DisableRecurring();
}
else
{
uxRecurring.EnableRecurring();
}
}
private void ProductKitCondition()
{
if (uxProductKit.IsProductKit)
{
uxProductKit.SetIsProductKit( true );
uxProductAttributes.SetProductKitControlVisible( true );
uxProductSubscription.DisableProductScuscriptionControl();
uxProductAttributes.IsDownloadableEnabled( false );
}
else
{
uxProductKit.SetIsProductKit( false );
uxProductAttributes.SetProductKitControlVisible( false );
uxProductSubscription.EnableProductScuscriptionControl();
uxProductAttributes.IsDownloadableEnabled( true );
}
}
private void ShowHideQuantityDiscount()
{
if (uxProductKit.IsProductKit || uxProductSubscription.IsProductSubscription)
{
uxProductAttributes.SetEnabledQuantityDiscount( false );
}
else
{
uxProductAttributes.SetEnabledQuantityDiscount( true );
}
}
private void ShowHideMinMaxQTY()
{
if (uxProductSubscription.IsProductSubscription)
{
uxProductAttributes.SetEnabledMinMaxQTY( false );
uxProductAttributes.SetMinQuantity( 1 );
uxProductAttributes.SetMaxQuantity( 1 );
}
else
{
uxProductAttributes.SetEnabledMinMaxQTY( true );
}
}
private void ShowHideDownloadable()
{
if (uxProductKit.IsProductKit || uxRecurring.IsRecurring)
{
uxProductAttributes.IsDownloadableEnabled( false );
}
else
{
uxProductAttributes.IsDownloadableEnabled( true );
}
}
#endregion
#region Protected
protected string CurrentID
{
get
{
if (IsEditMode())
return MainContext.QueryString["ProductID"];
else
return "0";
}
}
protected void Page_Load( object sender, EventArgs e )
{
uxLanguageControl.BubbleEvent += new EventHandler( Language_RefreshHandler );
uxProductInfo.CurrentCulture = uxLanguageControl.CurrentCulture;
uxDepartmentInfo.CurrentCulture = uxLanguageControl.CurrentCulture;
uxProductSeo.CurrentCulture = uxLanguageControl.CurrentCulture;
uxProductSeo.StoreID = uxStoreList.CurrentSelected;
uxProductAttributes.CurrentCulture = uxLanguageControl.CurrentCulture;
uxProductAttributes.SetEditMode( IsEditMode() );
uxProductAttributes.PopulateShippingCostControl();
uxProductAttributes.PopulateSpecificationItemControls();
if (!MainContext.IsPostBack)
{
if (!KeyUtilities.IsMultistoreLicense())
{
uxStoreList.Visible = false;
uxStoreViewLabel.Visible = false;
}
uxProductAttributes.InitTaxClassDrop();
uxProductAttributes.InitDiscountDrop();
PopulateLink();
uxProductAttributes.PopulateDropdown();
uxProductSubscription.InitDropDown();
}
uxTabContainer.ActiveTabIndex = TabId;
}
protected void Page_PreRender( object sender, EventArgs e )
{
if (!KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName ))
{
ucProductSubscriptionTR.Visible = false;
}
if (Action == "copy" && !MainContext.IsPostBack)
{
uxMessage.DisplayMessage( Resources.ProductMessages.CopySuccess );
}
if (!MainContext.IsPostBack)
{
uxProductAttributes.SetOptionList();
}
if (IsEditMode())
{
if (!MainContext.IsPostBack)
{
PopulateControls();
if (CurrentID != null &&
int.Parse( CurrentID ) >= 0)
{
Product product = DataAccessContext.ProductRepository.GetOne(
uxLanguageControl.CurrentCulture, CurrentID, uxStoreList.CurrentSelected );
uxProductAttributes.SelectOptionList( product );
uxProductAttributes.PopulateStockOptionControl();
}
}
}
else
{
if (!MainContext.IsPostBack)
{
uxEditButton.Visible = false;
CopyVisible( false );
PopulateControls();
uxProductAttributes.HideStockOption();
uxProductIDTR.Visible = false;
uxProductAttributes.PopulateStockVisibility();
//Add code for Recurring.
uxRecurring.HideRecurring();
}
}
uxProductAttributes.RestoreSessionData();
uxProductAttributes.SetWholesaleVisible( uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring );
uxProductAttributes.SetRetailPriceVisible( uxGiftCertificate.IsFixedPrice, uxGiftCertificate.IsGiftCertificate, uxRecurring.IsRecurring );
uxProductAttributes.SetProductRatingVisible( uxGiftCertificate.IsGiftCertificate );
uxGiftCertificate.SetGiftCertificateControlsVisibility( IsEditMode() );
ProductSubscriptionCondition();
RecurringCondition();
ProductKitCondition();
GiftCertificateCondition();
ShowHideQuantityDiscount();
ShowHideDownloadable();
ShowHideMinMaxQTY();
uxProductAttributes.SetFixedShippingCostVisibility( uxGiftCertificate.IsGiftCertificate );
DisplayControlsByVersion();
EnforcePermission();
}
protected void uxSaveAndViewImageLinkButton_Click( object sender, EventArgs e )
{
Update();
MainContext.RedirectMainControl( "ProductImageList.ascx", "ProductID=" + CurrentID );
}
protected void uxEditButton_Click( object sender, EventArgs e )
{
Update();
}
protected void uxCopyButton_Click( object sender, EventArgs e )
{
try
{
if (Page.IsValid)
{
if (!uxProductAttributes.VerifyInputListOption())
{
DisplayErrorOption();
return;
}
string newProductID = AddNew();
Product originalProduct = DataAccessContext.ProductRepository.GetOne( uxLanguageControl.CurrentCulture, CurrentID, new StoreRetriever().GetCurrentStoreID() );
CopyRemainingProductLocales( originalProduct, newProductID );
CopyMetaInformation( originalProduct, newProductID );
CopyProductPrice( originalProduct, newProductID );
ClearInputFields();
uxProductAttributes.PopulateStockOptionControl();
AdminUtilities.ClearSiteMapCache();
MainContext.RedirectMainControl( "ProductEdit.ascx", String.Format( "ProductID={0}&action=copy", newProductID ) );
}
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
}
protected void uxIsFixedPriceDrop_SelectedIndexChanged( object sender, EventArgs e )
{
uxStatusHidden.Value = "Refresh";
}
protected void uxReviewLink_Click( object sender, EventArgs e )
{
MainContext.RedirectMainControl( "ProductReviewList.ascx", String.Format( "ProductID={0}", CurrentID ) );
}
protected void uxDeleteButton_Click( object sender, EventArgs e )
{
try
{
bool deleted = false;
DataAccessContext.ProductRepository.Delete( CurrentID );
DataAccessContextDeluxe.PromotionProductRepository.DeleteByProductID( CurrentID );
DataAccessContextDeluxe.ProductSubscriptionRepository.DeleteByProductID( CurrentID );
deleted = true;
if (deleted)
{
uxMessage.DisplayMessage( Resources.ProductMessages.DeleteSuccess );
MainContext.RedirectMainControl( "ProductList.ascx" );
}
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
}
#endregion
#region Public Methods
public bool IsEditMode()
{
return (_mode == Mode.Edit);
}
public void SetEditMode()
{
_mode = Mode.Edit;
}
public int GetNumberOfCategories()
{
return DataAccessContext.CategoryRepository.GetAll( uxLanguageControl.CurrentCulture, "CategoryID" ).Count;
}
private void PopulateLanguageSection()
{
if (CurrentID != null &&
int.Parse( CurrentID ) > 0)
{
Product product = DataAccessContext.ProductRepository.GetOne(
uxLanguageControl.CurrentCulture, CurrentID, new StoreRetriever().GetCurrentStoreID() );
}
uxProductInfo.CurrentCulture = uxLanguageControl.CurrentCulture;
uxProductInfo.PopulateControls();
uxDepartmentInfo.CurrentCulture = uxLanguageControl.CurrentCulture;
uxProductAttributes.CurrentCulture = uxLanguageControl.CurrentCulture;
uxProductSeo.CurrentCulture = uxLanguageControl.CurrentCulture;
uxProductSeo.StoreID = uxStoreList.CurrentSelected;
uxProductSeo.PopulateControls();
uxProductKit.CurrentCulture = uxLanguageControl.CurrentCulture;
uxProductImageList.CurrentCulture = uxLanguageControl.CurrentCulture;
uxProductImageList.PopulateControls();
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using EIDSS.Reports.BaseControls.Filters;
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.OperationContext;
using bv.common.Core;
using bv.model.BLToolkit;
using bv.winclient.Layout;
using eidss.model.Reports.Common;
namespace EIDSS.Reports.BaseControls.Keeper
{
public partial class BaseDateKeeper : BaseReportKeeper
{
private readonly Type m_ReportType;
private static readonly ComponentResourceManager m_Resources = new ComponentResourceManager(typeof (BaseDateKeeper));
public bool m_IsMonthRange;
private List<ItemWrapper> m_MonthCollection;
//For design-time only
internal BaseDateKeeper()
: this(typeof (BaseDateReport), new Dictionary<string, string>())
{
}
public BaseDateKeeper(Type reportType)
: this(reportType, new Dictionary<string, string>())
{
}
public BaseDateKeeper(Type reportType, Dictionary<string, string> parameters)
: base(parameters)
{
Utils.CheckNotNull(reportType, "reportType");
m_ReportType = reportType;
if (!(typeof (BaseDateReport)).IsAssignableFrom(reportType))
{
throw new ApplicationException("Repor Type should be child of BaseDateReport");
}
InitializeComponent();
EndMonthLabel.VisibleChanged += EndMonthLabel_VisibleChanged;
LayoutCorrector.SetStyleController(spinEdit, LayoutCorrector.MandatoryStyleController);
spinEdit.Value = DateTime.Now.Year;
BindLookup(cbMonth, MonthCollection, label2.Text);
BindLookup(cbMonthEnd, MonthCollection, EndMonthLabel.Text);
cbMonth.ItemIndex = DateTime.Now.Month - 1;
cbMonth.EditValue = MonthCollection[DateTime.Now.Month - 1];
m_HasLoad = true;
}
private void EndMonthLabel_VisibleChanged(object sender, EventArgs e)
{
EndMonthLabel.Visible = IsMonthRange;
}
[Browsable(true)]
[DefaultValue(false)]
public bool IsMonthRange
{
get { return m_IsMonthRange; }
set
{
m_IsMonthRange = value;
cbMonthEnd.Visible = m_IsMonthRange;
EndMonthLabel.Visible = m_IsMonthRange;
if (m_IsMonthRange)
{
label2.Text = StartMonthLabel.Text;
}
}
}
[Browsable(false)]
protected int YearParam
{
get { return (int) spinEdit.Value; }
}
[Browsable(false)]
protected int? StartMonthParam
{
get
{
return (cbMonth.EditValue == null)
? (int?) null
: ((ItemWrapper) cbMonth.EditValue).Number;
}
}
[Browsable(false)]
protected int? EndMonthParam
{
get
{
return (cbMonthEnd.EditValue == null)
? (int?) null
: ((ItemWrapper) cbMonthEnd.EditValue).Number;
}
}
public void SetMandatory()
{
BaseFilter.SetLookupMandatory(cbMonth);
BaseFilter.SetLookupMandatory(cbMonthEnd);
}
protected override BaseReport GenerateReport(DbManagerProxy manager)
{
object reportObject = Activator.CreateInstance(m_ReportType, 0, null, null, CurrentCulture.CultureInfo);
var report = ((BaseDateReport) reportObject);
var model = new BaseDateModel(CurrentCulture.ShortName, YearParam, StartMonthParam, EndMonthParam, UseArchive);
report.SetParameters(manager, model);
return report;
}
protected override void ApplyResources()
{
try
{
IsResourceLoading = true;
m_MonthCollection = null;
m_HasLoad = false;
base.ApplyResources();
m_Resources.ApplyResources(cbMonth, "cbMonth");
m_Resources.ApplyResources(label2, "label2");
m_Resources.ApplyResources(label1, "label1");
m_Resources.ApplyResources(StartMonthLabel, "StartMonthLabel");
m_Resources.ApplyResources(EndMonthLabel, "EndMonthLabel");
if (IsMonthRange)
{
label2.Text = StartMonthLabel.Text;
}
// Note: do not load resources for spinEdit because it reset it's value
//m_Resources.ApplyResources(spinEdit, "spinEdit");
ApplyLookupResources(cbMonth, MonthCollection, StartMonthParam, label2.Text);
ApplyLookupResources(cbMonthEnd, MonthCollection, EndMonthParam, EndMonthLabel.Text);
}
finally
{
m_HasLoad = true;
IsResourceLoading = false;
}
}
private List<ItemWrapper> MonthCollection
{
get
{
if (m_MonthCollection == null)
{
m_MonthCollection = CreateMonthCollection();
}
return m_MonthCollection;
}
}
private void spinEdit_EditValueChanged(object sender, EventArgs e)
{
ReloadReportIfFormLoaded(spinEdit);
}
private void cbMonth_EditValueChanged(object sender, EventArgs e)
{
CorrectMonthRange();
ReloadReportIfFormLoaded(cbMonth);
cbMonthEnd.Enabled = true;
}
private void cbMonthEnd_EditValueChanged(object sender, EventArgs e)
{
CorrectMonthRange();
ReloadReportIfFormLoaded(cbMonthEnd);
}
private void CorrectMonthRange()
{
if ((cbMonthEnd.EditValue != null) && (cbMonth.EditValue != null))
{
var startMonth = ((ItemWrapper) (cbMonth.EditValue));
var endMonth = ((ItemWrapper) (cbMonthEnd.EditValue));
if (endMonth.Number < startMonth.Number)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
cbMonthEnd.EditValue = cbMonth.EditValue;
}
}
}
}
private void cbMonth_ButtonClick(object sender, ButtonPressedEventArgs e)
{
if (e.Button.Kind == ButtonPredefines.Delete && sender is LookUpEdit)
{
using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading))
{
if (sender == cbMonth)
{
cbMonth.EditValue = null;
cbMonthEnd.EditValue = null;
cbMonthEnd.Enabled = false;
}
if (sender == cbMonthEnd)
{
cbMonthEnd.EditValue = null;
}
}
ReloadReportIfFormLoaded((LookUpEdit) sender);
}
}
public static List<ItemWrapper> CreateMonthCollection()
{
var defaultMonth = new[]
{
"January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"
};
return CreateCollection(defaultMonth, "cbMonth");
}
public static List<ItemWrapper> CreateCounterCollection()
{
var defaults = new[] {"Absolute number", "For 10.000 population", "For 100.000 population", "For 1.000.000 population"};
return CreateCollection(defaults, "cbCounter");
}
public static List<ItemWrapper> CreatePeriodTypeCollection()
{
var defaults = new[] {"Year", "Half-year", "Quarter", "Month"};
return CreateCollection(defaults, "cbPeriodType");
}
public static List<ItemWrapper> CreateHalfYearCollection()
{
return CreateCollection(new[] {"I", "II"}, "cbHalfYear");
}
public static List<ItemWrapper> CreateQuarterCollection()
{
return CreateCollection(new[] {"1", "2", "3", "4"}, "cbQuarter");
}
public static List<ItemWrapper> CreateCollection(string[] englishDefaults, string resourcename)
{
var collection = new List<ItemWrapper>();
for (int index = 0; index < englishDefaults.Length; index++)
{
string counterName = m_Resources.GetString(resourcename + index);
if (String.IsNullOrEmpty(counterName))
{
counterName = englishDefaults[index];
}
collection.Add(new ItemWrapper(counterName, index + 1));
}
return collection;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using dk.nita.saml20.identity;
using dk.nita.saml20.protocol;
using dk.nita.saml20.Schema.Metadata;
using dk.nita.saml20.Utils;
using Saml2.Properties;
using Trace=dk.nita.saml20.Utils.Trace;
using System.Security.Cryptography;
namespace dk.nita.saml20.config
{
/// <summary>
/// Configuration elements for SAML20 Federation
/// To create a new XSD Run this command:
/// xsd -t:dk.nita.saml20.config.SAML20Federation dk.nita.saml20.dll
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
[XmlRoot(ConfigurationConstants.SectionNames.SAML20Federation, Namespace = ConfigurationConstants.NamespaceUri, IsNullable = false)]
public class SAML20FederationConfig : ConfigurationInstance<SAML20FederationConfig>
{
/// <summary>
/// Initializes a new instance of the <see cref="SAML20FederationConfig"/> class.
/// </summary>
public SAML20FederationConfig()
{
ServiceProvider = new ServiceProviderElement();
_idpEndpoints = new IDPEndpoints();
}
/// <summary>
/// Requested attributes
/// </summary>
[XmlElement]
public RequestedAttributes RequestedAttributes;
/// <summary>
/// Service provider
/// </summary>
[XmlElement]
public ServiceProviderElement ServiceProvider;
private CommonDomainConfig _commonDomain;
/// <summary>
/// Gets or sets the common domain configuration section.
/// </summary>
[XmlElement(ElementName = "CommonDomain")]
public CommonDomainConfig CommonDomain
{
get
{
if (_commonDomain == null)
_commonDomain = new CommonDomainConfig();
return _commonDomain;
}
set
{
_commonDomain = value;
}
}
private IDPEndpoints _idpEndpoints;
/// <summary>
/// Gets or sets the IDP endpoints.
/// </summary>
/// <value>The IDP endpoints.</value>
[XmlIgnore]
public List<IDPEndPoint> IDPEndPoints
{
get { return _idpEndpoints.IDPEndPoints; }
set { _idpEndpoints.IDPEndPoints = value; }
}
/// <summary>
/// Gets or sets the endpoints.
/// </summary>
/// <value>The endpoints.</value>
[XmlElement("IDPEndPoints")]
public IDPEndpoints Endpoints
{
get { return _idpEndpoints; }
set { _idpEndpoints = value; }
}
/// <summary>
/// Metadata element
/// </summary>
[XmlElement("Metadata")] public ConfigMetadata Metadata;
/// <summary>
/// Finds an endpoint given its id.
/// </summary>
/// <param name="endPointId">The end point id.</param>
/// <returns></returns>
public IDPEndPoint FindEndPoint(string endPointId)
{
return IDPEndPoints.Find(delegate(IDPEndPoint ep) { return ep.Id == endPointId; });
}
}
/// <summary>
/// Holds common domain configuration for a service provider
/// </summary>
public class CommonDomainConfig
{
/// <summary>
/// Is common domain cookie reading enabled
/// </summary>
[XmlAttribute(AttributeName = "enabled")]
public bool Enabled;
/// <summary>
/// A full url to the local common domain cookie reader endpoint.
/// </summary>
[XmlAttribute(AttributeName = "localReaderEndpoint")]
public string LocalReaderEndpoint;
}
/// <summary>
/// Configuration element that defines settings for generating metadata.
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class ConfigMetadata
{
/// <summary>
/// Artifact protocol binding is not a part of DK-SAML2.0 and should only be included in metadata
/// when communicating with a non DK-SAML2.0 compliant IdP
/// </summary>
[XmlAttribute("IncludeArtifactEndpoints", Namespace = ConfigurationConstants.NamespaceUri)]
public bool IncludeArtifactEndpoints;
}
/// <summary>
/// Requested attributes configuration element
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class RequestedAttributes
{
/// <summary>
/// Initializes a new instance of the <see cref="RequestedAttributes"/> class.
/// </summary>
public RequestedAttributes()
{
Attributes = new List<Attribute>();
}
/// <summary>
/// Attributes
/// </summary>
[XmlElement("att")]
public List<Attribute> Attributes;
}
/// <summary>
/// Attribute configuration element
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class Attribute
{
/// <summary>
/// Attribute name, eg. urn:oid:2.5.4.5 or urn:oid:2.5.4.3.
/// </summary>
[XmlAttribute("name", Namespace = ConfigurationConstants.NamespaceUri)]
public string name;
/// <summary>
/// Is the attribute required
/// </summary>
[XmlAttribute("isRequired", Namespace = ConfigurationConstants.NamespaceUri)]
public string required;
/// <summary>
/// Gets or sets a value indicating whether the attribute is required.
/// </summary>
/// <value>
/// <c>true</c> if the attribute is required; otherwise, <c>false</c>.
/// </value>
[XmlIgnore]
public bool IsRequired
{
get
{
if (string.IsNullOrEmpty(required))
return false;
return Convert.ToBoolean(required);
}
set { required = Convert.ToString(value); }
}
}
/// <summary>
/// Endpoints configuration element.
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class IDPEndpoints
{
/// <summary>
/// Initializes a new instance of the <see cref="IDPEndpoints"/> class.
/// </summary>
public IDPEndpoints()
{
IDPEndPoints = new List<IDPEndPoint>();
_fileInfo = new Dictionary<string, DateTime>();
_fileToEntity = new Dictionary<string, string>();
Refresh();
}
/// <summary>
/// The directory in which the metadata files of trusted identity providers should be found.
/// </summary>
[XmlAttribute("metadata")]
public string metadataLocation;
/// <summary>
/// The encodings that should be attempted when a metadata file does not contain an encoding attribute and
/// the signature doesn't validate. Contains a space-delimited list of encoding names to try out.
/// </summary>
[XmlAttribute("encodings")]
public string encodings;
/// <summary>
/// URL to a page that is used, in case more than one IDPEndPoint is configured,
/// AND no Common Domain Cookie is set AND no default IDP is selected with the default-attribute.
/// </summary>
[XmlAttribute("idpSelectionUrl")]
public string idpSelectionUrl;
/// <summary>
/// Contains Encoding instances of the the encodings that should by tried when a metadata file does not have its
/// encoding specified.
/// </summary>
[XmlIgnore]
private List<Encoding> _encodings;
/// <summary>
/// Finds an endpoint given its id.
/// </summary>
/// <param name="endPointId">The endpoint's id.</param>
/// <returns></returns>
public IDPEndPoint FindEndPoint(string endPointId)
{
return IDPEndPoints.Find(delegate(IDPEndPoint ep) { return ep.Id == endPointId; });
}
/// <summary>
/// Returns a list of the encodings that should be tried when a metadata file does not contain a valid signature
/// or cannot be loaded by the XmlDocument class. Either returns a list specified by the administrator in the configuration file
/// or a default list.
/// </summary>
private List<Encoding> _getEncodings()
{
if (_encodings != null)
return _encodings;
if (string.IsNullOrEmpty(encodings))
{
// If it has not been specified in the config file, use the defaults.
_encodings = new List<Encoding>();
_encodings.Add(Encoding.UTF8);
_encodings.Add(Encoding.GetEncoding("iso-8859-1"));
return _encodings;
}
string[] encs = encodings.Split(' ');
_encodings = new List<Encoding>(encs.Length);
foreach (string enc in encs)
_encodings.Add(Encoding.GetEncoding(enc));
return _encodings;
}
/// <summary>
/// List of IdP endpoints
/// </summary>
[XmlElement("add")]
public List<IDPEndPoint> IDPEndPoints;
#region Handling of metadata files
/// <summary>
/// A list of the files that have currently been loaded. The filename is used as key, while last seen modification time is used as value.
/// </summary>
[XmlIgnore]
private Dictionary<string, DateTime> _fileInfo;
/// <summary>
/// This dictionary links a file name to the entity id of the metadata document in the file.
/// </summary>
[XmlIgnore]
private Dictionary<string, string> _fileToEntity;
/// <summary>
/// Refreshes the information retrieved from the directory containing metadata files.
/// </summary>
public void Refresh()
{
if (metadataLocation == null)
return;
if (!Directory.Exists(metadataLocation))
throw new DirectoryNotFoundException(Resources.MetadataLocationNotFoundFormat(metadataLocation));
// Start by removing information on files that are no long in the directory.
List<string> keys = new List<string>(_fileInfo.Keys.Count);
keys.AddRange(_fileInfo.Keys);
foreach (string file in keys)
if (!File.Exists(file))
{
_fileInfo.Remove(file);
if (_fileToEntity.ContainsKey(file))
{
IDPEndPoint endp = FindEndPoint(_fileToEntity[file]);
if (endp != null)
endp.metadata = null;
_fileToEntity.Remove(file);
}
}
// Detect added classes
string[] files = Directory.GetFiles(metadataLocation);
foreach (string file in files)
{
Saml20MetadataDocument metadataDoc;
if (_fileInfo.ContainsKey(file))
{
if (_fileInfo[file] != File.GetLastWriteTime(file))
metadataDoc = ParseFile(file);
else
continue;
} else
{
metadataDoc = ParseFile(file);
}
if (metadataDoc != null)
{
IDPEndPoint endp = FindEndPoint(metadataDoc.EntityId);
if (endp == null) // If the endpoint does not exist, create it.
{
endp = new IDPEndPoint();
IDPEndPoints.Add(endp);
}
endp.Id = endp.Name = metadataDoc.EntityId; // Set some default valuDes.
endp.metadata = metadataDoc;
if (_fileToEntity.ContainsKey(file))
_fileToEntity.Remove(file);
_fileToEntity.Add(file, metadataDoc.EntityId);
}
}
}
/// <summary>
/// Parses the metadata files found in the directory specified in the configuration.
/// </summary>
private Saml20MetadataDocument ParseFile(string file)
{
XmlDocument doc = LoadFileAsXmlDocument(file);
//_fileInfo[file] = File.GetLastWriteTime(file); // Mark that we have seen the file.
try
{
foreach (XmlNode child in doc.ChildNodes)
{
if (child.NamespaceURI == Saml20Constants.METADATA)
{
if (child.LocalName == EntityDescriptor.ELEMENT_NAME)
return new Saml20MetadataDocument(doc);
// TODO Decide how to handle several entities in one metadata file.
if (child.LocalName == EntitiesDescriptor.ELEMENT_NAME)
throw new NotImplementedException();
}
}
// No entity descriptor found.
throw new InvalidDataException(); // BAIIIIIIL!!
} catch(Exception e)
{
// Probably not a metadata file.
Trace.TraceData(TraceEventType.Error, file, "Probably not a SAML2.0 metadata file.", e.ToString());
return null;
}
}
/// <summary>
/// Loads a file into an XmlDocument. If the loading or the signature check fails, the method will retry using another encoding.
/// </summary>
private XmlDocument LoadFileAsXmlDocument(string filename)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
try
{
// First attempt a standard load, where the XML document is expected to declare its encoding by itself.
doc.Load(filename);
try
{
if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
throw new InvalidOperationException("Invalid file signature");
// Throw an exception to get into quirksmode.
}catch(CryptographicException)
{
//Ignore cryptographic exception caused by Geneva server's inability to generate a
//.net compliant xml signature
return ParseGenevaServerMetadata(doc);
}
return doc;
}
catch (XmlException)
{
// Enter quirksmode
List<Encoding> encs = _getEncodings();
foreach (Encoding encoding in encs)
{
StreamReader reader = null;
try
{
reader = new StreamReader(filename, encoding);
doc.Load(reader);
if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
continue;
}
catch (XmlException)
{ continue; }
finally
{
if (reader != null)
reader.Close();
}
return doc;
}
}
return null;
}
private static XmlDocument ParseGenevaServerMetadata(XmlDocument doc)
{
if (doc == null) throw new ArgumentNullException("doc");
if( doc.DocumentElement == null) throw new ArgumentException("DocumentElement cannot be null", "doc");
XmlDocument other = new XmlDocument();
other.PreserveWhitespace = true;
other.LoadXml(doc.OuterXml);
List<XmlNode> remove = new List<XmlNode>();
foreach(XmlNode node in other.DocumentElement.ChildNodes)
{
if(node.Name != IDPSSODescriptor.ELEMENT_NAME)
{
remove.Add(node);
}
}
foreach (XmlNode node in remove)
{
other.DocumentElement.RemoveChild(node);
}
return other;
}
#endregion
}
/// <summary>
/// Service provider configuration element
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class ServiceProviderElement
{
/// <summary>
/// Initializes a new instance of the <see cref="ServiceProviderElement"/> class.
/// </summary>
public ServiceProviderElement()
{
ContactPerson = new List<Contact>();
NameIdFormats = new NameIdFormatsElement();
}
private string _id;
/// <summary>
/// Gets or sets the ID.
/// </summary>
/// <value>The ID.</value>
[XmlAttribute(AttributeName = "id")]
public string ID
{
get
{
#if DEBUG
if (_id == "urn:")
{
string machineName = Environment.MachineName.ToLower();
return "urn:" + machineName.Substring(0, 1).ToUpper() + machineName.Remove(0, 1);
}
#endif
return _id;
}
set
{
if (!Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute))
throw new ConfigurationErrorsException(Resources.InvalidWellformedAbsoluteUriStringFormat(value));
_id = value;
}
}
private string _server;
/// <summary>
/// Gets or sets the server.
/// </summary>
/// <value>The server.</value>
[XmlAttribute(AttributeName = "server")]
public string Server
{
get
{
#if DEBUG
if (_server == "http://" || _server == "https://")
return _server + Environment.MachineName.ToLower() + "." + Environment.GetEnvironmentVariable("USERDNSDOMAIN").ToLower();
#endif
return _server;
}
set { _server = value; }
}
/// <summary>
/// List of service endpoints
/// </summary>
[XmlElement("ServiceEndpoint")] public List<Saml20ServiceEndpoint> serviceEndpoints;
/// <summary>
/// Gets the logout endpoint.
/// </summary>
/// <value>The logout endpoint.</value>
public Saml20ServiceEndpoint LogoutEndpoint
{
get
{
return FindEndpoint(EndpointType.LOGOUT);
}
}
/// <summary>
/// Gets the sign on endpoint.
/// </summary>
/// <value>The sign on endpoint.</value>
public Saml20ServiceEndpoint SignOnEndpoint
{
get
{
return FindEndpoint(EndpointType.SIGNON);
}
}
/// <summary>
/// Gets the metadata endpoint.
/// </summary>
/// <value>The metadata endpoint.</value>
public Saml20ServiceEndpoint MetadataEndpoint
{
get
{
return FindEndpoint(EndpointType.METADATA);
}
}
/// <summary>
/// Supported NameIdFormats
/// </summary>
public NameIdFormatsElement NameIdFormats;
private Saml20ServiceEndpoint FindEndpoint(EndpointType type)
{
return serviceEndpoints.Find(delegate(Saml20ServiceEndpoint ep) { return ep.endpointType == type; });
}
/// <summary>
/// Organization
/// </summary>
[XmlElement(Namespace = Saml20Constants.METADATA)]
public Organization Organization;
/// <summary>
/// Contact person
/// </summary>
[XmlElement(Namespace = Saml20Constants.METADATA)]
public List<Contact> ContactPerson;
}
/// <summary>
/// Holds NameIdFormats supported by the service provider
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class NameIdFormatsElement
{
/// <summary>
/// Initializes a new instance of the <see cref="NameIdFormatsElement"/> class.
/// </summary>
public NameIdFormatsElement()
{
NameIdFormats = new List<NameIdFormatElement>();
}
/// <summary>
/// Shorthand for supporting all NameIdFormats
/// </summary>
[XmlAttribute(AttributeName="all")]
public bool All;
/// <summary>
/// List of supported NameFormatIds
/// </summary>
[XmlElement(ElementName = "add")]
public List<NameIdFormatElement> NameIdFormats;
}
/// <summary>
/// An element that holds a single supported NameIdFormat
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class NameIdFormatElement
{
/// <summary>
/// The NameIdFormat
/// </summary>
[XmlAttribute(AttributeName="nameIdFormat")]
public string NameIdFormat;
}
/// <summary>
/// The service provider behaviour configuration element
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public enum ServiceProviderBehaviour
{
/// <summary>
/// Keep token
/// </summary>
KeepToken,
/// <summary>
/// Translate token
/// </summary>
TranslateToken
}
/// <summary>
/// The Saml20Service endpoint configuration element
/// </summary>
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class Saml20ServiceEndpoint
{
/// <summary>
/// The local path to the url on which this endpoint should be placed.
/// </summary>
[XmlAttribute("localpath")]
public string localPath;
/// <summary>
/// Type of endpoint
/// </summary>
[XmlAttribute("type")]
public EndpointType endpointType;
/// <summary>
/// Numeric index of this endpoint
/// </summary>
[XmlAttribute("index")]
public ushort endPointIndex;
/// <summary>
/// Redirect to this url on succesful request
/// </summary>
[XmlAttribute("redirectUrl")]
public string RedirectUrl;
/// <summary>
/// Saml binding
/// </summary>
[XmlAttribute("binding")]
public SAMLBinding Binding = SAMLBinding.NOT_SET;
/// <summary>
/// Error handling behaviour
/// </summary>
[XmlAttribute("errorBehaviour")]
public ErrorBehaviour ErrorBehaviour = ErrorBehaviour.SHOWPAGE;
}
/// <summary>
/// Endpoint types (signon, logout or metadata)
/// </summary>
public enum EndpointType
{
/// <summary>
/// Signon endpoint
/// </summary>
[XmlEnum("signon")]
SIGNON,
/// <summary>
/// Logout endpoint
/// </summary>
[XmlEnum("logout")]
LOGOUT,
/// <summary>
/// Metadata endpoint
/// </summary>
[XmlEnum("metadata")]
METADATA
}
/// <summary>
/// Error handling behaviour (showpage, throwexception)
/// </summary>
public enum ErrorBehaviour
{
/// <summary>
/// ShowPage behaviour
/// </summary>
[XmlEnum("showpage")]
SHOWPAGE,
/// <summary>
/// ThrowException behaviour
/// </summary>
[XmlEnum("throwexception")]
THROWEXCEPTION
}
/// <summary>
/// the IDPEndpoint configuration element
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class IDPEndPoint
{
/// <summary>
/// The metadata associated with the endpoint.
/// </summary>
[XmlIgnore]
public Saml20MetadataDocument metadata;
/// <summary>
/// Id
/// </summary>
[XmlAttribute(AttributeName = "id")]
public string Id;
/// <summary>
/// Name
/// </summary>
[XmlAttribute(AttributeName = "name")]
public string Name;
/// <summary>
/// Override option for the default UTF-8 encoding convention on SAML responses
/// </summary>
[XmlAttribute(AttributeName = "responseEncoding")]
public string ResponseEncoding;
/// <summary>
/// Enable quirks mode
/// </summary>
[XmlAttribute(AttributeName = "QuirksMode")]
public bool QuirksMode;
/// <summary>
/// Omit signature checks on assertions.
/// </summary>
[XmlAttribute(AttributeName = "omitAssertionSignatureCheck")]
public bool OmitAssertionSignatureCheck;
/// <summary>
/// Force authentication on each authnrequest
/// </summary>
[XmlAttribute(AttributeName = "forceAuthn")]
public bool ForceAuthn;
/// <summary>
/// AuthnRequest is passive
/// </summary>
[XmlAttribute(AttributeName = "isPassive")]
public bool IsPassive;
/// <summary>
/// Use default in case common domain cookie is not set, and more than one endpoint is available
/// </summary>
[XmlAttribute(AttributeName = "default")]
public bool Default;
/// <summary>
/// Certificate validation
/// </summary>
[XmlElement(ElementName = "CertificateValidation")]
public CertificateValidationElements CertificateValidation;
/// <summary>
/// AttributeQuery configuration parameters
/// </summary>
[XmlElement(ElementName = "AttributeQuery")]
public HttpBasicAuthElement AttributeQuery;
/// <summary>
/// ArtifactResolution configuration parameters
/// </summary>
[XmlElement(ElementName = "ArtifactResolution")]
public HttpBasicAuthElement ArtifactResolution;
/// <summary>
/// Single sign on
/// </summary>
[XmlElement(ElementName = "SSO")]
public IDPEndPointElement SSOEndpoint;
/// <summary>
/// Single log off
/// </summary>
[XmlElement(ElementName = "SLO")]
public IDPEndPointElement SLOEndpoint;
/// <summary>
/// Common Domain Cookie settings
/// </summary>
[XmlElement(ElementName = "CDC")]
public CDCElement CDC;
/// <summary>
/// Persistent pseudonym
/// </summary>
[XmlElement(ElementName = "PersistentPseudonym")]
public PersistentPseudonymMapper PersistentPseudonym;
/// <summary>
/// Get a URL that redirects the user to the login-page for this IDPEndPoint
/// </summary>
/// <returns></returns>
public string GetIDPLoginUrl()
{
return IDPSelectionUtil.GetIDPLoginUrl(Id);
}
}
/// <summary>
/// Holds rules for certificate validation
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class CertificateValidationElements
{
private List<CertificateValidationElement> _elems;
/// <summary>
/// Initializes a new instance of the <see cref="CertificateValidationElements"/> class.
/// </summary>
public CertificateValidationElements()
{
_elems = new List<CertificateValidationElement>();
}
/// <summary>
/// List certificate validation implementations
/// </summary>
[XmlElement(ElementName = "add")]
public List<CertificateValidationElement> CertificateValidations;
}
/// <summary>
/// A single certificate validation element
/// </summary>
public class CertificateValidationElement
{
/// <summary>
/// The concrete type that implements the ICertificateValidationSpecification interface.
/// </summary>
[XmlAttribute(AttributeName = "type")]
public string type;
}
/// <summary>
/// Holds Http Basic Auth settings
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class HttpBasicAuthElement
{
/// <summary>
/// Is http basic auth enabled
/// </summary>
[XmlAttribute(AttributeName = "enableHttpBasicAuth")]
public bool Enabled;
/// <summary>
/// The username
/// </summary>
[XmlAttribute(AttributeName = "username")]
public string Username;
/// <summary>
/// The password
/// </summary>
[XmlAttribute(AttributeName = "password")]
public string Password;
}
/// <summary>
/// Holds Common Domain Cookie settings
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class CDCElement
{
/// <summary>
/// Extra common domain cookie settings.
/// </summary>
[XmlElement(ElementName = "Settings")]
public ExtraSettings ExtraSettings;
}
/// <summary>
/// Extra key value settings for a configuration element
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class ExtraSettings
{
/// <summary>
/// List of extra settings
/// </summary>
[XmlElement(ElementName="add")]
public List<KeyValue> KeyValues;
}
/// <summary>
/// Hold key value pairs.
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class KeyValue
{
/// <summary>
/// The key (name)
/// </summary>
[XmlAttribute(AttributeName="key")]
public string Key;
/// <summary>
/// The value
/// </summary>
[XmlAttribute(AttributeName = "value")]
public string Value;
}
/// <summary>
/// The persistent pseudonym mapper configuration element
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class PersistentPseudonymMapper
{
private IPersistentPseudonymMapper _mapper = null;
/// <summary>
/// Mapper to use
/// </summary>
[XmlAttribute("mapper")]
public string Mapper;
///<summary>
/// Returns the runtime-class configured pseudonym mapper (if any is present) for a given IdP.
///</summary>
///<returns></returns>
public IPersistentPseudonymMapper GetMapper()
{
if (String.IsNullOrEmpty(Mapper))
return null;
if (_mapper != null)
return _mapper;
_mapper = (IPersistentPseudonymMapper)Activator.CreateInstance(Type.GetType(Mapper), true);
return _mapper;
}
}
/// <summary>
/// The IDPEndPointElement configuration element
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
public class IDPEndPointElement
{
/// <summary>
/// Initializes a new instance of the <see cref="IDPEndPointElement"/> class.
/// </summary>
public IDPEndPointElement()
{}
/// <summary>
/// Constructor that converts the Saml20 Endpoint element to our IDPEndpointElement.
/// </summary>
public IDPEndPointElement(Endpoint endpoint)
{
if (endpoint == null)
throw new ArgumentNullException("endpoint");
Url = endpoint.Location;
switch(endpoint.Binding)
{
case Saml20Constants.ProtocolBindings.HTTP_Post :
Binding = SAMLBinding.POST;
break;
case Saml20Constants.ProtocolBindings.HTTP_Redirect :
Binding = SAMLBinding.REDIRECT;
break;
case Saml20Constants.ProtocolBindings.HTTP_Artifact :
Binding = SAMLBinding.ARTIFACT;
break;
case Saml20Constants.ProtocolBindings.HTTP_SOAP :
Binding = SAMLBinding.SOAP;
break;
default:
throw new InvalidOperationException("Binding not supported: " + endpoint.Binding);
}
}
/// <summary>
/// Url
/// </summary>
[XmlAttribute(AttributeName = "url")]
public string Url;
/// <summary>
/// Binding
/// </summary>
[XmlAttribute(AttributeName = "binding")]
public SAMLBinding Binding;
/// <summary>
/// Force a different protocol binding
/// </summary>
[XmlAttribute(AttributeName = "ForceProtocolBinding")]
public string ForceProtocolBinding;
/// <summary>
/// Allows the caller to access the xml representation of an assertion before it's
/// translated to a strongly typed instance
/// </summary>
[XmlAttribute(AttributeName = "idpTokenAccessor")]
public string IdpTokenAccessor;
}
/// <summary>
/// Saml binding types
/// </summary>
[Serializable]
[XmlType(Namespace = ConfigurationConstants.NamespaceUri)]
[Flags]
public enum SAMLBinding
{
/// <summary>
/// No binding set.
/// </summary>
NOT_SET = 0,
/// <summary>
/// POST binding
/// </summary>
POST = 1,
/// <summary>
/// Redirect binding
/// </summary>
REDIRECT = 2,
/// <summary>
/// Artifact binding
/// </summary>
ARTIFACT = 4,
/// <summary>
/// SOAP binding
/// </summary>
SOAP = 8,
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Globalization;
using System.Runtime.Serialization;
namespace System.Xml
{
internal class XmlBinaryReader : XmlBaseReader
{
private bool _isTextWithEndElement;
private bool _buffered;
private ArrayState _arrayState;
private int _arrayCount;
private int _maxBytesPerRead;
private XmlBinaryNodeType _arrayNodeType;
public XmlBinaryReader()
{
}
public void SetInput(byte[] buffer, int offset, int count,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
MoveToInitial(quotas, session, null);
BufferReader.SetBuffer(buffer, offset, count, dictionary, session);
_buffered = true;
}
public void SetInput(Stream stream,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session)
{
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
MoveToInitial(quotas, session, null);
BufferReader.SetBuffer(stream, dictionary, session);
_buffered = false;
}
private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose)
{
MoveToInitial(quotas);
_maxBytesPerRead = quotas.MaxBytesPerRead;
_arrayState = ArrayState.None;
_isTextWithEndElement = false;
}
public override void Close()
{
base.Close();
}
public override string ReadElementContentAsString()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (!CanOptimizeReadElementContent())
return base.ReadElementContentAsString();
string value;
switch (GetNodeType())
{
case XmlBinaryNodeType.Chars8TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadUTF8String(ReadUInt8());
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.DictionaryTextWithEndElement:
SkipNodeType();
value = BufferReader.GetDictionaryString(ReadDictionaryKey()).Value;
ReadTextWithEndElement();
break;
default:
value = base.ReadElementContentAsString();
break;
}
if (value.Length > Quotas.MaxStringContentLength)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, Quotas.MaxStringContentLength);
return value;
}
public override bool ReadElementContentAsBoolean()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (!CanOptimizeReadElementContent())
return base.ReadElementContentAsBoolean();
bool value;
switch (GetNodeType())
{
case XmlBinaryNodeType.TrueTextWithEndElement:
SkipNodeType();
value = true;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.FalseTextWithEndElement:
SkipNodeType();
value = false;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.BoolTextWithEndElement:
SkipNodeType();
value = (BufferReader.ReadUInt8() != 0);
ReadTextWithEndElement();
break;
default:
value = base.ReadElementContentAsBoolean();
break;
}
return value;
}
public override int ReadElementContentAsInt()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (!CanOptimizeReadElementContent())
return base.ReadElementContentAsInt();
int value;
switch (GetNodeType())
{
case XmlBinaryNodeType.ZeroTextWithEndElement:
SkipNodeType();
value = 0;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.OneTextWithEndElement:
SkipNodeType();
value = 1;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.Int8TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadInt8();
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.Int16TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadInt16();
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.Int32TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadInt32();
ReadTextWithEndElement();
break;
default:
value = base.ReadElementContentAsInt();
break;
}
return value;
}
private bool CanOptimizeReadElementContent()
{
return (_arrayState == ArrayState.None);
}
public override float ReadElementContentAsFloat()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.FloatTextWithEndElement)
{
SkipNodeType();
float value = BufferReader.ReadSingle();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsFloat();
}
public override double ReadElementContentAsDouble()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DoubleTextWithEndElement)
{
SkipNodeType();
double value = BufferReader.ReadDouble();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsDouble();
}
public override decimal ReadElementContentAsDecimal()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DecimalTextWithEndElement)
{
SkipNodeType();
decimal value = BufferReader.ReadDecimal();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsDecimal();
}
public override DateTime ReadElementContentAsDateTime()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DateTimeTextWithEndElement)
{
SkipNodeType();
DateTime value = BufferReader.ReadDateTime();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsDateTime();
}
public override TimeSpan ReadElementContentAsTimeSpan()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.TimeSpanTextWithEndElement)
{
SkipNodeType();
TimeSpan value = BufferReader.ReadTimeSpan();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsTimeSpan();
}
public override Guid ReadElementContentAsGuid()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.GuidTextWithEndElement)
{
SkipNodeType();
Guid value = BufferReader.ReadGuid();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsGuid();
}
public override UniqueId ReadElementContentAsUniqueId()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.UniqueIdTextWithEndElement)
{
SkipNodeType();
UniqueId value = BufferReader.ReadUniqueId();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsUniqueId();
}
public override bool TryGetBase64ContentLength(out int length)
{
length = 0;
if (!_buffered)
return false;
if (_arrayState != ArrayState.None)
return false;
int totalLength;
if (!this.Node.Value.TryGetByteArrayLength(out totalLength))
return false;
int offset = BufferReader.Offset;
try
{
bool done = false;
while (!done && !BufferReader.EndOfFile)
{
XmlBinaryNodeType nodeType = GetNodeType();
SkipNodeType();
int actual;
switch (nodeType)
{
case XmlBinaryNodeType.Bytes8TextWithEndElement:
actual = BufferReader.ReadUInt8();
done = true;
break;
case XmlBinaryNodeType.Bytes16TextWithEndElement:
actual = BufferReader.ReadUInt16();
done = true;
break;
case XmlBinaryNodeType.Bytes32TextWithEndElement:
actual = BufferReader.ReadUInt31();
done = true;
break;
case XmlBinaryNodeType.EndElement:
actual = 0;
done = true;
break;
case XmlBinaryNodeType.Bytes8Text:
actual = BufferReader.ReadUInt8();
break;
case XmlBinaryNodeType.Bytes16Text:
actual = BufferReader.ReadUInt16();
break;
case XmlBinaryNodeType.Bytes32Text:
actual = BufferReader.ReadUInt31();
break;
default:
// Non-optimal or unexpected node - fallback
return false;
}
BufferReader.Advance(actual);
if (totalLength > int.MaxValue - actual)
return false;
totalLength += actual;
}
length = totalLength;
return true;
}
finally
{
BufferReader.Offset = offset;
}
}
private void ReadTextWithEndElement()
{
ExitScope();
ReadNode();
}
private XmlAtomicTextNode MoveToAtomicTextWithEndElement()
{
_isTextWithEndElement = true;
return MoveToAtomicText();
}
public override bool Read()
{
if (this.Node.ReadState == ReadState.Closed)
return false;
if (_isTextWithEndElement)
{
_isTextWithEndElement = false;
MoveToEndElement();
return true;
}
if (_arrayState == ArrayState.Content)
{
if (_arrayCount != 0)
{
MoveToArrayElement();
return true;
}
_arrayState = ArrayState.None;
}
if (this.Node.ExitScope)
{
ExitScope();
}
return ReadNode();
}
private bool ReadNode()
{
if (!_buffered)
BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead);
if (BufferReader.EndOfFile)
{
MoveToEndOfFile();
return false;
}
XmlBinaryNodeType nodeType;
if (_arrayState == ArrayState.None)
{
nodeType = GetNodeType();
SkipNodeType();
}
else
{
DiagnosticUtility.DebugAssert(_arrayState == ArrayState.Element, "");
nodeType = _arrayNodeType;
_arrayCount--;
_arrayState = ArrayState.Content;
}
XmlElementNode elementNode;
PrefixHandleType prefix;
switch (nodeType)
{
case XmlBinaryNodeType.ShortElement:
elementNode = EnterScope();
elementNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.Element:
elementNode = EnterScope();
ReadName(elementNode.Prefix);
ReadName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(elementNode.Prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.ShortDictionaryElement:
elementNode = EnterScope();
elementNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadDictionaryName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.DictionaryElement:
elementNode = EnterScope();
ReadName(elementNode.Prefix);
ReadDictionaryName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(elementNode.Prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.PrefixElementA:
case XmlBinaryNodeType.PrefixElementB:
case XmlBinaryNodeType.PrefixElementC:
case XmlBinaryNodeType.PrefixElementD:
case XmlBinaryNodeType.PrefixElementE:
case XmlBinaryNodeType.PrefixElementF:
case XmlBinaryNodeType.PrefixElementG:
case XmlBinaryNodeType.PrefixElementH:
case XmlBinaryNodeType.PrefixElementI:
case XmlBinaryNodeType.PrefixElementJ:
case XmlBinaryNodeType.PrefixElementK:
case XmlBinaryNodeType.PrefixElementL:
case XmlBinaryNodeType.PrefixElementM:
case XmlBinaryNodeType.PrefixElementN:
case XmlBinaryNodeType.PrefixElementO:
case XmlBinaryNodeType.PrefixElementP:
case XmlBinaryNodeType.PrefixElementQ:
case XmlBinaryNodeType.PrefixElementR:
case XmlBinaryNodeType.PrefixElementS:
case XmlBinaryNodeType.PrefixElementT:
case XmlBinaryNodeType.PrefixElementU:
case XmlBinaryNodeType.PrefixElementV:
case XmlBinaryNodeType.PrefixElementW:
case XmlBinaryNodeType.PrefixElementX:
case XmlBinaryNodeType.PrefixElementY:
case XmlBinaryNodeType.PrefixElementZ:
elementNode = EnterScope();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixElementA);
elementNode.Prefix.SetValue(prefix);
ReadName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.PrefixDictionaryElementA:
case XmlBinaryNodeType.PrefixDictionaryElementB:
case XmlBinaryNodeType.PrefixDictionaryElementC:
case XmlBinaryNodeType.PrefixDictionaryElementD:
case XmlBinaryNodeType.PrefixDictionaryElementE:
case XmlBinaryNodeType.PrefixDictionaryElementF:
case XmlBinaryNodeType.PrefixDictionaryElementG:
case XmlBinaryNodeType.PrefixDictionaryElementH:
case XmlBinaryNodeType.PrefixDictionaryElementI:
case XmlBinaryNodeType.PrefixDictionaryElementJ:
case XmlBinaryNodeType.PrefixDictionaryElementK:
case XmlBinaryNodeType.PrefixDictionaryElementL:
case XmlBinaryNodeType.PrefixDictionaryElementM:
case XmlBinaryNodeType.PrefixDictionaryElementN:
case XmlBinaryNodeType.PrefixDictionaryElementO:
case XmlBinaryNodeType.PrefixDictionaryElementP:
case XmlBinaryNodeType.PrefixDictionaryElementQ:
case XmlBinaryNodeType.PrefixDictionaryElementR:
case XmlBinaryNodeType.PrefixDictionaryElementS:
case XmlBinaryNodeType.PrefixDictionaryElementT:
case XmlBinaryNodeType.PrefixDictionaryElementU:
case XmlBinaryNodeType.PrefixDictionaryElementV:
case XmlBinaryNodeType.PrefixDictionaryElementW:
case XmlBinaryNodeType.PrefixDictionaryElementX:
case XmlBinaryNodeType.PrefixDictionaryElementY:
case XmlBinaryNodeType.PrefixDictionaryElementZ:
elementNode = EnterScope();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryElementA);
elementNode.Prefix.SetValue(prefix);
ReadDictionaryName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.EndElement:
MoveToEndElement();
return true;
case XmlBinaryNodeType.Comment:
ReadName(MoveToComment().Value);
return true;
case XmlBinaryNodeType.EmptyTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Empty);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.ZeroTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Zero);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.OneTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.One);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.TrueTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.True);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.FalseTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.False);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.BoolTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ReadUInt8() != 0 ? ValueHandleType.True : ValueHandleType.False);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.Chars8TextWithEndElement:
if (_buffered)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt8());
else
ReadPartialUTF8Text(true, ReadUInt8());
return true;
case XmlBinaryNodeType.Chars8Text:
if (_buffered)
ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt8());
else
ReadPartialUTF8Text(false, ReadUInt8());
return true;
case XmlBinaryNodeType.Chars16TextWithEndElement:
if (_buffered)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt16());
else
ReadPartialUTF8Text(true, ReadUInt16());
return true;
case XmlBinaryNodeType.Chars16Text:
if (_buffered)
ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt16());
else
ReadPartialUTF8Text(false, ReadUInt16());
return true;
case XmlBinaryNodeType.Chars32TextWithEndElement:
if (_buffered)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt31());
else
ReadPartialUTF8Text(true, ReadUInt31());
return true;
case XmlBinaryNodeType.Chars32Text:
if (_buffered)
ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt31());
else
ReadPartialUTF8Text(false, ReadUInt31());
return true;
case XmlBinaryNodeType.UnicodeChars8TextWithEndElement:
ReadUnicodeText(true, ReadUInt8());
return true;
case XmlBinaryNodeType.UnicodeChars8Text:
ReadUnicodeText(false, ReadUInt8());
return true;
case XmlBinaryNodeType.UnicodeChars16TextWithEndElement:
ReadUnicodeText(true, ReadUInt16());
return true;
case XmlBinaryNodeType.UnicodeChars16Text:
ReadUnicodeText(false, ReadUInt16());
return true;
case XmlBinaryNodeType.UnicodeChars32TextWithEndElement:
ReadUnicodeText(true, ReadUInt31());
return true;
case XmlBinaryNodeType.UnicodeChars32Text:
ReadUnicodeText(false, ReadUInt31());
return true;
case XmlBinaryNodeType.Bytes8TextWithEndElement:
if (_buffered)
ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt8());
else
ReadPartialBinaryText(true, ReadUInt8());
return true;
case XmlBinaryNodeType.Bytes8Text:
if (_buffered)
ReadBinaryText(MoveToComplexText(), ReadUInt8());
else
ReadPartialBinaryText(false, ReadUInt8());
return true;
case XmlBinaryNodeType.Bytes16TextWithEndElement:
if (_buffered)
ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt16());
else
ReadPartialBinaryText(true, ReadUInt16());
return true;
case XmlBinaryNodeType.Bytes16Text:
if (_buffered)
ReadBinaryText(MoveToComplexText(), ReadUInt16());
else
ReadPartialBinaryText(false, ReadUInt16());
return true;
case XmlBinaryNodeType.Bytes32TextWithEndElement:
if (_buffered)
ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt31());
else
ReadPartialBinaryText(true, ReadUInt31());
return true;
case XmlBinaryNodeType.Bytes32Text:
if (_buffered)
ReadBinaryText(MoveToComplexText(), ReadUInt31());
else
ReadPartialBinaryText(false, ReadUInt31());
return true;
case XmlBinaryNodeType.DictionaryTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetDictionaryValue(ReadDictionaryKey());
return true;
case XmlBinaryNodeType.UniqueIdTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UniqueId, ValueHandleLength.UniqueId);
return true;
case XmlBinaryNodeType.GuidTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Guid, ValueHandleLength.Guid);
return true;
case XmlBinaryNodeType.DecimalTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Decimal, ValueHandleLength.Decimal);
return true;
case XmlBinaryNodeType.Int8TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int8, ValueHandleLength.Int8);
return true;
case XmlBinaryNodeType.Int16TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int16, ValueHandleLength.Int16);
return true;
case XmlBinaryNodeType.Int32TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int32, ValueHandleLength.Int32);
return true;
case XmlBinaryNodeType.Int64TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int64, ValueHandleLength.Int64);
return true;
case XmlBinaryNodeType.UInt64TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UInt64, ValueHandleLength.UInt64);
return true;
case XmlBinaryNodeType.FloatTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Single, ValueHandleLength.Single);
return true;
case XmlBinaryNodeType.DoubleTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Double, ValueHandleLength.Double);
return true;
case XmlBinaryNodeType.TimeSpanTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.TimeSpan, ValueHandleLength.TimeSpan);
return true;
case XmlBinaryNodeType.DateTimeTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.DateTime, ValueHandleLength.DateTime);
return true;
case XmlBinaryNodeType.QNameDictionaryTextWithEndElement:
BufferReader.ReadQName(MoveToAtomicTextWithEndElement().Value);
return true;
case XmlBinaryNodeType.Array:
ReadArray();
return true;
default:
BufferReader.ReadValue(nodeType, MoveToComplexText().Value);
return true;
}
}
private void VerifyWhitespace()
{
if (!this.Node.Value.IsWhitespace())
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
}
private void ReadAttributes()
{
XmlBinaryNodeType nodeType = GetNodeType();
if (nodeType < XmlBinaryNodeType.MinAttribute || nodeType > XmlBinaryNodeType.MaxAttribute)
return;
ReadAttributes2();
}
private void ReadAttributes2()
{
int startOffset = 0;
if (_buffered)
startOffset = BufferReader.Offset;
while (true)
{
XmlAttributeNode attributeNode;
Namespace nameSpace;
PrefixHandleType prefix;
XmlBinaryNodeType nodeType = GetNodeType();
switch (nodeType)
{
case XmlBinaryNodeType.ShortAttribute:
SkipNodeType();
attributeNode = AddAttribute();
attributeNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.Attribute:
SkipNodeType();
attributeNode = AddAttribute();
ReadName(attributeNode.Prefix);
ReadName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
FixXmlAttribute(attributeNode);
break;
case XmlBinaryNodeType.ShortDictionaryAttribute:
SkipNodeType();
attributeNode = AddAttribute();
attributeNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadDictionaryName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.DictionaryAttribute:
SkipNodeType();
attributeNode = AddAttribute();
ReadName(attributeNode.Prefix);
ReadDictionaryName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.XmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
ReadName(nameSpace.Prefix);
ReadName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.ShortXmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
nameSpace.Prefix.SetValue(PrefixHandleType.Empty);
ReadName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.ShortDictionaryXmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
nameSpace.Prefix.SetValue(PrefixHandleType.Empty);
ReadDictionaryName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.DictionaryXmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
ReadName(nameSpace.Prefix);
ReadDictionaryName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.PrefixDictionaryAttributeA:
case XmlBinaryNodeType.PrefixDictionaryAttributeB:
case XmlBinaryNodeType.PrefixDictionaryAttributeC:
case XmlBinaryNodeType.PrefixDictionaryAttributeD:
case XmlBinaryNodeType.PrefixDictionaryAttributeE:
case XmlBinaryNodeType.PrefixDictionaryAttributeF:
case XmlBinaryNodeType.PrefixDictionaryAttributeG:
case XmlBinaryNodeType.PrefixDictionaryAttributeH:
case XmlBinaryNodeType.PrefixDictionaryAttributeI:
case XmlBinaryNodeType.PrefixDictionaryAttributeJ:
case XmlBinaryNodeType.PrefixDictionaryAttributeK:
case XmlBinaryNodeType.PrefixDictionaryAttributeL:
case XmlBinaryNodeType.PrefixDictionaryAttributeM:
case XmlBinaryNodeType.PrefixDictionaryAttributeN:
case XmlBinaryNodeType.PrefixDictionaryAttributeO:
case XmlBinaryNodeType.PrefixDictionaryAttributeP:
case XmlBinaryNodeType.PrefixDictionaryAttributeQ:
case XmlBinaryNodeType.PrefixDictionaryAttributeR:
case XmlBinaryNodeType.PrefixDictionaryAttributeS:
case XmlBinaryNodeType.PrefixDictionaryAttributeT:
case XmlBinaryNodeType.PrefixDictionaryAttributeU:
case XmlBinaryNodeType.PrefixDictionaryAttributeV:
case XmlBinaryNodeType.PrefixDictionaryAttributeW:
case XmlBinaryNodeType.PrefixDictionaryAttributeX:
case XmlBinaryNodeType.PrefixDictionaryAttributeY:
case XmlBinaryNodeType.PrefixDictionaryAttributeZ:
SkipNodeType();
attributeNode = AddAttribute();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryAttributeA);
attributeNode.Prefix.SetValue(prefix);
ReadDictionaryName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.PrefixAttributeA:
case XmlBinaryNodeType.PrefixAttributeB:
case XmlBinaryNodeType.PrefixAttributeC:
case XmlBinaryNodeType.PrefixAttributeD:
case XmlBinaryNodeType.PrefixAttributeE:
case XmlBinaryNodeType.PrefixAttributeF:
case XmlBinaryNodeType.PrefixAttributeG:
case XmlBinaryNodeType.PrefixAttributeH:
case XmlBinaryNodeType.PrefixAttributeI:
case XmlBinaryNodeType.PrefixAttributeJ:
case XmlBinaryNodeType.PrefixAttributeK:
case XmlBinaryNodeType.PrefixAttributeL:
case XmlBinaryNodeType.PrefixAttributeM:
case XmlBinaryNodeType.PrefixAttributeN:
case XmlBinaryNodeType.PrefixAttributeO:
case XmlBinaryNodeType.PrefixAttributeP:
case XmlBinaryNodeType.PrefixAttributeQ:
case XmlBinaryNodeType.PrefixAttributeR:
case XmlBinaryNodeType.PrefixAttributeS:
case XmlBinaryNodeType.PrefixAttributeT:
case XmlBinaryNodeType.PrefixAttributeU:
case XmlBinaryNodeType.PrefixAttributeV:
case XmlBinaryNodeType.PrefixAttributeW:
case XmlBinaryNodeType.PrefixAttributeX:
case XmlBinaryNodeType.PrefixAttributeY:
case XmlBinaryNodeType.PrefixAttributeZ:
SkipNodeType();
attributeNode = AddAttribute();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixAttributeA);
attributeNode.Prefix.SetValue(prefix);
ReadName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
default:
ProcessAttributes();
return;
}
}
}
private void ReadText(XmlTextNode textNode, ValueHandleType type, int length)
{
int offset = BufferReader.ReadBytes(length);
textNode.Value.SetValue(type, offset, length);
if (this.OutsideRootElement)
VerifyWhitespace();
}
private void ReadBinaryText(XmlTextNode textNode, int length)
{
ReadText(textNode, ValueHandleType.Base64, length);
}
private void ReadPartialUTF8Text(bool withEndElement, int length)
{
// The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need
// to account for that.
const int maxTextNodeLength = 5;
int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0);
if (length <= maxLength)
{
if (withEndElement)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, length);
else
ReadText(MoveToComplexText(), ValueHandleType.UTF8, length);
}
else
{
// We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode
// for the split data.
int actual = Math.Max(maxLength - maxTextNodeLength, 0);
int offset = BufferReader.ReadBytes(actual);
// We need to make sure we don't split a utf8 character, so scan backwards for a
// character boundary. We'll actually always push off at least one character since
// although we find the character boundary, we don't bother to figure out if we have
// all the bytes that comprise the character.
int i;
for (i = offset + actual - 1; i >= offset; i--)
{
byte b = BufferReader.GetByte(i);
// The first byte of UTF8 character sequence has either the high bit off, or the
// two high bits set.
if ((b & 0x80) == 0 || (b & 0xC0) == 0xC0)
break;
}
// Move any split characters so we can insert the node
int byteCount = (offset + actual - i);
// Include the split characters in the count
BufferReader.Offset = BufferReader.Offset - byteCount;
actual -= byteCount;
MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, actual);
if (this.OutsideRootElement)
VerifyWhitespace();
XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Chars32TextWithEndElement : XmlBinaryNodeType.Chars32Text);
InsertNode(nodeType, length - actual);
}
}
private void ReadUnicodeText(bool withEndElement, int length)
{
if ((length & 1) != 0)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
if (_buffered)
{
if (withEndElement)
{
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length);
}
else
{
ReadText(MoveToComplexText(), ValueHandleType.Unicode, length);
}
}
else
{
ReadPartialUnicodeText(withEndElement, length);
}
}
private void ReadPartialUnicodeText(bool withEndElement, int length)
{
// The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need
// to account for that.
const int maxTextNodeLength = 5;
int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0);
if (length <= maxLength)
{
if (withEndElement)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length);
else
ReadText(MoveToComplexText(), ValueHandleType.Unicode, length);
}
else
{
// We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode
// for the split data.
int actual = Math.Max(maxLength - maxTextNodeLength, 0);
// Make sure we break on a char boundary
if ((actual & 1) != 0)
actual--;
int offset = BufferReader.ReadBytes(actual);
// We need to make sure we don't split a Unicode surrogate character
int byteCount = 0;
char ch = (char)BufferReader.GetInt16(offset + actual - sizeof(char));
// If the last char is a high surrogate char, then move back
if (ch >= 0xD800 && ch < 0xDC00)
byteCount = sizeof(char);
// Include the split characters in the count
BufferReader.Offset = BufferReader.Offset - byteCount;
actual -= byteCount;
MoveToComplexText().Value.SetValue(ValueHandleType.Unicode, offset, actual);
if (this.OutsideRootElement)
VerifyWhitespace();
XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.UnicodeChars32TextWithEndElement : XmlBinaryNodeType.UnicodeChars32Text);
InsertNode(nodeType, length - actual);
}
}
private void ReadPartialBinaryText(bool withEndElement, int length)
{
const int nodeLength = 5;
int maxBytesPerRead = Math.Max(_maxBytesPerRead - nodeLength, 0);
if (length <= maxBytesPerRead)
{
if (withEndElement)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Base64, length);
else
ReadText(MoveToComplexText(), ValueHandleType.Base64, length);
}
else
{
int actual = maxBytesPerRead;
if (actual > 3)
actual -= (actual % 3);
ReadText(MoveToComplexText(), ValueHandleType.Base64, actual);
XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Bytes32TextWithEndElement : XmlBinaryNodeType.Bytes32Text);
InsertNode(nodeType, length - actual);
}
}
private void InsertNode(XmlBinaryNodeType nodeType, int length)
{
byte[] buffer = new byte[5];
buffer[0] = (byte)nodeType;
buffer[1] = (byte)length;
length >>= 8;
buffer[2] = (byte)length;
length >>= 8;
buffer[3] = (byte)length;
length >>= 8;
buffer[4] = (byte)length;
BufferReader.InsertBytes(buffer, 0, buffer.Length);
}
private void ReadAttributeText(XmlAttributeTextNode textNode)
{
XmlBinaryNodeType nodeType = GetNodeType();
SkipNodeType();
BufferReader.ReadValue(nodeType, textNode.Value);
}
private void ReadName(ValueHandle value)
{
int length = ReadMultiByteUInt31();
int offset = BufferReader.ReadBytes(length);
value.SetValue(ValueHandleType.UTF8, offset, length);
}
private void ReadName(StringHandle handle)
{
int length = ReadMultiByteUInt31();
int offset = BufferReader.ReadBytes(length);
handle.SetValue(offset, length);
}
private void ReadName(PrefixHandle prefix)
{
int length = ReadMultiByteUInt31();
int offset = BufferReader.ReadBytes(length);
prefix.SetValue(offset, length);
}
private void ReadDictionaryName(StringHandle s)
{
int key = ReadDictionaryKey();
s.SetValue(key);
}
private XmlBinaryNodeType GetNodeType()
{
return BufferReader.GetNodeType();
}
private void SkipNodeType()
{
BufferReader.SkipNodeType();
}
private int ReadDictionaryKey()
{
return BufferReader.ReadDictionaryKey();
}
private int ReadMultiByteUInt31()
{
return BufferReader.ReadMultiByteUInt31();
}
private int ReadUInt8()
{
return BufferReader.ReadUInt8();
}
private int ReadUInt16()
{
return BufferReader.ReadUInt16();
}
private int ReadUInt31()
{
return BufferReader.ReadUInt31();
}
private bool IsValidArrayType(XmlBinaryNodeType nodeType)
{
switch (nodeType)
{
case XmlBinaryNodeType.BoolTextWithEndElement:
case XmlBinaryNodeType.Int16TextWithEndElement:
case XmlBinaryNodeType.Int32TextWithEndElement:
case XmlBinaryNodeType.Int64TextWithEndElement:
case XmlBinaryNodeType.FloatTextWithEndElement:
case XmlBinaryNodeType.DoubleTextWithEndElement:
case XmlBinaryNodeType.DecimalTextWithEndElement:
case XmlBinaryNodeType.DateTimeTextWithEndElement:
case XmlBinaryNodeType.TimeSpanTextWithEndElement:
case XmlBinaryNodeType.GuidTextWithEndElement:
return true;
default:
return false;
}
}
private void ReadArray()
{
if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
ReadNode(); // ReadStartElement
if (this.Node.NodeType != XmlNodeType.Element)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
ReadNode(); // ReadEndElement
if (this.Node.NodeType != XmlNodeType.EndElement)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
_arrayState = ArrayState.Element;
_arrayNodeType = GetNodeType();
if (!IsValidArrayType(_arrayNodeType))
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
SkipNodeType();
_arrayCount = ReadMultiByteUInt31();
if (_arrayCount == 0)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
MoveToArrayElement();
}
private void MoveToArrayElement()
{
_arrayState = ArrayState.Element;
MoveToNode(ElementNode);
}
private void SkipArrayElements(int count)
{
_arrayCount -= count;
if (_arrayCount == 0)
{
_arrayState = ArrayState.None;
ExitScope();
ReadNode();
}
}
public override bool IsStartArray(out Type type)
{
type = null;
if (_arrayState != ArrayState.Element)
return false;
switch (_arrayNodeType)
{
case XmlBinaryNodeType.BoolTextWithEndElement:
type = typeof(bool);
break;
case XmlBinaryNodeType.Int16TextWithEndElement:
type = typeof(Int16);
break;
case XmlBinaryNodeType.Int32TextWithEndElement:
type = typeof(Int32);
break;
case XmlBinaryNodeType.Int64TextWithEndElement:
type = typeof(Int64);
break;
case XmlBinaryNodeType.FloatTextWithEndElement:
type = typeof(float);
break;
case XmlBinaryNodeType.DoubleTextWithEndElement:
type = typeof(double);
break;
case XmlBinaryNodeType.DecimalTextWithEndElement:
type = typeof(decimal);
break;
case XmlBinaryNodeType.DateTimeTextWithEndElement:
type = typeof(DateTime);
break;
case XmlBinaryNodeType.GuidTextWithEndElement:
type = typeof(Guid);
break;
case XmlBinaryNodeType.TimeSpanTextWithEndElement:
type = typeof(TimeSpan);
break;
case XmlBinaryNodeType.UniqueIdTextWithEndElement:
type = typeof(UniqueId);
break;
default:
return false;
}
return true;
}
public override bool TryGetArrayLength(out int count)
{
count = 0;
if (!_buffered)
return false;
if (_arrayState != ArrayState.Element)
return false;
count = _arrayCount;
return true;
}
private bool IsStartArray(string localName, string namespaceUri, XmlBinaryNodeType nodeType)
{
return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType;
}
private bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, XmlBinaryNodeType nodeType)
{
return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType;
}
private void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
// bool
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (bool* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// Int16
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(Int16[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (Int16* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, Int16[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// Int32
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(Int32[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (Int32* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, Int32[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// Int64
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(Int64[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (Int64* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, Int64[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// float
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(float[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (float* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// double
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(double[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (double* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// decimal
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (decimal* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// DateTime
private int ReadArray(DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
for (int i = 0; i < actual; i++)
{
array[offset + i] = BufferReader.ReadDateTime();
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// Guid
private int ReadArray(Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
for (int i = 0; i < actual; i++)
{
array[offset + i] = BufferReader.ReadGuid();
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// TimeSpan
private int ReadArray(TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
for (int i = 0; i < actual; i++)
{
array[offset + i] = BufferReader.ReadTimeSpan();
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
private enum ArrayState
{
None,
Element,
Content
}
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Collections;
using Thrift.Protocols;
using Thrift.Server;
using Thrift.Transports;
using Thrift.Transports.Server;
namespace ThriftTest
{
internal class ServerParam
{
internal bool useBufferedSockets = false;
internal bool useFramed = false;
internal bool useEncryption = false;
internal bool compact = false;
internal bool json = false;
internal int port = 9090;
internal string pipe = null;
internal void Parse(List<string> args)
{
for (var i = 0; i < args.Count; i++)
{
if (args[i].StartsWith("--pipe="))
{
pipe = args[i].Substring(args[i].IndexOf("=") + 1);
}
else if (args[i].StartsWith("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
useBufferedSockets = true;
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
useFramed = true;
}
else if (args[i] == "--binary" || args[i] == "--protocol=binary")
{
// nothing needed
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
compact = true;
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
json = true;
}
else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--ssl")
{
useEncryption = true;
}
else
{
//throw new ArgumentException(args[i]);
}
}
}
}
public class TestServer
{
public static int _clientID = -1;
public delegate void TestLogDelegate(string msg, params object[] values);
public class MyServerEventHandler : TServerEventHandler
{
public int callCount = 0;
public Task PreServeAsync(CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
public Task<object> CreateContextAsync(TProtocol input, TProtocol output, CancellationToken cancellationToken)
{
callCount++;
return Task.FromResult<object>(null);
}
public Task DeleteContextAsync(object serverContext, TProtocol input, TProtocol output, CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
public Task ProcessContextAsync(object serverContext, TClientTransport transport, CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
}
public class TestHandlerAsync : ThriftTest.IAsync
{
public TBaseServer server { get; set; }
private int handlerID;
private StringBuilder sb = new StringBuilder();
private TestLogDelegate logger;
public TestHandlerAsync()
{
handlerID = Interlocked.Increment(ref _clientID);
logger += testConsoleLogger;
logger.Invoke("New TestHandler instance created");
}
public void testConsoleLogger(string msg, params object[] values)
{
sb.Clear();
sb.AppendFormat("handler{0:D3}:", handlerID);
sb.AppendFormat(msg, values);
sb.AppendLine();
Console.Write(sb.ToString());
}
public Task testVoidAsync(CancellationToken cancellationToken)
{
logger.Invoke("testVoid()");
return Task.CompletedTask;
}
public Task<string> testStringAsync(string thing, CancellationToken cancellationToken)
{
logger.Invoke("testString({0})", thing);
return Task.FromResult(thing);
}
public Task<bool> testBoolAsync(bool thing, CancellationToken cancellationToken)
{
logger.Invoke("testBool({0})", thing);
return Task.FromResult(thing);
}
public Task<sbyte> testByteAsync(sbyte thing, CancellationToken cancellationToken)
{
logger.Invoke("testByte({0})", thing);
return Task.FromResult(thing);
}
public Task<int> testI32Async(int thing, CancellationToken cancellationToken)
{
logger.Invoke("testI32({0})", thing);
return Task.FromResult(thing);
}
public Task<long> testI64Async(long thing, CancellationToken cancellationToken)
{
logger.Invoke("testI64({0})", thing);
return Task.FromResult(thing);
}
public Task<double> testDoubleAsync(double thing, CancellationToken cancellationToken)
{
logger.Invoke("testDouble({0})", thing);
return Task.FromResult(thing);
}
public Task<byte[]> testBinaryAsync(byte[] thing, CancellationToken cancellationToken)
{
var hex = BitConverter.ToString(thing).Replace("-", string.Empty);
logger.Invoke("testBinary({0:X})", hex);
return Task.FromResult(thing);
}
public Task<Xtruct> testStructAsync(Xtruct thing, CancellationToken cancellationToken)
{
logger.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.String_thing, thing.Byte_thing, thing.I32_thing, thing.I64_thing);
return Task.FromResult(thing);
}
public Task<Xtruct2> testNestAsync(Xtruct2 nest, CancellationToken cancellationToken)
{
var thing = nest.Struct_thing;
logger.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})",
nest.Byte_thing,
thing.String_thing,
thing.Byte_thing,
thing.I32_thing,
thing.I64_thing,
nest.I32_thing);
return Task.FromResult(nest);
}
public Task<Dictionary<int, int>> testMapAsync(Dictionary<int, int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testMap({{");
var first = true;
foreach (var key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0} => {1}", key, thing[key]);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<Dictionary<string, string>> testStringMapAsync(Dictionary<string, string> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testStringMap({{");
var first = true;
foreach (var key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0} => {1}", key, thing[key]);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<THashSet<int>> testSetAsync(THashSet<int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testSet({{");
var first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0}", elem);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<List<int>> testListAsync(List<int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testList({{");
var first = true;
foreach (var elem in thing)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0}", elem);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<Numberz> testEnumAsync(Numberz thing, CancellationToken cancellationToken)
{
logger.Invoke("testEnum({0})", thing);
return Task.FromResult(thing);
}
public Task<long> testTypedefAsync(long thing, CancellationToken cancellationToken)
{
logger.Invoke("testTypedef({0})", thing);
return Task.FromResult(thing);
}
public Task<Dictionary<int, Dictionary<int, int>>> testMapMapAsync(int hello, CancellationToken cancellationToken)
{
logger.Invoke("testMapMap({0})", hello);
var mapmap = new Dictionary<int, Dictionary<int, int>>();
var pos = new Dictionary<int, int>();
var neg = new Dictionary<int, int>();
for (var i = 1; i < 5; i++)
{
pos[i] = i;
neg[-i] = -i;
}
mapmap[4] = pos;
mapmap[-4] = neg;
return Task.FromResult(mapmap);
}
public Task<Dictionary<long, Dictionary<Numberz, Insanity>>> testInsanityAsync(Insanity argument, CancellationToken cancellationToken)
{
logger.Invoke("testInsanity()");
/** from ThriftTest.thrift:
* So you think you've got this all worked, out eh?
*
* Creates a the returned map with these values and prints it out:
* { 1 => { 2 => argument,
* 3 => argument,
* },
* 2 => { 6 => <empty Insanity struct>, },
* }
* @return map<UserId, map<Numberz,Insanity>> - a map with the above values
*/
var first_map = new Dictionary<Numberz, Insanity>();
var second_map = new Dictionary<Numberz, Insanity>(); ;
first_map[Numberz.TWO] = argument;
first_map[Numberz.THREE] = argument;
second_map[Numberz.SIX] = new Insanity();
var insane = new Dictionary<long, Dictionary<Numberz, Insanity>>
{
[1] = first_map,
[2] = second_map
};
return Task.FromResult(insane);
}
public Task<Xtruct> testMultiAsync(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5,
CancellationToken cancellationToken)
{
logger.Invoke("testMulti()");
var hello = new Xtruct(); ;
hello.String_thing = "Hello2";
hello.Byte_thing = arg0;
hello.I32_thing = arg1;
hello.I64_thing = arg2;
return Task.FromResult(hello);
}
public Task testExceptionAsync(string arg, CancellationToken cancellationToken)
{
logger.Invoke("testException({0})", arg);
if (arg == "Xception")
{
var x = new Xception
{
ErrorCode = 1001,
Message = arg
};
throw x;
}
if (arg == "TException")
{
throw new TException();
}
return Task.CompletedTask;
}
public Task<Xtruct> testMultiExceptionAsync(string arg0, string arg1, CancellationToken cancellationToken)
{
logger.Invoke("testMultiException({0}, {1})", arg0, arg1);
if (arg0 == "Xception")
{
var x = new Xception
{
ErrorCode = 1001,
Message = "This is an Xception"
};
throw x;
}
if (arg0 == "Xception2")
{
var x = new Xception2
{
ErrorCode = 2002,
Struct_thing = new Xtruct { String_thing = "This is an Xception2" }
};
throw x;
}
var result = new Xtruct { String_thing = arg1 };
return Task.FromResult(result);
}
public Task testOnewayAsync(int secondsToSleep, CancellationToken cancellationToken)
{
logger.Invoke("testOneway({0}), sleeping...", secondsToSleep);
Task.Delay(secondsToSleep * 1000, cancellationToken).GetAwaiter().GetResult();
logger.Invoke("testOneway finished");
return Task.CompletedTask;
}
}
internal static void PrintOptionsHelp()
{
Console.WriteLine("Server options:");
Console.WriteLine(" --pipe=<pipe name>");
Console.WriteLine(" --port=<port number>");
Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
Console.WriteLine(" --server-type=<type> one of threaded,threadpool (defaults to simple)");
Console.WriteLine(" --processor=<prototype>");
Console.WriteLine(" --ssl");
Console.WriteLine();
}
private static X509Certificate2 GetServerCert()
{
var serverCertName = "server.p12";
var possiblePaths = new List<string>
{
"../../../keys/",
"../../keys/",
"../keys/",
"keys/",
};
string existingPath = null;
foreach (var possiblePath in possiblePaths)
{
var path = Path.GetFullPath(possiblePath + serverCertName);
if (File.Exists(path))
{
existingPath = path;
break;
}
}
if (string.IsNullOrEmpty(existingPath))
{
throw new FileNotFoundException($"Cannot find file: {serverCertName}");
}
var cert = new X509Certificate2(existingPath, "thrift");
return cert;
}
public static int Execute(List<string> args)
{
var loggerFactory = new LoggerFactory();//.AddConsole().AddDebug();
var logger = new LoggerFactory().CreateLogger("Test");
try
{
var param = new ServerParam();
try
{
param.Parse(args);
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Error while parsing arguments");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
return 1;
}
// Transport
TServerTransport trans;
if (param.pipe != null)
{
trans = new TNamedPipeServerTransport(param.pipe);
}
// else if (param.useFramed)
// {
// trans = new TServerFramedTransport(param.port);
// }
else
{
if (param.useEncryption)
{
var cert = GetServerCert();
if (cert == null || !cert.HasPrivateKey)
{
throw new InvalidOperationException("Certificate doesn't contain private key");
}
trans = new TTlsServerSocketTransport(param.port, param.useBufferedSockets, param.useFramed, cert,
(sender, certificate, chain, errors) => true,
null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
}
else
{
trans = new TServerSocketTransport(param.port, 0, param.useBufferedSockets, param.useFramed);
}
}
ITProtocolFactory proto;
if (param.compact)
proto = new TCompactProtocol.Factory();
else if (param.json)
proto = new TJsonProtocol.Factory();
else
proto = new TBinaryProtocol.Factory();
ITProcessorFactory processorFactory;
// Processor
var testHandler = new TestHandlerAsync();
var testProcessor = new ThriftTest.AsyncProcessor(testHandler);
processorFactory = new SingletonTProcessorFactory(testProcessor);
TTransportFactory transFactory = new TTransportFactory();
TBaseServer serverEngine = new AsyncBaseServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger);
//Server event handler
var serverEvents = new MyServerEventHandler();
serverEngine.SetEventHandler(serverEvents);
// Run it
var where = (! string.IsNullOrEmpty(param.pipe)) ? "on pipe " + param.pipe : "on port " + param.port;
Console.WriteLine("Starting the AsyncBaseServer " + where +
" with processor TPrototypeProcessorFactory prototype factory " +
(param.useBufferedSockets ? " with buffered socket" : "") +
(param.useFramed ? " with framed transport" : "") +
(param.useEncryption ? " with encryption" : "") +
(param.compact ? " with compact protocol" : "") +
(param.json ? " with json protocol" : "") +
"...");
serverEngine.ServeAsync(CancellationToken.None).GetAwaiter().GetResult();
Console.ReadLine();
}
catch (Exception x)
{
Console.Error.Write(x);
return 1;
}
Console.WriteLine("done.");
return 0;
}
}
}
| |
//
// AmpachePlayerFixture.cs
//
// Author:
// John Moore <jcwmoore@gmail.com>
//
// Copyright (c) 2012 John Moore
//
// 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 NUnit.Framework;
using System;
using System.Linq;
using System.Collections.Generic;
using JohnMoore.AmpacheNet.Logic;
using JohnMoore.AmpacheNet.Entities;
using JohnMoore.AmpacheNet.DataAccess;
using System.IO;
using NSubstitute;
namespace JohnMoore.AmpacheNet.Logic.Tests
{
[TestFixture()]
public class BackgroundFixture
{
[Test()]
public void BackgroundStartInitializesModelConfigurationTest ()
{
var container = new Athena.IoC.Container();
var persister = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(persister);
persister.SelectBy(Arg.Any<int>()).Returns(new UserConfiguration { ServerUrl = string.Empty });
var target = new BackgroundHandle(null, null, new AmpacheModel(), container);
var initial = target.Model;
target.Start(new MemoryStream());
var after = target.Model.Configuration;
Assert.That(after, Is.Not.Null);
}
[Test()]
[ExpectedException(typeof(ArgumentNullException))]
public void BackgroundStartFailsWithNullParameterTest ()
{
var target = new BackgroundHandle(null, null);
target.Start(null);
Assert.Fail();
}
[Test()]
public void BackgroundStartPopulatesArtLoaderTest ()
{
var container = new Athena.IoC.Container();
string path = "myartpath";
var persister = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(persister);
persister.SelectBy(Arg.Any<int>()).Returns(new UserConfiguration { ServerUrl = string.Empty });
var target = new BackgroundHandle(null, path, new AmpacheModel(), container);
target.Start(new MemoryStream());
var exp = target.Loader;
Assert.That(exp, Is.Not.Null);
}
// TODO: replace the factory
[Test()]
public void BackgroundStartPopulatesModelFactoryWhenNoUserConfigExistsTest ()
{
var container = new Athena.IoC.Container();
string path = "myartpath";
var persister = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(persister);
persister.SelectBy(Arg.Any<int>()).Returns(new UserConfiguration { ServerUrl = string.Empty });
var target = new BackgroundHandle(null, path, new AmpacheModel(), container);
target.Start(new MemoryStream());
var exp = target.Model.Factory;
Assert.That(exp, Is.Not.Null);
}
[Test()]
public void BackgroundStartBeginsAutoShutOffTest ()
{
var container = new Athena.IoC.Container();
string path = "myartpath";
var persister = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(persister);
persister.SelectBy(Arg.Any<int>()).Returns(new UserConfiguration { ServerUrl = string.Empty });
var target = new BackgroundHandle(null, path, new AmpacheModel(), container);
target.Start(new MemoryStream());
Assert.That(target.AutoShutOffCallCount, Is.EqualTo(1));
}
[Test()]
public void BackgroundStartPopulatesModelFactoryWhenUserConfigExistsTest ()
{
var container = new Athena.IoC.Container();
string path = "myartpath";
var config = new UserConfiguration();
config.ServerUrl = "test";
config.User = "test";
config.Password = "test";
var persister = Substitute.For<IPersister<AmpacheSong>>();
container.Register<IPersister<AmpacheSong>>().To(persister);
var configpersist = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(configpersist);
configpersist.SelectBy(Arg.Any<int>()).Returns(config);
var sngs = new List<AmpacheSong>();
sngs.Add(new AmpacheSong(){Url = "http://test"});
sngs.Add(new AmpacheSong(){Url = "http://test"});
persister.SelectAll().Returns(sngs);
var factory = Substitute.For<AmpacheSelectionFactory>();
factory.AuthenticateToServer(config).Returns(x => (Authenticate)null);
var mockHs = new MockHandShake();
mockHs.Setup("test", "test");
factory.Handshake.Returns(mockHs);
var target = new BackgroundHandle(config, path, factory, new AmpacheModel(), container);
target.Start(new MemoryStream());
System.Threading.Thread.Sleep(100);
var exp = target.Model.Factory;
Assert.That(exp, Is.Not.Null);
var userMessage = target.Model.UserMessage;
Assert.That(userMessage, Is.Not.Null);
Assert.That(userMessage, Is.EqualTo(BackgroundHandle.SUCCESS_MESSAGE));
Assert.That(target.Model.Playlist, Is.EquivalentTo(sngs));
}
[Test()]
public void BackgroundStartPopulatesModelPlaylistWhenUserConfigExistsTest ()
{
var container = new Athena.IoC.Container();
string path = "myartpath";
var config = new UserConfiguration();
config.ServerUrl = "test";
config.User = "test";
config.Password = "test";
var persister = Substitute.For<IPersister<UserConfiguration>>();
persister.SelectBy(Arg.Any<int>()).Returns(config);
container.Register<IPersister<UserConfiguration>>().To(persister);
var factory = Substitute.For<AmpacheSelectionFactory>();
factory.AuthenticateToServer(config).Returns(x => (Authenticate)null);
container.Register<IPersister<UserConfiguration>>();
var target = new BackgroundHandle(config, path, factory, new AmpacheModel(), container);
target.Start(new MemoryStream());
var exp = target.Model.Playlist;
Assert.That(exp, Is.Not.Null);
}
[Test()]
public void BackgroundListensForModelDispositionTest ()
{
var container = new Athena.IoC.Container();
string path = "myartpath";
var persister = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(persister);
persister.SelectBy(Arg.Any<int>()).Returns(new UserConfiguration { ServerUrl = string.Empty });
var target = new BackgroundHandle(null, path, null, new AmpacheModel(), container);
target.Start(new MemoryStream());
target.Model.Dispose();
Assert.That(target.FinalizedCalled, Is.True);
}
[Test()]
public void BackgroundListensForConfigChangesTest ()
{
var container = new Athena.IoC.Container();
string path = "myartpath";
var persister = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(persister);
bool persisted = false;
var config = new UserConfiguration();
persister.When(x => x.Persist(config)).Do(p => persisted = true);
var target = new BackgroundHandle(null, path, new AmpacheModel(), container);
target.Start(new MemoryStream());
System.Threading.Thread.Sleep(100);
target.Model.Configuration = config;
Assert.That(persisted, Is.True);
}
[Test()]
public void BackgroundListensForPlaylistChangesTest ()
{
var container = new Athena.IoC.Container();
var persister = Substitute.For<IPersister<AmpacheSong>>();
var sng = new AmpacheSong();
container.Register<IPersister<AmpacheSong>>().To(persister);
var usrp = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(usrp);
bool persisted = false;
persister.When(p => p.Persist(sng)).Do(p => persisted = true);
string path = "myartpath";
var target = new BackgroundHandle(null, path, new AmpacheModel(), container);
target.Start(new MemoryStream());
System.Threading.Thread.Sleep(100);
var sngs = new List<AmpacheSong>();
sngs.Add(sng);
target.Model.Playlist = sngs;
Assert.That(persisted, Is.True);
}
[Test()]
public void BackgroundListensForPlayingChangesAndCancelsShutOffTest ()
{
var container = new Athena.IoC.Container();
string path = "myartpath";
var persister = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(persister);
persister.SelectBy(Arg.Any<int>()).Returns(new UserConfiguration { ServerUrl = string.Empty });
var target = new BackgroundHandle(null, path, new AmpacheModel(), container);
target.Start(new MemoryStream());
System.Threading.Thread.Sleep(100);
target.Model.IsPlaying = true;
Assert.That(target.StopShutOffCallCount, Is.EqualTo(1));
}
[Test()]
public void BackgroundListensForPlayingChangesAndStartsShutOffTest ()
{
var container = new Athena.IoC.Container();
string path = "myartpath";
var persister = Substitute.For<IPersister<UserConfiguration>>();
container.Register<IPersister<UserConfiguration>>().To(persister);
persister.SelectBy(Arg.Any<int>()).Returns(new UserConfiguration { ServerUrl = string.Empty });
var target = new BackgroundHandle(null, path, new AmpacheModel(), container);
target.Start(new MemoryStream());
System.Threading.Thread.Sleep(100);
target.Model.IsPlaying = true;
Assert.That(target.StopShutOffCallCount, Is.EqualTo(1));
target.Model.IsPlaying = false;
Assert.That(target.AutoShutOffCallCount, Is.EqualTo(2));
}
private class MockHandShake : Handshake
{
public void Setup (string test, string test2)
{
Passphrase = test;
Server = test2;
}
}
private class BackgroundHandle : Background
{
private readonly UserConfiguration _config;
private readonly AmpacheSelectionFactory _factory;
public const string SUCCESS_MESSAGE = "success";
public bool FinalizedCalled { get; private set;}
public bool SavedSongsCalled { get; private set;}
public bool LoadSongsCalled { get; private set;}
public int AutoShutOffCallCount { get; private set; }
public int StopShutOffCallCount { get; private set; }
public BackgroundHandle (UserConfiguration config, string art)
{
_successConnectionMessage = SUCCESS_MESSAGE;
_config = config;
FinalizedCalled = false;
SavedSongsCalled = false;
LoadSongsCalled = false;
AutoShutOffCallCount = 0;
StopShutOffCallCount = 0;
}
public BackgroundHandle(UserConfiguration config, string art, AmpacheModel model, Athena.IoC.Container container)
: this(config, art)
{
_model = model;
_container = container;
}
public BackgroundHandle(UserConfiguration config, string art, AmpacheSelectionFactory factory, AmpacheModel model, Athena.IoC.Container container)
: this(config, art, model, container)
{
_factory = factory;
}
public AmpacheModel Model { get { return _model; } }
public AlbumArtLoader Loader { get { return _loader; } }
public override AmpacheSelectionFactory CreateFactory ()
{
return _factory ?? base.CreateFactory();
}
public override void PlatformFinalize ()
{
FinalizedCalled = true;
}
public override void StartAutoShutOff ()
{
++AutoShutOffCallCount;
}
public override void StopAutoShutOff ()
{
++StopShutOffCallCount;
}
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Kisa;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Ntt;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Security
{
/// <remarks>
/// Cipher Utility class contains methods that can not be specifically grouped into other classes.
/// </remarks>
public sealed class CipherUtilities
{
private enum CipherAlgorithm {
AES,
ARC4,
BLOWFISH,
CAMELLIA,
CAST5,
CAST6,
DES,
DESEDE,
ELGAMAL,
GOST28147,
HC128,
HC256,
IDEA,
NOEKEON,
PBEWITHSHAAND128BITRC4,
PBEWITHSHAAND40BITRC4,
RC2,
RC5,
RC5_64,
RC6,
RIJNDAEL,
RSA,
SALSA20,
SEED,
SERPENT,
SKIPJACK,
TEA,
TWOFISH,
VMPC,
VMPC_KSA3,
XTEA,
};
private enum CipherMode { ECB, NONE, CBC, CCM, CFB, CTR, CTS, EAX, GCM, GOFB, OFB, OPENPGPCFB, SIC };
private enum CipherPadding
{
NOPADDING,
RAW,
ISO10126PADDING,
ISO10126D2PADDING,
ISO10126_2PADDING,
ISO7816_4PADDING,
ISO9797_1PADDING,
ISO9796_1,
ISO9796_1PADDING,
OAEP,
OAEPPADDING,
OAEPWITHMD5ANDMGF1PADDING,
OAEPWITHSHA1ANDMGF1PADDING,
OAEPWITHSHA_1ANDMGF1PADDING,
OAEPWITHSHA224ANDMGF1PADDING,
OAEPWITHSHA_224ANDMGF1PADDING,
OAEPWITHSHA256ANDMGF1PADDING,
OAEPWITHSHA_256ANDMGF1PADDING,
OAEPWITHSHA384ANDMGF1PADDING,
OAEPWITHSHA_384ANDMGF1PADDING,
OAEPWITHSHA512ANDMGF1PADDING,
OAEPWITHSHA_512ANDMGF1PADDING,
PKCS1,
PKCS1PADDING,
PKCS5,
PKCS5PADDING,
PKCS7,
PKCS7PADDING,
TBCPADDING,
WITHCTS,
X923PADDING,
ZEROBYTEPADDING,
};
private static readonly IDictionary algorithms = Platform.CreateHashtable();
private static readonly IDictionary oids = Platform.CreateHashtable();
static CipherUtilities()
{
// Signal to obfuscation tools not to change enum constants
((CipherAlgorithm)Enums.GetArbitraryValue(typeof(CipherAlgorithm))).ToString();
((CipherMode)Enums.GetArbitraryValue(typeof(CipherMode))).ToString();
((CipherPadding)Enums.GetArbitraryValue(typeof(CipherPadding))).ToString();
// TODO Flesh out the list of aliases
algorithms[NistObjectIdentifiers.IdAes128Ecb.Id] = "AES/ECB/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes192Ecb.Id] = "AES/ECB/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes256Ecb.Id] = "AES/ECB/PKCS7PADDING";
algorithms["AES//PKCS7"] = "AES/ECB/PKCS7PADDING";
algorithms["AES//PKCS7PADDING"] = "AES/ECB/PKCS7PADDING";
algorithms["AES//PKCS5"] = "AES/ECB/PKCS7PADDING";
algorithms["AES//PKCS5PADDING"] = "AES/ECB/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes128Cbc.Id] = "AES/CBC/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes192Cbc.Id] = "AES/CBC/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes256Cbc.Id] = "AES/CBC/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes128Ofb.Id] = "AES/OFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes192Ofb.Id] = "AES/OFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes256Ofb.Id] = "AES/OFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes128Cfb.Id] = "AES/CFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes192Cfb.Id] = "AES/CFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes256Cfb.Id] = "AES/CFB/NOPADDING";
algorithms["RSA/ECB/PKCS1"] = "RSA//PKCS1PADDING";
algorithms["RSA/ECB/PKCS1PADDING"] = "RSA//PKCS1PADDING";
algorithms[PkcsObjectIdentifiers.RsaEncryption.Id] = "RSA//PKCS1PADDING";
algorithms[PkcsObjectIdentifiers.IdRsaesOaep.Id] = "RSA//OAEPPADDING";
algorithms[OiwObjectIdentifiers.DesCbc.Id] = "DES/CBC";
algorithms[OiwObjectIdentifiers.DesCfb.Id] = "DES/CFB";
algorithms[OiwObjectIdentifiers.DesEcb.Id] = "DES/ECB";
algorithms[OiwObjectIdentifiers.DesOfb.Id] = "DES/OFB";
algorithms[OiwObjectIdentifiers.DesEde.Id] = "DESEDE";
algorithms[PkcsObjectIdentifiers.DesEde3Cbc.Id] = "DESEDE/CBC";
algorithms[PkcsObjectIdentifiers.RC2Cbc.Id] = "RC2/CBC";
algorithms["1.3.6.1.4.1.188.7.1.1.2"] = "IDEA/CBC";
algorithms["1.2.840.113533.7.66.10"] = "CAST5/CBC";
algorithms["RC4"] = "ARC4";
algorithms["ARCFOUR"] = "ARC4";
algorithms["1.2.840.113549.3.4"] = "ARC4";
algorithms["PBEWITHSHA1AND128BITRC4"] = "PBEWITHSHAAND128BITRC4";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd128BitRC4.Id] = "PBEWITHSHAAND128BITRC4";
algorithms["PBEWITHSHA1AND40BITRC4"] = "PBEWITHSHAAND40BITRC4";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd40BitRC4.Id] = "PBEWITHSHAAND40BITRC4";
algorithms["PBEWITHSHA1ANDDES"] = "PBEWITHSHA1ANDDES-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithSha1AndDesCbc.Id] = "PBEWITHSHA1ANDDES-CBC";
algorithms["PBEWITHSHA1ANDRC2"] = "PBEWITHSHA1ANDRC2-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithSha1AndRC2Cbc.Id] = "PBEWITHSHA1ANDRC2-CBC";
algorithms["PBEWITHSHA1AND3-KEYTRIPLEDES-CBC"] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
algorithms["PBEWITHSHAAND3KEYTRIPLEDES"] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc.Id] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
algorithms["PBEWITHSHA1ANDDESEDE"] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
algorithms["PBEWITHSHA1AND2-KEYTRIPLEDES-CBC"] = "PBEWITHSHAAND2-KEYTRIPLEDES-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd2KeyTripleDesCbc.Id] = "PBEWITHSHAAND2-KEYTRIPLEDES-CBC";
algorithms["PBEWITHSHA1AND128BITRC2-CBC"] = "PBEWITHSHAAND128BITRC2-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd128BitRC2Cbc.Id] = "PBEWITHSHAAND128BITRC2-CBC";
algorithms["PBEWITHSHA1AND40BITRC2-CBC"] = "PBEWITHSHAAND40BITRC2-CBC";
algorithms[PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc.Id] = "PBEWITHSHAAND40BITRC2-CBC";
algorithms["PBEWITHSHA1AND128BITAES-CBC-BC"] = "PBEWITHSHAAND128BITAES-CBC-BC";
algorithms["PBEWITHSHA-1AND128BITAES-CBC-BC"] = "PBEWITHSHAAND128BITAES-CBC-BC";
algorithms["PBEWITHSHA1AND192BITAES-CBC-BC"] = "PBEWITHSHAAND192BITAES-CBC-BC";
algorithms["PBEWITHSHA-1AND192BITAES-CBC-BC"] = "PBEWITHSHAAND192BITAES-CBC-BC";
algorithms["PBEWITHSHA1AND256BITAES-CBC-BC"] = "PBEWITHSHAAND256BITAES-CBC-BC";
algorithms["PBEWITHSHA-1AND256BITAES-CBC-BC"] = "PBEWITHSHAAND256BITAES-CBC-BC";
algorithms["PBEWITHSHA-256AND128BITAES-CBC-BC"] = "PBEWITHSHA256AND128BITAES-CBC-BC";
algorithms["PBEWITHSHA-256AND192BITAES-CBC-BC"] = "PBEWITHSHA256AND192BITAES-CBC-BC";
algorithms["PBEWITHSHA-256AND256BITAES-CBC-BC"] = "PBEWITHSHA256AND256BITAES-CBC-BC";
algorithms["GOST"] = "GOST28147";
algorithms["GOST-28147"] = "GOST28147";
algorithms[CryptoProObjectIdentifiers.GostR28147Cbc.Id] = "GOST28147/CBC/PKCS7PADDING";
algorithms["RC5-32"] = "RC5";
algorithms[NttObjectIdentifiers.IdCamellia128Cbc.Id] = "CAMELLIA/CBC/PKCS7PADDING";
algorithms[NttObjectIdentifiers.IdCamellia192Cbc.Id] = "CAMELLIA/CBC/PKCS7PADDING";
algorithms[NttObjectIdentifiers.IdCamellia256Cbc.Id] = "CAMELLIA/CBC/PKCS7PADDING";
algorithms[KisaObjectIdentifiers.IdSeedCbc.Id] = "SEED/CBC/PKCS7PADDING";
algorithms["1.3.6.1.4.1.3029.1.2"] = "BLOWFISH/CBC";
}
private CipherUtilities()
{
}
/// <summary>
/// Returns a ObjectIdentifier for a give encoding.
/// </summary>
/// <param name="mechanism">A string representation of the encoding.</param>
/// <returns>A DerObjectIdentifier, null if the Oid is not available.</returns>
// TODO Don't really want to support this
public static DerObjectIdentifier GetObjectIdentifier(
string mechanism)
{
if (mechanism == null)
throw new ArgumentNullException("mechanism");
mechanism = mechanism.ToUpper(CultureInfo.InvariantCulture);
string aliased = (string) algorithms[mechanism];
if (aliased != null)
mechanism = aliased;
return (DerObjectIdentifier) oids[mechanism];
}
public static ICollection Algorithms
{
get { return oids.Keys; }
}
public static IBufferedCipher GetCipher(
DerObjectIdentifier oid)
{
return GetCipher(oid.Id);
}
public static IBufferedCipher GetCipher(
string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
algorithm = algorithm.ToUpper(CultureInfo.InvariantCulture);
string aliased = (string) algorithms[algorithm];
if (aliased != null)
algorithm = aliased;
IBasicAgreement iesAgreement = null;
if (algorithm == "IES")
{
iesAgreement = new DHBasicAgreement();
}
else if (algorithm == "ECIES")
{
iesAgreement = new ECDHBasicAgreement();
}
if (iesAgreement != null)
{
return new BufferedIesCipher(
new IesEngine(
iesAgreement,
new Kdf2BytesGenerator(
new Sha1Digest()),
new HMac(
new Sha1Digest())));
}
if (algorithm.StartsWith("PBE"))
{
if (algorithm.EndsWith("-CBC"))
{
if (algorithm == "PBEWITHSHA1ANDDES-CBC")
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new DesEngine()));
}
else if (algorithm == "PBEWITHSHA1ANDRC2-CBC")
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new RC2Engine()));
}
else if (Strings.IsOneOf(algorithm,
"PBEWITHSHAAND2-KEYTRIPLEDES-CBC", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC"))
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new DesEdeEngine()));
}
else if (Strings.IsOneOf(algorithm,
"PBEWITHSHAAND128BITRC2-CBC", "PBEWITHSHAAND40BITRC2-CBC"))
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new RC2Engine()));
}
}
else if (algorithm.EndsWith("-BC") || algorithm.EndsWith("-OPENSSL"))
{
if (Strings.IsOneOf(algorithm,
"PBEWITHSHAAND128BITAES-CBC-BC",
"PBEWITHSHAAND192BITAES-CBC-BC",
"PBEWITHSHAAND256BITAES-CBC-BC",
"PBEWITHSHA256AND128BITAES-CBC-BC",
"PBEWITHSHA256AND192BITAES-CBC-BC",
"PBEWITHSHA256AND256BITAES-CBC-BC",
"PBEWITHMD5AND128BITAES-CBC-OPENSSL",
"PBEWITHMD5AND192BITAES-CBC-OPENSSL",
"PBEWITHMD5AND256BITAES-CBC-OPENSSL"))
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new AesFastEngine()));
}
}
}
string[] parts = algorithm.Split('/');
IBlockCipher blockCipher = null;
IAsymmetricBlockCipher asymBlockCipher = null;
IStreamCipher streamCipher = null;
string algorithmName = parts[0];
CipherAlgorithm cipherAlgorithm;
try
{
cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), algorithmName);
}
catch (ArgumentException)
{
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
switch (cipherAlgorithm)
{
case CipherAlgorithm.AES:
blockCipher = new AesFastEngine();
break;
case CipherAlgorithm.ARC4:
streamCipher = new RC4Engine();
break;
case CipherAlgorithm.BLOWFISH:
blockCipher = new BlowfishEngine();
break;
case CipherAlgorithm.CAMELLIA:
blockCipher = new CamelliaEngine();
break;
case CipherAlgorithm.CAST5:
blockCipher = new Cast5Engine();
break;
case CipherAlgorithm.CAST6:
blockCipher = new Cast6Engine();
break;
case CipherAlgorithm.DES:
blockCipher = new DesEngine();
break;
case CipherAlgorithm.DESEDE:
blockCipher = new DesEdeEngine();
break;
case CipherAlgorithm.ELGAMAL:
asymBlockCipher = new ElGamalEngine();
break;
case CipherAlgorithm.GOST28147:
blockCipher = new Gost28147Engine();
break;
case CipherAlgorithm.HC128:
streamCipher = new HC128Engine();
break;
case CipherAlgorithm.HC256:
streamCipher = new HC256Engine();
break;
#if INCLUDE_IDEA
case CipherAlgorithm.IDEA:
blockCipher = new IdeaEngine();
break;
#endif
case CipherAlgorithm.NOEKEON:
blockCipher = new NoekeonEngine();
break;
case CipherAlgorithm.PBEWITHSHAAND128BITRC4:
case CipherAlgorithm.PBEWITHSHAAND40BITRC4:
streamCipher = new RC4Engine();
break;
case CipherAlgorithm.RC2:
blockCipher = new RC2Engine();
break;
case CipherAlgorithm.RC5:
blockCipher = new RC532Engine();
break;
case CipherAlgorithm.RC5_64:
blockCipher = new RC564Engine();
break;
case CipherAlgorithm.RC6:
blockCipher = new RC6Engine();
break;
case CipherAlgorithm.RIJNDAEL:
blockCipher = new RijndaelEngine();
break;
case CipherAlgorithm.RSA:
asymBlockCipher = new RsaBlindedEngine();
break;
case CipherAlgorithm.SALSA20:
streamCipher = new Salsa20Engine();
break;
case CipherAlgorithm.SEED:
blockCipher = new SeedEngine();
break;
case CipherAlgorithm.SERPENT:
blockCipher = new SerpentEngine();
break;
case CipherAlgorithm.SKIPJACK:
blockCipher = new SkipjackEngine();
break;
case CipherAlgorithm.TEA:
blockCipher = new TeaEngine();
break;
case CipherAlgorithm.TWOFISH:
blockCipher = new TwofishEngine();
break;
case CipherAlgorithm.VMPC:
streamCipher = new VmpcEngine();
break;
case CipherAlgorithm.VMPC_KSA3:
streamCipher = new VmpcKsa3Engine();
break;
case CipherAlgorithm.XTEA:
blockCipher = new XteaEngine();
break;
default:
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
if (streamCipher != null)
{
if (parts.Length > 1)
throw new ArgumentException("Modes and paddings not used for stream ciphers");
return new BufferedStreamCipher(streamCipher);
}
bool cts = false;
bool padded = true;
IBlockCipherPadding padding = null;
IAeadBlockCipher aeadBlockCipher = null;
if (parts.Length > 2)
{
if (streamCipher != null)
throw new ArgumentException("Paddings not used for stream ciphers");
string paddingName = parts[2];
CipherPadding cipherPadding;
if (paddingName == "")
{
cipherPadding = CipherPadding.RAW;
}
else if (paddingName == "X9.23PADDING")
{
cipherPadding = CipherPadding.X923PADDING;
}
else
{
try
{
cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), paddingName);
}
catch (ArgumentException)
{
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
}
switch (cipherPadding)
{
case CipherPadding.NOPADDING:
padded = false;
break;
case CipherPadding.RAW:
break;
case CipherPadding.ISO10126PADDING:
case CipherPadding.ISO10126D2PADDING:
case CipherPadding.ISO10126_2PADDING:
padding = new ISO10126d2Padding();
break;
case CipherPadding.ISO7816_4PADDING:
case CipherPadding.ISO9797_1PADDING:
padding = new ISO7816d4Padding();
break;
case CipherPadding.ISO9796_1:
case CipherPadding.ISO9796_1PADDING:
asymBlockCipher = new ISO9796d1Encoding(asymBlockCipher);
break;
case CipherPadding.OAEP:
case CipherPadding.OAEPPADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher);
break;
case CipherPadding.OAEPWITHMD5ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new MD5Digest());
break;
case CipherPadding.OAEPWITHSHA1ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_1ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha1Digest());
break;
case CipherPadding.OAEPWITHSHA224ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_224ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha224Digest());
break;
case CipherPadding.OAEPWITHSHA256ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_256ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest());
break;
case CipherPadding.OAEPWITHSHA384ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_384ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha384Digest());
break;
case CipherPadding.OAEPWITHSHA512ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_512ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha512Digest());
break;
case CipherPadding.PKCS1:
case CipherPadding.PKCS1PADDING:
asymBlockCipher = new Pkcs1Encoding(asymBlockCipher);
break;
case CipherPadding.PKCS5:
case CipherPadding.PKCS5PADDING:
case CipherPadding.PKCS7:
case CipherPadding.PKCS7PADDING:
padding = new Pkcs7Padding();
break;
case CipherPadding.TBCPADDING:
padding = new TbcPadding();
break;
case CipherPadding.WITHCTS:
cts = true;
break;
case CipherPadding.X923PADDING:
padding = new X923Padding();
break;
case CipherPadding.ZEROBYTEPADDING:
padding = new ZeroBytePadding();
break;
default:
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
}
string mode = "";
if (parts.Length > 1)
{
mode = parts[1];
int di = GetDigitIndex(mode);
string modeName = di >= 0 ? mode.Substring(0, di) : mode;
try
{
CipherMode cipherMode = modeName == ""
? CipherMode.NONE
: (CipherMode)Enums.GetEnumValue(typeof(CipherMode), modeName);
switch (cipherMode)
{
case CipherMode.ECB:
case CipherMode.NONE:
break;
case CipherMode.CBC:
blockCipher = new CbcBlockCipher(blockCipher);
break;
case CipherMode.CCM:
aeadBlockCipher = new CcmBlockCipher(blockCipher);
break;
case CipherMode.CFB:
{
int bits = (di < 0)
? 8 * blockCipher.GetBlockSize()
: int.Parse(mode.Substring(di));
blockCipher = new CfbBlockCipher(blockCipher, bits);
break;
}
case CipherMode.CTR:
blockCipher = new SicBlockCipher(blockCipher);
break;
case CipherMode.CTS:
cts = true;
blockCipher = new CbcBlockCipher(blockCipher);
break;
case CipherMode.EAX:
aeadBlockCipher = new EaxBlockCipher(blockCipher);
break;
case CipherMode.GCM:
aeadBlockCipher = new GcmBlockCipher(blockCipher);
break;
case CipherMode.GOFB:
blockCipher = new GOfbBlockCipher(blockCipher);
break;
case CipherMode.OFB:
{
int bits = (di < 0)
? 8 * blockCipher.GetBlockSize()
: int.Parse(mode.Substring(di));
blockCipher = new OfbBlockCipher(blockCipher, bits);
break;
}
case CipherMode.OPENPGPCFB:
blockCipher = new OpenPgpCfbBlockCipher(blockCipher);
break;
case CipherMode.SIC:
if (blockCipher.GetBlockSize() < 16)
{
throw new ArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)");
}
blockCipher = new SicBlockCipher(blockCipher);
break;
default:
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
}
catch (ArgumentException)
{
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
}
if (aeadBlockCipher != null)
{
if (cts)
throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers.");
if (padded && parts.Length > 2 && parts[2] != "")
throw new SecurityUtilityException("Bad padding specified for AEAD cipher.");
return new BufferedAeadBlockCipher(aeadBlockCipher);
}
if (blockCipher != null)
{
if (cts)
{
return new CtsBlockCipher(blockCipher);
}
if (padding != null)
{
return new PaddedBufferedBlockCipher(blockCipher, padding);
}
if (!padded || blockCipher.IsPartialBlockOkay)
{
return new BufferedBlockCipher(blockCipher);
}
return new PaddedBufferedBlockCipher(blockCipher);
}
if (asymBlockCipher != null)
{
return new BufferedAsymmetricBlockCipher(asymBlockCipher);
}
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
public static string GetAlgorithmName(
DerObjectIdentifier oid)
{
return (string) algorithms[oid.Id];
}
private static int GetDigitIndex(
string s)
{
for (int i = 0; i < s.Length; ++i)
{
if (char.IsDigit(s[i]))
return i;
}
return -1;
}
}
}
| |
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using ReMi.Common.Utils;
using ReMi.Plugin.Go.Entities;
namespace ReMi.Plugin.Go.BusinessLogic
{
public class GitCommitsCollector : IGitCommitsCollector
{
private readonly IGoRequest _goRequest;
private static readonly object ParentsSync = new object();
private static readonly object ResultSync = new object();
public GitCommitsCollector(IGoRequest goRequest)
{
_goRequest = goRequest;
}
public IEnumerable<GitCommit> Collect(IEnumerable<string> livePipelines)
{
if (livePipelines == null)
return null;
var liveParents = new Dictionary<string, int>();
Parallel.ForEach(livePipelines, livePipeline =>
{
var tempLiveParents = FindLatestParentsPipelinesWithBuildNumbers(livePipeline);
if (tempLiveParents != null)
FillParents(tempLiveParents, liveParents);
});
var currentParents = new ConcurrentDictionary<string, int>();
Parallel.ForEach(liveParents, liveParent =>
{
var lastBuildNumber = FindLatestBuildNumer(liveParent.Key);
if (lastBuildNumber > 0)
currentParents.TryAdd(liveParent.Key, lastBuildNumber);
});
var lastGitCommits = FetchLastGitCommitsHistory(liveParents).Values.SelectMany(x => x.Values);
var gitCommits = FetchGitCommitsHistory(liveParents, currentParents).Values.SelectMany(x => x.Values);
return gitCommits
.Where(x => lastGitCommits.All(l => l.Revision != x.Revision))
.ToList();
}
private IDictionary<string, IDictionary<string, GitCommit>> FetchGitCommitsHistory(
IDictionary<string, int> liveParents, IEnumerable<KeyValuePair<string, int>> stagingParents)
{
var result = new Dictionary<string, IDictionary<string, GitCommit>>();
foreach (var stagingParent in stagingParents)
{
var stagingLastBuild = stagingParent.Value;
var liveLastBuild = liveParents.ContainsKey(stagingParent.Key)
? liveParents[stagingParent.Key] + 1 // we don't won't to take something which already gone live
: 1;
var parent = stagingParent;
Parallel.For(liveLastBuild, stagingLastBuild + 1, number =>
{
var valueStreamMap = _goRequest.GetPipelineValueStreamMap(parent.Key,
number.ToString(CultureInfo.InvariantCulture));
if (valueStreamMap == null || valueStreamMap.Levels.IsNullOrEmpty())
return;
if (valueStreamMap.Levels.First(x => x.Nodes.Any(n => n.Name == parent.Key))
.Nodes.First().Instances.Any(x => x.Stages.Any(s => s.Status != "Passed")))
return;
var levels = valueStreamMap.Levels;
foreach (var node in levels
.Where(level => !level.Nodes.IsNullOrEmpty())
.SelectMany(level => level.Nodes.Where(node => node.Node_Type == NoteType.Git)))
{
lock (ResultSync)
{
if (!result.ContainsKey(node.Name))
result.Add(node.Name, new Dictionary<string, GitCommit>());
var repo = result[node.Name];
foreach (var instance in node.Instances.Where(instance => !repo.ContainsKey(instance.Revision)))
{
repo.Add(instance.Revision, new GitCommit
{
Comment = instance.Comment,
User = instance.User,
ModifiedTime = instance.Modified_Time,
Revision = instance.Revision,
Repository = node.Name,
Name = RepositoryNameResolver.Resolve(node.Name)
});
}
}
}
});
}
return result;
}
private IDictionary<string, IDictionary<string, GitCommit>> FetchLastGitCommitsHistory(
IEnumerable<KeyValuePair<string, int>> liveParents)
{
var result = new Dictionary<string, IDictionary<string, GitCommit>>();
Parallel.ForEach(liveParents, liveParent =>
{
var valueStreamMap = _goRequest.GetPipelineValueStreamMap(liveParent.Key,
liveParent.Value.ToString(CultureInfo.InvariantCulture));
if (valueStreamMap == null || valueStreamMap.Levels.IsNullOrEmpty())
return;
var levels = valueStreamMap.Levels;
foreach (var node in levels
.Where(level => !level.Nodes.IsNullOrEmpty())
.SelectMany(level => level.Nodes.Where(node => node.Node_Type == NoteType.Git)))
{
lock (ResultSync)
{
if (!result.ContainsKey(node.Name))
result.Add(node.Name, new Dictionary<string, GitCommit>());
var repo = result[node.Name];
foreach (var instance in node.Instances.Where(instance => !repo.ContainsKey(instance.Revision)))
{
repo.Add(instance.Revision, new GitCommit
{
Comment = instance.Comment,
User = instance.User,
ModifiedTime = instance.Modified_Time,
Revision = instance.Revision,
Repository = node.Name,
Name = RepositoryNameResolver.Resolve(node.Name)
});
}
}
}
});
return result;
}
private static void FillParents(IEnumerable<KeyValuePair<string, int>> tempParents, IDictionary<string, int> parents)
{
foreach (var parent in tempParents)
{
lock (ParentsSync)
{
if (!parents.ContainsKey(parent.Key))
{
parents.Add(parent.Key, parent.Value);
}
else if (parents[parent.Key] > parent.Value)
{
parents[parent.Key] = parent.Value;
}
}
}
}
private int FindLatestBuildNumer(string pipelineName)
{
var history = FindLatestHistory(pipelineName);
if (history == null) return -1;
return int.Parse(history.CounterOrLabel);
}
private Dictionary<string, int> FindLatestParentsPipelinesWithBuildNumbers(string pipelineName)
{
var history = FindLatestHistory(pipelineName);
if (history == null) return null;
if (history.MaterialRevisions == null) return null;
var result = history.MaterialRevisions
.Where(x => x.Counter > 0 && x.PipelineName != null)
.ToDictionary(materialRevision => materialRevision.PipelineName, materialRevision => materialRevision.Counter);
return result;
}
private PipelineHistory FindLatestHistory(string pipelineName)
{
var pipelineInfo = _goRequest.GetPipelineInfo(pipelineName);
if (pipelineInfo == null || pipelineInfo.Groups.IsNullOrEmpty())
return null;
var group = pipelineInfo.Groups.First(x => !x.History.IsNullOrEmpty());
return group.History.IsNullOrEmpty() ? null : group.History.First();
}
}
}
| |
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace BlueOnion
{
internal class Colors : Form
{
private readonly Settings settings;
private readonly MonthCalendarEx monthCalendar;
private readonly Calendar form;
private ColorDialog colorDialog;
private GroupBox groupBox;
private GroupBox groupBoxOpacity;
private TrackBar trackBar;
private Button buttonRestoreDefaults;
private Button buttonOk;
private Button buttonCancel;
private Button buttonText;
private Label labelText;
private Label labelBackground;
private Button buttonBackground;
private Label labelTitleText;
private Button buttonTitleText;
private Label labelTitleBackground;
private Button buttonTitleBackground;
private Label labelTrailingText;
private Button buttonTrailingText;
private Label labelHighlight;
private Button buttonHighlight;
private Button buttonFont;
private Button buttonGridlines;
private Label labelGridlines;
private CheckBox checkBoxGridlines;
private Label labelWeekDayText;
private Button buttonWeekdayText;
private Label labelWeekdayBackground;
private Button buttonWeekdayBackground;
private Label labelWeeknumberBackground;
private Button buttonWeeknumberBackground;
private Label labelWeeknumberText;
private Button buttonWeeknumberText;
private Label labelWeekdayBar;
private Button buttonWeekdayBar;
private GroupBox groupBoxStart;
private CheckBox checkBoxJanuary;
private NumericUpDown numericUpDownStart;
private Label labelPreviousMonths;
/// <summary>
/// Required designer variable.
/// </summary>
private readonly Container components = null;
public Colors(MonthCalendarEx monthCalendar, Settings settings, Calendar form)
{
InitializeComponent();
this.monthCalendar = monthCalendar;
this.settings = settings;
this.form = form;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
if (colorDialog != null)
{
colorDialog.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox = new System.Windows.Forms.GroupBox();
this.labelWeekdayBar = new System.Windows.Forms.Label();
this.buttonWeekdayBar = new System.Windows.Forms.Button();
this.labelWeeknumberBackground = new System.Windows.Forms.Label();
this.buttonWeeknumberBackground = new System.Windows.Forms.Button();
this.labelWeeknumberText = new System.Windows.Forms.Label();
this.buttonWeeknumberText = new System.Windows.Forms.Button();
this.labelGridlines = new System.Windows.Forms.Label();
this.buttonGridlines = new System.Windows.Forms.Button();
this.labelWeekdayBackground = new System.Windows.Forms.Label();
this.buttonWeekdayBackground = new System.Windows.Forms.Button();
this.labelWeekDayText = new System.Windows.Forms.Label();
this.buttonWeekdayText = new System.Windows.Forms.Button();
this.labelHighlight = new System.Windows.Forms.Label();
this.buttonHighlight = new System.Windows.Forms.Button();
this.labelTrailingText = new System.Windows.Forms.Label();
this.buttonTrailingText = new System.Windows.Forms.Button();
this.labelTitleBackground = new System.Windows.Forms.Label();
this.buttonTitleBackground = new System.Windows.Forms.Button();
this.labelTitleText = new System.Windows.Forms.Label();
this.buttonTitleText = new System.Windows.Forms.Button();
this.labelBackground = new System.Windows.Forms.Label();
this.buttonBackground = new System.Windows.Forms.Button();
this.labelText = new System.Windows.Forms.Label();
this.buttonText = new System.Windows.Forms.Button();
this.colorDialog = new System.Windows.Forms.ColorDialog();
this.groupBoxOpacity = new System.Windows.Forms.GroupBox();
this.trackBar = new System.Windows.Forms.TrackBar();
this.buttonRestoreDefaults = new System.Windows.Forms.Button();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonFont = new System.Windows.Forms.Button();
this.groupBoxStart = new System.Windows.Forms.GroupBox();
this.checkBoxGridlines = new System.Windows.Forms.CheckBox();
this.checkBoxJanuary = new System.Windows.Forms.CheckBox();
this.numericUpDownStart = new System.Windows.Forms.NumericUpDown();
this.labelPreviousMonths = new System.Windows.Forms.Label();
this.groupBox.SuspendLayout();
this.groupBoxOpacity.SuspendLayout();
((System.ComponentModel.ISupportInitialize) (this.trackBar)).BeginInit();
this.groupBoxStart.SuspendLayout();
((System.ComponentModel.ISupportInitialize) (this.numericUpDownStart)).BeginInit();
this.SuspendLayout();
//
// groupBox
//
this.groupBox.Controls.Add(this.labelWeekdayBar);
this.groupBox.Controls.Add(this.buttonWeekdayBar);
this.groupBox.Controls.Add(this.labelWeeknumberBackground);
this.groupBox.Controls.Add(this.buttonWeeknumberBackground);
this.groupBox.Controls.Add(this.labelWeeknumberText);
this.groupBox.Controls.Add(this.buttonWeeknumberText);
this.groupBox.Controls.Add(this.labelGridlines);
this.groupBox.Controls.Add(this.buttonGridlines);
this.groupBox.Controls.Add(this.labelWeekdayBackground);
this.groupBox.Controls.Add(this.buttonWeekdayBackground);
this.groupBox.Controls.Add(this.labelWeekDayText);
this.groupBox.Controls.Add(this.buttonWeekdayText);
this.groupBox.Controls.Add(this.labelHighlight);
this.groupBox.Controls.Add(this.buttonHighlight);
this.groupBox.Controls.Add(this.labelTrailingText);
this.groupBox.Controls.Add(this.buttonTrailingText);
this.groupBox.Controls.Add(this.labelTitleBackground);
this.groupBox.Controls.Add(this.buttonTitleBackground);
this.groupBox.Controls.Add(this.labelTitleText);
this.groupBox.Controls.Add(this.buttonTitleText);
this.groupBox.Controls.Add(this.labelBackground);
this.groupBox.Controls.Add(this.buttonBackground);
this.groupBox.Controls.Add(this.labelText);
this.groupBox.Controls.Add(this.buttonText);
this.groupBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBox.Location = new System.Drawing.Point(8, 8);
this.groupBox.Name = "groupBox";
this.groupBox.Size = new System.Drawing.Size(296, 176);
this.groupBox.TabIndex = 0;
this.groupBox.TabStop = false;
this.groupBox.Text = "Colors";
//
// labelWeekdayBar
//
this.labelWeekdayBar.Location = new System.Drawing.Point(168, 144);
this.labelWeekdayBar.Name = "labelWeekdayBar";
this.labelWeekdayBar.Size = new System.Drawing.Size(120, 16);
this.labelWeekdayBar.TabIndex = 29;
this.labelWeekdayBar.Text = "Weekday Bar";
//
// buttonWeekdayBar
//
this.buttonWeekdayBar.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonWeekdayBar.Location = new System.Drawing.Point(144, 144);
this.buttonWeekdayBar.Name = "buttonWeekdayBar";
this.buttonWeekdayBar.Size = new System.Drawing.Size(16, 16);
this.buttonWeekdayBar.TabIndex = 28;
this.buttonWeekdayBar.Click += new System.EventHandler(this.buttonWeekdayBar_Click);
//
// labelWeeknumberBackground
//
this.labelWeeknumberBackground.Location = new System.Drawing.Point(168, 120);
this.labelWeeknumberBackground.Name = "labelWeeknumberBackground";
this.labelWeeknumberBackground.Size = new System.Drawing.Size(120, 16);
this.labelWeeknumberBackground.TabIndex = 27;
this.labelWeeknumberBackground.Text = "Week Numbers Back";
//
// buttonWeeknumberBackground
//
this.buttonWeeknumberBackground.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonWeeknumberBackground.Location = new System.Drawing.Point(144, 120);
this.buttonWeeknumberBackground.Name = "buttonWeeknumberBackground";
this.buttonWeeknumberBackground.Size = new System.Drawing.Size(16, 16);
this.buttonWeeknumberBackground.TabIndex = 26;
this.buttonWeeknumberBackground.Click += new System.EventHandler(this.buttonWeeknumberBackground_Click);
//
// labelWeeknumberText
//
this.labelWeeknumberText.Location = new System.Drawing.Point(40, 120);
this.labelWeeknumberText.Name = "labelWeeknumberText";
this.labelWeeknumberText.Size = new System.Drawing.Size(96, 16);
this.labelWeeknumberText.TabIndex = 25;
this.labelWeeknumberText.Text = "Week Numbers";
//
// buttonWeeknumberText
//
this.buttonWeeknumberText.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonWeeknumberText.Location = new System.Drawing.Point(16, 120);
this.buttonWeeknumberText.Name = "buttonWeeknumberText";
this.buttonWeeknumberText.Size = new System.Drawing.Size(16, 16);
this.buttonWeeknumberText.TabIndex = 24;
this.buttonWeeknumberText.Click += new System.EventHandler(this.buttonWeeknumberText_Click);
//
// labelGridlines
//
this.labelGridlines.Location = new System.Drawing.Point(40, 144);
this.labelGridlines.Name = "labelGridlines";
this.labelGridlines.Size = new System.Drawing.Size(96, 16);
this.labelGridlines.TabIndex = 19;
this.labelGridlines.Text = "Gridlines";
//
// buttonGridlines
//
this.buttonGridlines.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonGridlines.Location = new System.Drawing.Point(16, 144);
this.buttonGridlines.Name = "buttonGridlines";
this.buttonGridlines.Size = new System.Drawing.Size(16, 16);
this.buttonGridlines.TabIndex = 18;
this.buttonGridlines.Click += new System.EventHandler(this.buttonGridlines_Click);
//
// labelWeekdayBackground
//
this.labelWeekdayBackground.Location = new System.Drawing.Point(168, 48);
this.labelWeekdayBackground.Name = "labelWeekdayBackground";
this.labelWeekdayBackground.Size = new System.Drawing.Size(120, 16);
this.labelWeekdayBackground.TabIndex = 23;
this.labelWeekdayBackground.Text = "Weekday Background";
//
// buttonWeekdayBackground
//
this.buttonWeekdayBackground.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonWeekdayBackground.Location = new System.Drawing.Point(144, 48);
this.buttonWeekdayBackground.Name = "buttonWeekdayBackground";
this.buttonWeekdayBackground.Size = new System.Drawing.Size(16, 16);
this.buttonWeekdayBackground.TabIndex = 22;
this.buttonWeekdayBackground.Click += new System.EventHandler(this.buttonWeekdayBackground_Click);
//
// labelWeekDayText
//
this.labelWeekDayText.Location = new System.Drawing.Point(40, 48);
this.labelWeekDayText.Name = "labelWeekDayText";
this.labelWeekDayText.Size = new System.Drawing.Size(96, 16);
this.labelWeekDayText.TabIndex = 21;
this.labelWeekDayText.Text = "Weekday Text";
//
// buttonWeekdayText
//
this.buttonWeekdayText.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonWeekdayText.Location = new System.Drawing.Point(16, 48);
this.buttonWeekdayText.Name = "buttonWeekdayText";
this.buttonWeekdayText.Size = new System.Drawing.Size(16, 16);
this.buttonWeekdayText.TabIndex = 20;
this.buttonWeekdayText.Click += new System.EventHandler(this.buttonWeekdayText_Click);
//
// labelHighlight
//
this.labelHighlight.Location = new System.Drawing.Point(168, 96);
this.labelHighlight.Name = "labelHighlight";
this.labelHighlight.Size = new System.Drawing.Size(120, 16);
this.labelHighlight.TabIndex = 17;
this.labelHighlight.Text = "Highlight Text";
//
// buttonHighlight
//
this.buttonHighlight.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonHighlight.Location = new System.Drawing.Point(144, 96);
this.buttonHighlight.Name = "buttonHighlight";
this.buttonHighlight.Size = new System.Drawing.Size(16, 16);
this.buttonHighlight.TabIndex = 16;
this.buttonHighlight.Click += new System.EventHandler(this.buttonHighlight_Click);
//
// labelTrailingText
//
this.labelTrailingText.Location = new System.Drawing.Point(40, 96);
this.labelTrailingText.Name = "labelTrailingText";
this.labelTrailingText.Size = new System.Drawing.Size(96, 16);
this.labelTrailingText.TabIndex = 15;
this.labelTrailingText.Text = "Trailing Text";
//
// buttonTrailingText
//
this.buttonTrailingText.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonTrailingText.Location = new System.Drawing.Point(16, 96);
this.buttonTrailingText.Name = "buttonTrailingText";
this.buttonTrailingText.Size = new System.Drawing.Size(16, 16);
this.buttonTrailingText.TabIndex = 14;
this.buttonTrailingText.Click += new System.EventHandler(this.buttonTrailingText_Click);
//
// labelTitleBackground
//
this.labelTitleBackground.Location = new System.Drawing.Point(168, 24);
this.labelTitleBackground.Name = "labelTitleBackground";
this.labelTitleBackground.Size = new System.Drawing.Size(120, 16);
this.labelTitleBackground.TabIndex = 13;
this.labelTitleBackground.Text = "Title Background";
//
// buttonTitleBackground
//
this.buttonTitleBackground.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonTitleBackground.Location = new System.Drawing.Point(144, 24);
this.buttonTitleBackground.Name = "buttonTitleBackground";
this.buttonTitleBackground.Size = new System.Drawing.Size(16, 16);
this.buttonTitleBackground.TabIndex = 12;
this.buttonTitleBackground.Click += new System.EventHandler(this.buttonTitleBackground_Click);
//
// labelTitleText
//
this.labelTitleText.Location = new System.Drawing.Point(40, 24);
this.labelTitleText.Name = "labelTitleText";
this.labelTitleText.Size = new System.Drawing.Size(96, 16);
this.labelTitleText.TabIndex = 11;
this.labelTitleText.Text = "Title Text";
//
// buttonTitleText
//
this.buttonTitleText.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonTitleText.Location = new System.Drawing.Point(16, 24);
this.buttonTitleText.Name = "buttonTitleText";
this.buttonTitleText.Size = new System.Drawing.Size(16, 16);
this.buttonTitleText.TabIndex = 10;
this.buttonTitleText.Click += new System.EventHandler(this.buttonTitleText_Click);
//
// labelBackground
//
this.labelBackground.Location = new System.Drawing.Point(168, 72);
this.labelBackground.Name = "labelBackground";
this.labelBackground.Size = new System.Drawing.Size(120, 16);
this.labelBackground.TabIndex = 9;
this.labelBackground.Text = "Month Background";
//
// buttonBackground
//
this.buttonBackground.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonBackground.Location = new System.Drawing.Point(144, 72);
this.buttonBackground.Name = "buttonBackground";
this.buttonBackground.Size = new System.Drawing.Size(16, 16);
this.buttonBackground.TabIndex = 8;
this.buttonBackground.Click += new System.EventHandler(this.buttonBackground_Click);
//
// labelText
//
this.labelText.Location = new System.Drawing.Point(40, 72);
this.labelText.Name = "labelText";
this.labelText.Size = new System.Drawing.Size(100, 16);
this.labelText.TabIndex = 7;
this.labelText.Text = "Month Text";
//
// buttonText
//
this.buttonText.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonText.Location = new System.Drawing.Point(16, 72);
this.buttonText.Name = "buttonText";
this.buttonText.Size = new System.Drawing.Size(16, 16);
this.buttonText.TabIndex = 6;
this.buttonText.Click += new System.EventHandler(this.buttonText_Click);
//
// groupBoxOpacity
//
this.groupBoxOpacity.Controls.Add(this.trackBar);
this.groupBoxOpacity.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxOpacity.Location = new System.Drawing.Point(8, 200);
this.groupBoxOpacity.Name = "groupBoxOpacity";
this.groupBoxOpacity.Size = new System.Drawing.Size(152, 72);
this.groupBoxOpacity.TabIndex = 1;
this.groupBoxOpacity.TabStop = false;
this.groupBoxOpacity.Text = "Opacity";
//
// trackBar
//
this.trackBar.Location = new System.Drawing.Point(8, 24);
this.trackBar.Maximum = 100;
this.trackBar.Name = "trackBar";
this.trackBar.Size = new System.Drawing.Size(136, 45);
this.trackBar.TabIndex = 0;
this.trackBar.TickFrequency = 10;
this.trackBar.TickStyle = System.Windows.Forms.TickStyle.TopLeft;
this.trackBar.Scroll += new System.EventHandler(this.trackBar_Scroll);
//
// buttonRestoreDefaults
//
this.buttonRestoreDefaults.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonRestoreDefaults.Location = new System.Drawing.Point(8, 320);
this.buttonRestoreDefaults.Name = "buttonRestoreDefaults";
this.buttonRestoreDefaults.Size = new System.Drawing.Size(152, 23);
this.buttonRestoreDefaults.TabIndex = 2;
this.buttonRestoreDefaults.Text = "Restore Defaults...";
this.buttonRestoreDefaults.Click += new System.EventHandler(this.buttonRestoreDefaults_Click);
//
// buttonOk
//
this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOk.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonOk.Location = new System.Drawing.Point(77, 360);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(72, 23);
this.buttonOk.TabIndex = 3;
this.buttonOk.Text = "OK";
this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click);
//
// buttonCancel
//
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonCancel.Location = new System.Drawing.Point(165, 360);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(72, 23);
this.buttonCancel.TabIndex = 4;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonFont
//
this.buttonFont.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonFont.Location = new System.Drawing.Point(8, 288);
this.buttonFont.Name = "buttonFont";
this.buttonFont.Size = new System.Drawing.Size(152, 23);
this.buttonFont.TabIndex = 5;
this.buttonFont.Text = "Font...";
this.buttonFont.Click += new System.EventHandler(this.buttonFont_Click);
//
// groupBoxStart
//
this.groupBoxStart.Controls.Add(this.labelPreviousMonths);
this.groupBoxStart.Controls.Add(this.numericUpDownStart);
this.groupBoxStart.Controls.Add(this.checkBoxJanuary);
this.groupBoxStart.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxStart.Location = new System.Drawing.Point(176, 200);
this.groupBoxStart.Name = "groupBoxStart";
this.groupBoxStart.Size = new System.Drawing.Size(128, 112);
this.groupBoxStart.TabIndex = 6;
this.groupBoxStart.TabStop = false;
this.groupBoxStart.Text = "Start Month";
//
// checkBoxGridlines
//
this.checkBoxGridlines.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxGridlines.Location = new System.Drawing.Point(192, 320);
this.checkBoxGridlines.Name = "checkBoxGridlines";
this.checkBoxGridlines.Size = new System.Drawing.Size(112, 24);
this.checkBoxGridlines.TabIndex = 7;
this.checkBoxGridlines.Text = "Show Gridlines";
this.checkBoxGridlines.Click += new System.EventHandler(this.checkBoxGridlines_Click);
//
// checkBoxJanuary
//
this.checkBoxJanuary.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxJanuary.Location = new System.Drawing.Point(16, 24);
this.checkBoxJanuary.Name = "checkBoxJanuary";
this.checkBoxJanuary.TabIndex = 0;
this.checkBoxJanuary.Text = "January";
//
// numericUpDownStart
//
this.numericUpDownStart.Location = new System.Drawing.Point(72, 68);
this.numericUpDownStart.Minimum = new System.Decimal(new int[]
{
100,
0,
0,
-2147483648
});
this.numericUpDownStart.Name = "numericUpDownStart";
this.numericUpDownStart.Size = new System.Drawing.Size(40, 20);
this.numericUpDownStart.TabIndex = 1;
//
// labelPreviousMonths
//
this.labelPreviousMonths.Location = new System.Drawing.Point(16, 64);
this.labelPreviousMonths.Name = "labelPreviousMonths";
this.labelPreviousMonths.Size = new System.Drawing.Size(48, 24);
this.labelPreviousMonths.TabIndex = 2;
this.labelPreviousMonths.Text = "Previous Months";
//
// Colors
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(314, 400);
this.ControlBox = false;
this.Controls.Add(this.checkBoxGridlines);
this.Controls.Add(this.groupBoxStart);
this.Controls.Add(this.buttonFont);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.buttonRestoreDefaults);
this.Controls.Add(this.groupBoxOpacity);
this.Controls.Add(this.groupBox);
this.ForeColor = System.Drawing.SystemColors.ControlText;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Colors";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Appearance";
this.Load += new System.EventHandler(this.Colors_Load);
this.groupBox.ResumeLayout(false);
this.groupBoxOpacity.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize) (this.trackBar)).EndInit();
this.groupBoxStart.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize) (this.numericUpDownStart)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void Colors_Load(object sender, EventArgs e)
{
Location = Calendar.PositionAdjacent(this);
SetButtonColors();
checkBoxGridlines.Checked = settings.Gridlines;
trackBar.Value = (int) (form.Opacity*100);
checkBoxJanuary.Checked = settings.StartMonthJanuary;
numericUpDownStart.Value = settings.StartMonthPrevious;
}
private void SetButtonColors()
{
buttonText.BackColor = monthCalendar.ForeColor;
buttonBackground.BackColor = monthCalendar.BackColor;
buttonTitleText.BackColor = monthCalendar.TitleForeColor;
buttonTitleBackground.BackColor = monthCalendar.TitleBackColor;
buttonTrailingText.BackColor = monthCalendar.TrailingForeColor;
buttonHighlight.BackColor = monthCalendar.HighlightDayTextColor;
buttonGridlines.BackColor = monthCalendar.GridlinesColor;
buttonWeekdayText.BackColor = monthCalendar.WeekdayForeColor;
buttonWeekdayBackground.BackColor = monthCalendar.WeekdayBackColor;
buttonWeeknumberText.BackColor = monthCalendar.WeeknumberForeColor;
buttonWeeknumberBackground.BackColor = monthCalendar.WeeknumberBackColor;
buttonWeekdayBar.BackColor = monthCalendar.WeekdayBarColor;
}
private void buttonOk_Click(object sender, EventArgs e)
{
settings.ColorFore = monthCalendar.ForeColor;
settings.ColorBack = monthCalendar.BackColor;
settings.ColorTitleFore = monthCalendar.TitleForeColor;
settings.ColorTitleBack = monthCalendar.TitleBackColor;
settings.ColorTrailingFore = monthCalendar.TrailingForeColor;
settings.ColorHighlightDayFore = monthCalendar.HighlightDayTextColor;
settings.ColorGridlines = monthCalendar.GridlinesColor;
settings.ColorWeekdayFore = monthCalendar.WeekdayForeColor;
settings.ColorWeekdayBack = monthCalendar.WeekdayBackColor;
settings.ColorWeeknumberFore = monthCalendar.WeeknumberForeColor;
settings.ColorWeeknumberBack = monthCalendar.WeeknumberBackColor;
settings.ColorWeekdayBar = monthCalendar.WeekdayBarColor;
settings.Opacity = trackBar.Value/(double) 100;
settings.Font = monthCalendar.Font;
settings.Gridlines = monthCalendar.Gridlines;
settings.StartMonthJanuary = checkBoxJanuary.Checked;
settings.StartMonthPrevious = Convert.ToInt32(numericUpDownStart.Value);
}
private void buttonCancel_Click(object sender, EventArgs e)
{
settingsToCalendar(settings);
}
private void buttonRestoreDefaults_Click(object sender, EventArgs e)
{
var settings = new Settings();
settingsToCalendar(settings);
SetButtonColors();
}
private void settingsToCalendar(Settings settings)
{
monthCalendar.ForeColor = settings.ColorFore;
monthCalendar.BackColor = settings.ColorBack;
monthCalendar.TitleForeColor = settings.ColorTitleFore;
monthCalendar.TitleBackColor = settings.ColorTitleBack;
monthCalendar.TrailingForeColor = settings.ColorTrailingFore;
monthCalendar.HighlightDayTextColor = settings.ColorHighlightDayFore;
monthCalendar.GridlinesColor = settings.ColorGridlines;
monthCalendar.WeekdayForeColor = settings.ColorWeekdayFore;
monthCalendar.WeekdayBackColor = settings.ColorWeekdayBack;
monthCalendar.WeeknumberForeColor = settings.ColorWeeknumberFore;
monthCalendar.WeeknumberBackColor = settings.ColorWeeknumberBack;
monthCalendar.WeekdayBarColor = settings.ColorWeekdayBar;
form.Opacity = settings.Opacity;
form.BackColor = settings.ColorBack;
trackBar.Value = (int) (settings.Opacity*100);
monthCalendar.Font = settings.Font;
monthCalendar.Gridlines = settings.Gridlines;
checkBoxJanuary.Checked = settings.StartMonthJanuary;
numericUpDownStart.Value = settings.StartMonthPrevious;
}
private void trackBar_Scroll(object sender, EventArgs e)
{
var opacity = (double) trackBar.Value/100;
form.Opacity = opacity;
}
private void buttonText_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.ForeColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.ForeColor = colorDialog.Color;
buttonText.BackColor = colorDialog.Color;
}
}
private void buttonBackground_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.BackColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.BackColor = colorDialog.Color;
buttonBackground.BackColor = colorDialog.Color;
}
}
private void buttonTitleText_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.TitleForeColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.TitleForeColor = colorDialog.Color;
buttonTitleText.BackColor = colorDialog.Color;
}
}
private void buttonTitleBackground_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.TitleBackColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.TitleBackColor = colorDialog.Color;
buttonTitleBackground.BackColor = colorDialog.Color;
}
}
private void buttonTrailingText_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.TrailingForeColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.TrailingForeColor = colorDialog.Color;
buttonTrailingText.BackColor = colorDialog.Color;
}
}
private void buttonHighlight_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.HighlightDayTextColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.HighlightDayTextColor = colorDialog.Color;
buttonHighlight.BackColor = colorDialog.Color;
}
}
private void buttonGridlines_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.GridlinesColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.GridlinesColor = colorDialog.Color;
buttonGridlines.BackColor = colorDialog.Color;
}
}
private void buttonFont_Click(object sender, EventArgs e)
{
var fontDialog = new FontDialog();
fontDialog.Font = monthCalendar.Font;
fontDialog.ShowEffects = false;
fontDialog.ScriptsOnly = true;
if (fontDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.Font = fontDialog.Font;
}
}
private void checkBoxGridlines_Click(object sender, EventArgs e)
{
monthCalendar.Gridlines = checkBoxGridlines.Checked;
}
private void buttonWeekdayText_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.WeekdayForeColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.WeekdayForeColor = colorDialog.Color;
buttonWeekdayText.BackColor = colorDialog.Color;
}
}
private void buttonWeekdayBackground_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.WeekdayBackColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.WeekdayBackColor = colorDialog.Color;
buttonWeekdayBackground.BackColor = colorDialog.Color;
}
}
private void buttonWeeknumberText_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.WeeknumberForeColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.WeeknumberForeColor = colorDialog.Color;
buttonWeeknumberText.BackColor = colorDialog.Color;
}
}
private void buttonWeeknumberBackground_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.WeeknumberBackColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.WeeknumberBackColor = colorDialog.Color;
buttonWeeknumberBackground.BackColor = colorDialog.Color;
}
}
private void buttonWeekdayBar_Click(object sender, EventArgs e)
{
colorDialog.Color = monthCalendar.WeekdayBarColor;
if (colorDialog.ShowDialog(this) == DialogResult.OK)
{
monthCalendar.WeekdayBarColor = colorDialog.Color;
buttonWeekdayBar.BackColor = colorDialog.Color;
}
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Q42.HueApi.Converters;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Q42.HueApi.Models.Groups
{
[DataContract]
public class Group
{
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// Luminaire / Lightsource / LightGroup
/// </summary>
[JsonConverter(typeof(StringNullableEnumConverter))]
[DataMember(Name = "type")]
public GroupType? Type { get; set; }
/// <summary>
/// Category of the Room type. Default is "Other".
/// </summary>
[JsonConverter(typeof(StringNullableEnumConverter))]
[DataMember(Name = "class")]
public RoomClass? Class { get; set; }
/// <summary>
/// As of 1.4. Uniquely identifies the hardware model of the luminaire. Only present for automatically created Luminaires.
/// </summary>
[DataMember(Name = "modelid")]
public string ModelId { get; set; }
/// <summary>
/// The IDs of the lights that are in the group.
/// </summary>
[DataMember(Name = "lights")]
public List<string> Lights { get; set; }
/// <summary>
/// The light state of one of the lamps in the group.
/// </summary>
[DataMember(Name = "action")]
public State Action { get; set; }
[DataMember(Name = "state")]
public GroupState State { get; set; }
[DataMember(Name = "locations")]
public Dictionary<string, LightLocation> Locations { get; set; }
[DataMember(Name = "recycle")]
public bool? Recycle { get; set; }
[DataMember(Name = "stream")]
public Stream Stream { get; set; }
[DataMember(Name = "sensors")]
public List<string> Sensors { get; set; }
[DataMember(Name = "presence")]
public GroupPresence Presence { get; set; }
[DataMember(Name = "lightlevel")]
public GroupLightLevel LightLevel { get; set; }
/// <summary>
/// Overrides ToString() to give something more useful than object name.
/// </summary>
/// <returns>A string like "Group 1: Living"</returns>
public override string ToString()
{
return String.Format("Group {0}: {1}", Id, Name);
}
}
public class GroupPresence
{
[DataMember(Name = "State")]
public State State { get; set; }
[JsonProperty("lastupdated")]
[JsonConverter(typeof(NullableDateTimeConverter))]
public DateTime? Lastupdated { get; set; }
[JsonProperty("presence")]
public bool Presence { get; set; }
[JsonProperty("presence_all")]
public bool PresenceAll { get; set; }
}
public class GroupLightLevel
{
[DataMember(Name = "State")]
public SensorState State { get; set; }
[JsonProperty("lastupdated")]
[JsonConverter(typeof(NullableDateTimeConverter))]
public DateTime? Lastupdated { get; set; }
[JsonProperty("dark")]
public bool Dark { get; set; }
[JsonProperty("dark_all")]
public bool DarkAll { get; set; }
[JsonProperty("daylight")]
public bool Daylight { get; set; }
[JsonProperty("daylight_any")]
public bool DaylightAny { get; set; }
[JsonProperty("lightlevel")]
public int LightLevel { get; set; }
[JsonProperty("lightlevel_min")]
public int LightLevelMin { get; set; }
[JsonProperty("lightlevel_max")]
public int LightLevelMax { get; set; }
}
public class LightLocation : List<double>
{
[JsonIgnore]
public double X
{
get { return this[0]; }
set { this[0] = value; }
}
[JsonIgnore]
public double Y
{
get { return this[1]; }
set { this[1] = value; }
}
[JsonIgnore]
public double Z
{
get { return this[2]; }
set { this[2] = value; }
}
/// <summary>
/// Default constructor used for json deserialization
/// </summary>
public LightLocation()
{
}
public LightLocation(double x, double y, double z)
{
this.Add(x);
this.Add(y);
this.Add(z);
}
public bool IsLeft => X <= 0; //Include 0 with left
public bool IsRight => X > 0;
public bool IsFront => Y >= 0; //Include 0 with front
public bool IsBack => Y < 0;
public bool IsTop => Z >= 0; //Include 0 with top
public bool IsBottom => Z < 0;
/// <summary>
/// X > -0.1 && X < 0.1
/// </summary>
public bool IsCenter => X > -0.1 && X < 0.1;
public double Distance(double x, double y, double z)
{
var x2 = this.X;
var y2 = this.Y;
var z2 = this.Z;
return Math.Sqrt(Math.Pow(x - x2, 2) + Math.Pow(y - y2, 2) + Math.Pow(z - z2, 2));
}
public double Angle(double x, double y)
{
var lengthX = this.X - x;
var lengthY = this.Y - y;
return (Math.Atan2(lengthY, lengthX) * (180 / Math.PI)) + 180;
}
}
[DataContract]
public class GroupState
{
[DataMember(Name = "any_on")]
public bool? AnyOn { get; set; }
[DataMember(Name = "all_on")]
public bool? AllOn { get; set; }
}
/// <summary>
/// Possible group types
/// </summary>
public enum GroupType
{
[EnumMember(Value = "LightGroup")]
LightGroup,
[EnumMember(Value = "Room")]
Room,
[EnumMember(Value = "Luminaire")]
Luminaire,
[EnumMember(Value = "LightSource")]
LightSource,
[EnumMember(Value = "Entertainment")]
Entertainment,
[EnumMember(Value = "Zone")]
Zone,
[EnumMember(Value = "Free")]
Free
}
/// <summary>
/// Possible room types
/// </summary>
public enum RoomClass
{
[EnumMember(Value = "Other")]
Other,
[EnumMember(Value = "Living room")]
LivingRoom,
[EnumMember(Value = "Kitchen")]
Kitchen,
[EnumMember(Value = "Dining")]
Dining,
[EnumMember(Value = "Bedroom")]
Bedroom,
[EnumMember(Value = "Kids bedroom")]
KidsBedroom,
[EnumMember(Value = "Bathroom")]
Bathroom,
[EnumMember(Value = "Nursery")]
Nursery,
[EnumMember(Value = "Recreation")]
Recreation,
[EnumMember(Value = "Office")]
Office,
[EnumMember(Value = "Gym")]
Gym,
[EnumMember(Value = "Hallway")]
Hallway,
[EnumMember(Value = "Toilet")]
Toilet,
[EnumMember(Value = "Front door")]
FrontDoor,
[EnumMember(Value = "Garage")]
Garage,
[EnumMember(Value = "Terrace")]
Terrace,
[EnumMember(Value = "Garden")]
Garden,
[EnumMember(Value = "Driveway")]
Driveway,
[EnumMember(Value = "Carport")]
Carport,
[EnumMember(Value = "TV")]
TV,
[EnumMember(Value = "Home")]
Home,
[EnumMember(Value = "Downstairs")]
Downstairs,
[EnumMember(Value = "Upstairs")]
Upstairs,
[EnumMember(Value = "Top floor")]
TopFloor,
[EnumMember(Value = "Attic")]
Attic,
[EnumMember(Value = "Guest room")]
GuestRoom,
[EnumMember(Value = "Staircase")]
Staircase,
[EnumMember(Value = "Lounge")]
Lounge,
[EnumMember(Value = "Man cave")]
ManCave,
[EnumMember(Value = "Computer")]
Computer,
[EnumMember(Value = "Studio")]
Studio,
[EnumMember(Value = "Music")]
Music,
[EnumMember(Value = "Reading")]
Reading,
[EnumMember(Value = "Closet")]
Closet,
[EnumMember(Value = "Storage")]
Storage,
[EnumMember(Value = "Laundry room")]
LaundryRoom,
[EnumMember(Value = "Balcony")]
Balcony,
[EnumMember(Value = "Porch")]
Porch,
[EnumMember(Value = "Barbecue")]
Barbecue,
[EnumMember(Value = "Pool")]
Pool,
[EnumMember(Value = "Free")]
Free
}
[DataContract]
public class Stream
{
[DataMember(Name = "proxymode")]
public string ProxyMode { get; set; }
[DataMember(Name = "proxynode")]
public string ProxyNode { get; set; }
[DataMember(Name = "active")]
public bool Active { get; set; }
[DataMember(Name = "owner")]
public string Owner { get; set; }
}
}
| |
/*
* daap-sharp
* Copyright (C) 2005 James Willcox <snorp@snorp.net>
*
* 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.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
using System.Web;
using System.Net;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Daap {
public class Client : IDisposable {
private const int UpdateSleepInterval = 2 * 60 * 1000; // 2 minutes
private IPAddress address;
private UInt16 port;
private ContentCodeBag bag;
private ServerInfo serverInfo;
private List<Database> databases = new List<Database> ();
private ContentFetcher fetcher;
private int revision;
private bool updateRunning;
public event EventHandler Updated;
internal int Revision {
get { return revision; }
}
public string Name {
get { return serverInfo.Name; }
}
public IPAddress Address {
get { return address; }
}
public ushort Port {
get { return port; }
}
public AuthenticationMethod AuthenticationMethod {
get { return serverInfo.AuthenticationMethod; }
}
public IList<Database> Databases {
get { return new ReadOnlyCollection<Database> (databases); }
}
internal ContentCodeBag Bag {
get { return bag; }
}
internal ContentFetcher Fetcher {
get { return fetcher; }
}
public Client (Service service) : this (service.Address, service.Port) {
}
public Client (string host, UInt16 port) : this (Dns.GetHostEntry (host).AddressList[0], port) {
}
public Client (IPAddress address, UInt16 port) {
this.address = address;
this.port = port;
fetcher = new ContentFetcher (address, port);
ContentNode node = ContentParser.Parse (ContentCodeBag.Default, fetcher.Fetch ("/server-info"));
serverInfo = ServerInfo.FromNode (node);
}
~Client () {
Dispose ();
}
public void Dispose () {
updateRunning = false;
if (fetcher != null) {
fetcher.Dispose ();
fetcher = null;
}
}
private void ParseSessionId (ContentNode node) {
fetcher.SessionId = (int) node.GetChild ("dmap.sessionid").Value;
}
public void Login () {
Login (null, null);
}
public void Login (string password) {
Login (null, password);
}
public void Login (string username, string password) {
fetcher.Username = username;
fetcher.Password = password;
try {
bag = ContentCodeBag.ParseCodes (fetcher.Fetch ("/content-codes"));
ContentNode node = ContentParser.Parse (bag, fetcher.Fetch ("/login"));
ParseSessionId (node);
FetchDatabases ();
Refresh ();
if (serverInfo.SupportsUpdate) {
updateRunning = true;
Thread thread = new Thread (UpdateLoop);
thread.Name = "DAAP";
thread.IsBackground = true;
thread.Start ();
}
} catch (WebException e) {
if (e.Response != null && (e.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
throw new AuthenticationException ("Username or password incorrect");
else
throw new LoginException ("Failed to login", e);
} catch (Exception e) {
throw new LoginException ("Failed to login", e);
}
}
public void Logout () {
try {
updateRunning = false;
fetcher.KillAll ();
fetcher.Fetch ("/logout");
} catch (WebException) {
// some servers don't implement this, etc.
}
fetcher.SessionId = 0;
}
private void FetchDatabases () {
ContentNode dbnode = ContentParser.Parse (bag, fetcher.Fetch ("/databases"));
foreach (ContentNode child in (ContentNode[]) dbnode.Value) {
if (child.Name != "dmap.listing")
continue;
foreach (ContentNode item in (ContentNode[]) child.Value) {
Database db = new Database (this, item);
databases.Add (db);
}
}
}
private int GetCurrentRevision () {
ContentNode revNode = ContentParser.Parse (bag, fetcher.Fetch ("/update"), "dmap.serverrevision");
return (int) revNode.Value;
}
private int WaitForRevision (int currentRevision) {
ContentNode revNode = ContentParser.Parse (bag, fetcher.Fetch ("/update",
"revision-number=" + currentRevision));
return (int) revNode.GetChild ("dmap.serverrevision").Value;
}
private void Refresh () {
int newrev = revision;
if (serverInfo.SupportsUpdate) {
if (revision == 0)
newrev = GetCurrentRevision ();
else
newrev = WaitForRevision (revision);
if (newrev == revision)
return;
}
// Console.WriteLine ("Got new revision: " + newrev);
foreach (Database db in databases) {
db.Refresh (newrev);
}
revision = newrev;
if (Updated != null)
Updated (this, new EventArgs ());
}
private void UpdateLoop () {
while (true) {
try {
if (!updateRunning)
break;
Refresh ();
} catch (WebException) {
if (!updateRunning)
break;
// chill out for a while, maybe the server went down
// temporarily or something.
Thread.Sleep (UpdateSleepInterval);
} catch (Exception e) {
if (!updateRunning)
break;
Console.Error.WriteLine ("Exception in update loop: " + e);
Thread.Sleep (UpdateSleepInterval);
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CarouselMovement.cs" company="Google LLC">
//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
/// <summary>
/// This class handles the movement and logic of the 3D carousel.
/// </summary>
public class CarouselMovement : MonoBehaviour
{
/// <summary>
/// Camera that renders the carousel and related elements.
/// </summary>
public Camera GUICamera;
/// <summary>
/// The RawImage that renders the rendertexture.
/// </summary>
public RawImage RawImage;
/// <summary>
/// Text for the label under the center carousel button.
/// </summary>
public Text ButtonLabel;
/// <summary>
/// Number of seconds for the same button to be in the center before switching scenes.
/// </summary>
public float SecondsBeforeSwitching = 3f;
/// <summary>
/// Multiplier for carousel movement.
/// </summary>
public float TouchDeltaStrength = 4f;
/// <summary>
/// The minimum Y rotation angle for the carousel.
/// </summary>
public float MinimumRotation;
/// <summary>
/// The maximum Y rotation angle for the carousel.
/// </summary>
public float MaximumRotation;
private const string _defaultSceneLabel = "Depth-Lab";
private const float _sceneButtonAngle = 4.5f;
private Component[] _buttons;
private Coroutine _interpolateCoroutine;
private GameObject _centerButton;
private GameObject _delayedCenterButton;
private GameObject _triggeredCenterButton;
private Texture _guiTex;
private bool _centerButtonChanged = true;
private float _sceneLoadTimer = 0;
private float _clickHoldTimer = 0;
private float _startCursorPosition = 0;
private float _lastCursorPosition = 0;
private float _startCarouselRotation = 0;
private float _destinyCarouselRotation = 0;
private float _carouselVelocity = 0.0f;
private float _carouseltemAngleStep = 4.5f;
private int _negativeHalfNumberOfItens = 3;
private int _positiveHalfNumberOfItens = 3;
private bool _touchStarted = false;
// Start is called before the first frame update.
private void Start()
{
_guiTex = GUICamera.targetTexture;
_buttons = GetComponentsInChildren<SceneButton>();
if (_buttons.Length == 0)
{
// Demo Carousel is the only active scene.
ButtonLabel.text = _defaultSceneLabel;
gameObject.SetActive(false);
return;
}
float maxRotation = float.NegativeInfinity;
float minRotation = float.PositiveInfinity;
int buttonIndex = 0;
foreach (SceneButton button in _buttons)
{
// List all scene buttons from left to right based on the index.
GameObject item = button.gameObject.transform.parent.gameObject;
item.transform.localEulerAngles = new Vector3(0, -buttonIndex * _sceneButtonAngle, 0);
float rotation = WrapAngle(item.transform.localEulerAngles.y) * -1;
maxRotation = Mathf.Max(rotation, maxRotation);
minRotation = Mathf.Min(rotation, minRotation);
buttonIndex++;
}
_negativeHalfNumberOfItens = (int)(minRotation / _carouseltemAngleStep);
_positiveHalfNumberOfItens = (int)(maxRotation / _carouseltemAngleStep);
// Starts the carousel on the leftmost item.
transform.localEulerAngles = new Vector3(0, minRotation, 0);
_destinyCarouselRotation = minRotation;
}
// Update is called once per frame.
private void Update()
{
UpdateScaleAndLabels();
bool carouselIsStopped = UpdateMovement();
if (carouselIsStopped)
{
LoadCenterButtonScene();
}
// Only allow the screen to sleep when not tracking.
Screen.sleepTimeout = ARSession.notTrackingReason == NotTrackingReason.None
? SleepTimeout.NeverSleep
: SleepTimeout.SystemSetting;
}
private bool UpdateMovement()
{
if (Input.GetMouseButtonDown(0) && IsCursorOnTouchRegion())
{
// On touch start.
_startCursorPosition = Input.mousePosition.x;
_lastCursorPosition = Input.mousePosition.x;
_startCarouselRotation = transform.localEulerAngles.y;
_clickHoldTimer = 0f;
_touchStarted = true;
LoadingSpinner.Instance.Show();
}
else if (Input.GetMouseButton(0) && _touchStarted)
{
// On touch move.
float dx = (_lastCursorPosition - Input.mousePosition.x) / Screen.width;
_carouselVelocity = dx / Time.deltaTime;
_lastCursorPosition = Input.mousePosition.x;
float distanceFromStart = _startCursorPosition - Input.mousePosition.x;
distanceFromStart /= Screen.width;
distanceFromStart *= Screen.width * 0.02f; // Small speed boost.
transform.localEulerAngles = new Vector3(0,
_startCarouselRotation + distanceFromStart, 0);
_clickHoldTimer += Time.deltaTime;
}
else if (Input.GetMouseButtonUp(0) && _touchStarted)
{
float destiny = 0;
//// On touch end.
//// Check if it was just a tap.
if (_clickHoldTimer < 0.1f)
{
// If its just a tap retrieve the tapped icon and
// make the carousel animate to it.
float rescaled_x = (_lastCursorPosition / Screen.width) * _guiTex.width;
destiny = GetTappedItem(new Vector2(rescaled_x,
_guiTex.height / 2));
}
else
{
float current_y = transform.localEulerAngles.y;
current_y += _carouselVelocity;
destiny = WrapAngle(current_y);
destiny = Mathf.Round(destiny / _carouseltemAngleStep);
}
destiny = Mathf.Min(_positiveHalfNumberOfItens, destiny);
destiny = Mathf.Max(_negativeHalfNumberOfItens, destiny);
_destinyCarouselRotation = _carouseltemAngleStep * destiny;
_touchStarted = false;
}
float current = WrapAngle(transform.localEulerAngles.y);
float interpolatedRotation = current + (0.1f * (_destinyCarouselRotation - current));
transform.localEulerAngles = new Vector3(0, interpolatedRotation, 0);
return (interpolatedRotation - current) < 0.01f;
}
private bool IsCursorOnTouchRegion()
{
return Input.mousePosition.y > Screen.height - (Screen.height * 0.2f);
}
private int GetTappedItem(Vector2 cursorPosition)
{
float rotation = WrapAngle(transform.localEulerAngles.y);
Ray ray = GUICamera.ScreenPointToRay(cursorPosition);
RaycastHit rayHit;
if (Physics.Raycast(ray, out rayHit, Mathf.Infinity))
{
if (rayHit.collider.gameObject.name == "quad")
{
GameObject item = rayHit.collider.gameObject.transform.parent.gameObject;
rotation = WrapAngle(item.transform.localEulerAngles.y) * -1;
}
}
return (int)Mathf.Round(rotation / _carouseltemAngleStep);
}
private void LoadCenterButtonScene()
{
// Timer and trigger logic for carousel.
_sceneLoadTimer += Time.deltaTime;
if (_sceneLoadTimer > SecondsBeforeSwitching)
{
_sceneLoadTimer = 0f;
if (_delayedCenterButton == _centerButton &&
_triggeredCenterButton != _centerButton)
{
// Trigger button press when carousel has been at center for.
SceneButton button = _centerButton.GetComponent<SceneButton>();
if (button != null)
{
button.Press();
}
_triggeredCenterButton = _centerButton;
}
else if (!_touchStarted && _triggeredCenterButton == _centerButton)
{
LoadingSpinner.Instance.Hide();
}
_delayedCenterButton = _centerButton;
}
}
private void UpdateScaleAndLabels()
{
// Cast ray from center of UI and assign the detected center button to the centerButton
// gameobject.
Ray centerRay = GUICamera.ScreenPointToRay(new Vector2(
_guiTex.width / 2, _guiTex.height / 2));
RaycastHit centerRayHit;
GameObject center_button = null;
if (Physics.Raycast(centerRay, out centerRayHit, Mathf.Infinity))
{
center_button = centerRayHit.collider.gameObject;
}
_centerButtonChanged = center_button != _centerButton;
if (_centerButtonChanged)
{
_centerButton = center_button;
//// Provide user with haptic feedback.
HapticManager.HapticFeedback();
//// Update button label based on center button.
if (_centerButton.GetComponent<SceneButton>() != null)
{
string centerButtonLabel = _centerButton.GetComponent<SceneButton>().SceneLabel;
if (centerButtonLabel != null)
{
ButtonLabel.text = centerButtonLabel;
}
}
}
// Scale down buttons that aren't in the center, and scale up the center button.
foreach (SceneButton button in _buttons)
{
if (button.gameObject == _centerButton)
{
float scale = button.transform.localScale.x +
(0.25f * (1.12f - button.transform.localScale.x));
button.transform.localScale = new Vector3(scale, scale, scale);
}
else
{
float scale = button.transform.localScale.x +
(0.1f * (1.0f - button.transform.localScale.x));
button.transform.localScale = new Vector3(scale, scale, scale);
}
}
}
/// <summary>
/// Converts 360 angles to -180 -> +180 degrees.
/// </summary>
/// <param name="angle">Input unwrapped angle.</param>
/// <returns>Returns wrapped angle.</returns>
private float WrapAngle(float angle)
{
angle %= 360;
if (angle > 180)
{
return angle - 360;
}
return angle;
}
/// <summary>
/// Converts -180 -> +180 angles to 360 degrees.
/// </summary>
/// <param name="angle">Input wrapped angle.</param>
/// <returns>Returns unwrapped angle.</returns>
private float UnwrapAngle(float angle)
{
if (angle >= 0)
{
return angle;
}
angle = -angle % 360;
return 360 - angle;
}
}
| |
using System;
using System.Diagnostics;
using Gnu.MP.BrickCoinProtocol.BouncyCastle.Math.Raw;
using Gnu.MP.BrickCoinProtocol.BouncyCastle.Utilities;
namespace Gnu.MP.BrickCoinProtocol.BouncyCastle.Math.EC
{
internal abstract class ECFieldElement
{
public abstract BigInteger ToBigInteger();
public abstract string FieldName
{
get;
}
public abstract int FieldSize
{
get;
}
public abstract ECFieldElement Add(ECFieldElement b);
public abstract ECFieldElement AddOne();
public abstract ECFieldElement Subtract(ECFieldElement b);
public abstract ECFieldElement Multiply(ECFieldElement b);
public abstract ECFieldElement Divide(ECFieldElement b);
public abstract ECFieldElement Negate();
public abstract ECFieldElement Square();
public abstract ECFieldElement Invert();
public abstract ECFieldElement Sqrt();
public virtual int BitLength
{
get
{
return ToBigInteger().BitLength;
}
}
public virtual bool IsOne
{
get
{
return BitLength == 1;
}
}
public virtual bool IsZero
{
get
{
return 0 == ToBigInteger().SignValue;
}
}
public virtual ECFieldElement MultiplyMinusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
return Multiply(b).Subtract(x.Multiply(y));
}
public virtual ECFieldElement MultiplyPlusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
return Multiply(b).Add(x.Multiply(y));
}
public virtual ECFieldElement SquareMinusProduct(ECFieldElement x, ECFieldElement y)
{
return Square().Subtract(x.Multiply(y));
}
public virtual ECFieldElement SquarePlusProduct(ECFieldElement x, ECFieldElement y)
{
return Square().Add(x.Multiply(y));
}
public virtual ECFieldElement SquarePow(int pow)
{
ECFieldElement r = this;
for(int i = 0; i < pow; ++i)
{
r = r.Square();
}
return r;
}
public virtual bool TestBitZero()
{
return ToBigInteger().TestBit(0);
}
public override bool Equals(object obj)
{
return Equals(obj as ECFieldElement);
}
public virtual bool Equals(ECFieldElement other)
{
if(this == other)
return true;
if(null == other)
return false;
return ToBigInteger().Equals(other.ToBigInteger());
}
public override int GetHashCode()
{
return ToBigInteger().GetHashCode();
}
public override string ToString()
{
return this.ToBigInteger().ToString(16);
}
public virtual byte[] GetEncoded()
{
return BigIntegers.AsUnsignedByteArray((FieldSize + 7) / 8, ToBigInteger());
}
}
internal class FpFieldElement
: ECFieldElement
{
private readonly BigInteger q, r, x;
internal static BigInteger CalculateResidue(BigInteger p)
{
int bitLength = p.BitLength;
if(bitLength >= 96)
{
BigInteger firstWord = p.ShiftRight(bitLength - 64);
if(firstWord.LongValue == -1L)
{
return BigInteger.One.ShiftLeft(bitLength).Subtract(p);
}
if((bitLength & 7) == 0)
{
return BigInteger.One.ShiftLeft(bitLength << 1).Divide(p).Negate();
}
}
return null;
}
[Obsolete("Use ECCurve.FromBigInteger to construct field elements")]
public FpFieldElement(BigInteger q, BigInteger x)
: this(q, CalculateResidue(q), x)
{
}
internal FpFieldElement(BigInteger q, BigInteger r, BigInteger x)
{
if(x == null || x.SignValue < 0 || x.CompareTo(q) >= 0)
throw new ArgumentException("value invalid in Fp field element", "x");
this.q = q;
this.r = r;
this.x = x;
}
public override BigInteger ToBigInteger()
{
return x;
}
/**
* return the field name for this field.
*
* @return the string "Fp".
*/
public override string FieldName
{
get
{
return "Fp";
}
}
public override int FieldSize
{
get
{
return q.BitLength;
}
}
public BigInteger Q
{
get
{
return q;
}
}
public override ECFieldElement Add(
ECFieldElement b)
{
return new FpFieldElement(q, r, ModAdd(x, b.ToBigInteger()));
}
public override ECFieldElement AddOne()
{
BigInteger x2 = x.Add(BigInteger.One);
if(x2.CompareTo(q) == 0)
{
x2 = BigInteger.Zero;
}
return new FpFieldElement(q, r, x2);
}
public override ECFieldElement Subtract(
ECFieldElement b)
{
return new FpFieldElement(q, r, ModSubtract(x, b.ToBigInteger()));
}
public override ECFieldElement Multiply(
ECFieldElement b)
{
return new FpFieldElement(q, r, ModMult(x, b.ToBigInteger()));
}
public override ECFieldElement MultiplyMinusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
BigInteger ax = this.x, bx = b.ToBigInteger(), xx = x.ToBigInteger(), yx = y.ToBigInteger();
BigInteger ab = ax.Multiply(bx);
BigInteger xy = xx.Multiply(yx);
return new FpFieldElement(q, r, ModReduce(ab.Subtract(xy)));
}
public override ECFieldElement MultiplyPlusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
BigInteger ax = this.x, bx = b.ToBigInteger(), xx = x.ToBigInteger(), yx = y.ToBigInteger();
BigInteger ab = ax.Multiply(bx);
BigInteger xy = xx.Multiply(yx);
BigInteger sum = ab.Add(xy);
if(r != null && r.SignValue < 0 && sum.BitLength > (q.BitLength << 1))
{
sum = sum.Subtract(q.ShiftLeft(q.BitLength));
}
return new FpFieldElement(q, r, ModReduce(sum));
}
public override ECFieldElement Divide(
ECFieldElement b)
{
return new FpFieldElement(q, r, ModMult(x, ModInverse(b.ToBigInteger())));
}
public override ECFieldElement Negate()
{
return x.SignValue == 0 ? this : new FpFieldElement(q, r, q.Subtract(x));
}
public override ECFieldElement Square()
{
return new FpFieldElement(q, r, ModMult(x, x));
}
public override ECFieldElement SquareMinusProduct(ECFieldElement x, ECFieldElement y)
{
BigInteger ax = this.x, xx = x.ToBigInteger(), yx = y.ToBigInteger();
BigInteger aa = ax.Multiply(ax);
BigInteger xy = xx.Multiply(yx);
return new FpFieldElement(q, r, ModReduce(aa.Subtract(xy)));
}
public override ECFieldElement SquarePlusProduct(ECFieldElement x, ECFieldElement y)
{
BigInteger ax = this.x, xx = x.ToBigInteger(), yx = y.ToBigInteger();
BigInteger aa = ax.Multiply(ax);
BigInteger xy = xx.Multiply(yx);
BigInteger sum = aa.Add(xy);
if(r != null && r.SignValue < 0 && sum.BitLength > (q.BitLength << 1))
{
sum = sum.Subtract(q.ShiftLeft(q.BitLength));
}
return new FpFieldElement(q, r, ModReduce(sum));
}
public override ECFieldElement Invert()
{
// TODO Modular inversion can be faster for a (Generalized) Mersenne Prime.
return new FpFieldElement(q, r, ModInverse(x));
}
/**
* return a sqrt root - the routine verifies that the calculation
* returns the right value - if none exists it returns null.
*/
public override ECFieldElement Sqrt()
{
if(IsZero || IsOne)
return this;
if(!q.TestBit(0))
throw Platform.CreateNotImplementedException("even value of q");
if(q.TestBit(1)) // q == 4m + 3
{
BigInteger e = q.ShiftRight(2).Add(BigInteger.One);
return CheckSqrt(new FpFieldElement(q, r, x.ModPow(e, q)));
}
if(q.TestBit(2)) // q == 8m + 5
{
BigInteger t1 = x.ModPow(q.ShiftRight(3), q);
BigInteger t2 = ModMult(t1, x);
BigInteger t3 = ModMult(t2, t1);
if(t3.Equals(BigInteger.One))
{
return CheckSqrt(new FpFieldElement(q, r, t2));
}
// TODO This is constant and could be precomputed
BigInteger t4 = BigInteger.Two.ModPow(q.ShiftRight(2), q);
BigInteger y = ModMult(t2, t4);
return CheckSqrt(new FpFieldElement(q, r, y));
}
// q == 8m + 1
BigInteger legendreExponent = q.ShiftRight(1);
if(!(x.ModPow(legendreExponent, q).Equals(BigInteger.One)))
return null;
BigInteger X = this.x;
BigInteger fourX = ModDouble(ModDouble(X));
;
BigInteger k = legendreExponent.Add(BigInteger.One), qMinusOne = q.Subtract(BigInteger.One);
BigInteger U, V;
do
{
BigInteger P;
do
{
P = BigInteger.Arbitrary(q.BitLength);
}
while(P.CompareTo(q) >= 0
|| !ModReduce(P.Multiply(P).Subtract(fourX)).ModPow(legendreExponent, q).Equals(qMinusOne));
BigInteger[] result = LucasSequence(P, X, k);
U = result[0];
V = result[1];
if(ModMult(V, V).Equals(fourX))
{
return new FpFieldElement(q, r, ModHalfAbs(V));
}
}
while(U.Equals(BigInteger.One) || U.Equals(qMinusOne));
return null;
}
private ECFieldElement CheckSqrt(ECFieldElement z)
{
return z.Square().Equals(this) ? z : null;
}
private BigInteger[] LucasSequence(
BigInteger P,
BigInteger Q,
BigInteger k)
{
// TODO Research and apply "common-multiplicand multiplication here"
int n = k.BitLength;
int s = k.GetLowestSetBit();
Debug.Assert(k.TestBit(s));
BigInteger Uh = BigInteger.One;
BigInteger Vl = BigInteger.Two;
BigInteger Vh = P;
BigInteger Ql = BigInteger.One;
BigInteger Qh = BigInteger.One;
for(int j = n - 1; j >= s + 1; --j)
{
Ql = ModMult(Ql, Qh);
if(k.TestBit(j))
{
Qh = ModMult(Ql, Q);
Uh = ModMult(Uh, Vh);
Vl = ModReduce(Vh.Multiply(Vl).Subtract(P.Multiply(Ql)));
Vh = ModReduce(Vh.Multiply(Vh).Subtract(Qh.ShiftLeft(1)));
}
else
{
Qh = Ql;
Uh = ModReduce(Uh.Multiply(Vl).Subtract(Ql));
Vh = ModReduce(Vh.Multiply(Vl).Subtract(P.Multiply(Ql)));
Vl = ModReduce(Vl.Multiply(Vl).Subtract(Ql.ShiftLeft(1)));
}
}
Ql = ModMult(Ql, Qh);
Qh = ModMult(Ql, Q);
Uh = ModReduce(Uh.Multiply(Vl).Subtract(Ql));
Vl = ModReduce(Vh.Multiply(Vl).Subtract(P.Multiply(Ql)));
Ql = ModMult(Ql, Qh);
for(int j = 1; j <= s; ++j)
{
Uh = ModMult(Uh, Vl);
Vl = ModReduce(Vl.Multiply(Vl).Subtract(Ql.ShiftLeft(1)));
Ql = ModMult(Ql, Ql);
}
return new BigInteger[] { Uh, Vl };
}
protected virtual BigInteger ModAdd(BigInteger x1, BigInteger x2)
{
BigInteger x3 = x1.Add(x2);
if(x3.CompareTo(q) >= 0)
{
x3 = x3.Subtract(q);
}
return x3;
}
protected virtual BigInteger ModDouble(BigInteger x)
{
BigInteger _2x = x.ShiftLeft(1);
if(_2x.CompareTo(q) >= 0)
{
_2x = _2x.Subtract(q);
}
return _2x;
}
protected virtual BigInteger ModHalf(BigInteger x)
{
if(x.TestBit(0))
{
x = q.Add(x);
}
return x.ShiftRight(1);
}
protected virtual BigInteger ModHalfAbs(BigInteger x)
{
if(x.TestBit(0))
{
x = q.Subtract(x);
}
return x.ShiftRight(1);
}
protected virtual BigInteger ModInverse(BigInteger x)
{
int bits = FieldSize;
int len = (bits + 31) >> 5;
uint[] p = Nat.FromBigInteger(bits, q);
uint[] n = Nat.FromBigInteger(bits, x);
uint[] z = Nat.Create(len);
Mod.Invert(p, n, z);
return Nat.ToBigInteger(len, z);
}
protected virtual BigInteger ModMult(BigInteger x1, BigInteger x2)
{
return ModReduce(x1.Multiply(x2));
}
protected virtual BigInteger ModReduce(BigInteger x)
{
if(r == null)
{
x = x.Mod(q);
}
else
{
bool negative = x.SignValue < 0;
if(negative)
{
x = x.Abs();
}
int qLen = q.BitLength;
if(r.SignValue > 0)
{
BigInteger qMod = BigInteger.One.ShiftLeft(qLen);
bool rIsOne = r.Equals(BigInteger.One);
while(x.BitLength > (qLen + 1))
{
BigInteger u = x.ShiftRight(qLen);
BigInteger v = x.Remainder(qMod);
if(!rIsOne)
{
u = u.Multiply(r);
}
x = u.Add(v);
}
}
else
{
int d = ((qLen - 1) & 31) + 1;
BigInteger mu = r.Negate();
BigInteger u = mu.Multiply(x.ShiftRight(qLen - d));
BigInteger quot = u.ShiftRight(qLen + d);
BigInteger v = quot.Multiply(q);
BigInteger bk1 = BigInteger.One.ShiftLeft(qLen + d);
v = v.Remainder(bk1);
x = x.Remainder(bk1);
x = x.Subtract(v);
if(x.SignValue < 0)
{
x = x.Add(bk1);
}
}
while(x.CompareTo(q) >= 0)
{
x = x.Subtract(q);
}
if(negative && x.SignValue != 0)
{
x = q.Subtract(x);
}
}
return x;
}
protected virtual BigInteger ModSubtract(BigInteger x1, BigInteger x2)
{
BigInteger x3 = x1.Subtract(x2);
if(x3.SignValue < 0)
{
x3 = x3.Add(q);
}
return x3;
}
public override bool Equals(
object obj)
{
if(obj == this)
return true;
FpFieldElement other = obj as FpFieldElement;
if(other == null)
return false;
return Equals(other);
}
public virtual bool Equals(
FpFieldElement other)
{
return q.Equals(other.q) && base.Equals(other);
}
public override int GetHashCode()
{
return q.GetHashCode() ^ base.GetHashCode();
}
}
/**
* Class representing the Elements of the finite field
* <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB)
* representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial
* basis representations are supported. Gaussian normal basis (GNB)
* representation is not supported.
*/
internal class F2mFieldElement
: ECFieldElement
{
/**
* Indicates gaussian normal basis representation (GNB). Number chosen
* according to X9.62. GNB is not implemented at present.
*/
public const int Gnb = 1;
/**
* Indicates trinomial basis representation (Tpb). Number chosen
* according to X9.62.
*/
public const int Tpb = 2;
/**
* Indicates pentanomial basis representation (Ppb). Number chosen
* according to X9.62.
*/
public const int Ppb = 3;
/**
* Tpb or Ppb.
*/
private int representation;
/**
* The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
*/
private int m;
private int[] ks;
/**
* The <code>LongArray</code> holding the bits.
*/
private LongArray x;
/**
* Constructor for Ppb.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2mFieldElement(
int m,
int k1,
int k2,
int k3,
BigInteger x)
{
if(x == null || x.SignValue < 0 || x.BitLength > m)
throw new ArgumentException("value invalid in F2m field element", "x");
if((k2 == 0) && (k3 == 0))
{
this.representation = Tpb;
this.ks = new int[] { k1 };
}
else
{
if(k2 >= k3)
throw new ArgumentException("k2 must be smaller than k3");
if(k2 <= 0)
throw new ArgumentException("k2 must be larger than 0");
this.representation = Ppb;
this.ks = new int[] { k1, k2, k3 };
}
this.m = m;
this.x = new LongArray(x);
}
/**
* Constructor for Tpb.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2mFieldElement(
int m,
int k,
BigInteger x)
: this(m, k, 0, 0, x)
{
// Set k1 to k, and set k2 and k3 to 0
}
private F2mFieldElement(int m, int[] ks, LongArray x)
{
this.m = m;
this.representation = (ks.Length == 1) ? Tpb : Ppb;
this.ks = ks;
this.x = x;
}
public override int BitLength
{
get
{
return x.Degree();
}
}
public override bool IsOne
{
get
{
return x.IsOne();
}
}
public override bool IsZero
{
get
{
return x.IsZero();
}
}
public override bool TestBitZero()
{
return x.TestBitZero();
}
public override BigInteger ToBigInteger()
{
return x.ToBigInteger();
}
public override string FieldName
{
get
{
return "F2m";
}
}
public override int FieldSize
{
get
{
return m;
}
}
/**
* Checks, if the ECFieldElements <code>a</code> and <code>b</code>
* are elements of the same field <code>F<sub>2<sup>m</sup></sub></code>
* (having the same representation).
* @param a field element.
* @param b field element to be compared.
* @throws ArgumentException if <code>a</code> and <code>b</code>
* are not elements of the same field
* <code>F<sub>2<sup>m</sup></sub></code> (having the same
* representation).
*/
public static void CheckFieldElements(
ECFieldElement a,
ECFieldElement b)
{
if(!(a is F2mFieldElement) || !(b is F2mFieldElement))
{
throw new ArgumentException("Field elements are not "
+ "both instances of F2mFieldElement");
}
F2mFieldElement aF2m = (F2mFieldElement)a;
F2mFieldElement bF2m = (F2mFieldElement)b;
if(aF2m.representation != bF2m.representation)
{
// Should never occur
throw new ArgumentException("One of the F2m field elements has incorrect representation");
}
if((aF2m.m != bF2m.m) || !Arrays.AreEqual(aF2m.ks, bF2m.ks))
{
throw new ArgumentException("Field elements are not elements of the same field F2m");
}
}
public override ECFieldElement Add(
ECFieldElement b)
{
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
LongArray iarrClone = this.x.Copy();
F2mFieldElement bF2m = (F2mFieldElement)b;
iarrClone.AddShiftedByWords(bF2m.x, 0);
return new F2mFieldElement(m, ks, iarrClone);
}
public override ECFieldElement AddOne()
{
return new F2mFieldElement(m, ks, x.AddOne());
}
public override ECFieldElement Subtract(
ECFieldElement b)
{
// Addition and subtraction are the same in F2m
return Add(b);
}
public override ECFieldElement Multiply(
ECFieldElement b)
{
// Right-to-left comb multiplication in the LongArray
// Input: Binary polynomials a(z) and b(z) of degree at most m-1
// Output: c(z) = a(z) * b(z) mod f(z)
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
return new F2mFieldElement(m, ks, x.ModMultiply(((F2mFieldElement)b).x, m, ks));
}
public override ECFieldElement MultiplyMinusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
return MultiplyPlusProduct(b, x, y);
}
public override ECFieldElement MultiplyPlusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
LongArray ax = this.x, bx = ((F2mFieldElement)b).x, xx = ((F2mFieldElement)x).x, yx = ((F2mFieldElement)y).x;
LongArray ab = ax.Multiply(bx, m, ks);
LongArray xy = xx.Multiply(yx, m, ks);
if(ab == ax || ab == bx)
{
ab = (LongArray)ab.Copy();
}
ab.AddShiftedByWords(xy, 0);
ab.Reduce(m, ks);
return new F2mFieldElement(m, ks, ab);
}
public override ECFieldElement Divide(
ECFieldElement b)
{
// There may be more efficient implementations
ECFieldElement bInv = b.Invert();
return Multiply(bInv);
}
public override ECFieldElement Negate()
{
// -x == x holds for all x in F2m
return this;
}
public override ECFieldElement Square()
{
return new F2mFieldElement(m, ks, x.ModSquare(m, ks));
}
public override ECFieldElement SquareMinusProduct(ECFieldElement x, ECFieldElement y)
{
return SquarePlusProduct(x, y);
}
public override ECFieldElement SquarePlusProduct(ECFieldElement x, ECFieldElement y)
{
LongArray ax = this.x, xx = ((F2mFieldElement)x).x, yx = ((F2mFieldElement)y).x;
LongArray aa = ax.Square(m, ks);
LongArray xy = xx.Multiply(yx, m, ks);
if(aa == ax)
{
aa = (LongArray)aa.Copy();
}
aa.AddShiftedByWords(xy, 0);
aa.Reduce(m, ks);
return new F2mFieldElement(m, ks, aa);
}
public override ECFieldElement SquarePow(int pow)
{
return pow < 1 ? this : new F2mFieldElement(m, ks, x.ModSquareN(pow, m, ks));
}
public override ECFieldElement Invert()
{
return new F2mFieldElement(this.m, this.ks, this.x.ModInverse(m, ks));
}
public override ECFieldElement Sqrt()
{
return (x.IsZero() || x.IsOne()) ? this : SquarePow(m - 1);
}
/**
* @return the representation of the field
* <code>F<sub>2<sup>m</sup></sub></code>, either of
* {@link F2mFieldElement.Tpb} (trinomial
* basis representation) or
* {@link F2mFieldElement.Ppb} (pentanomial
* basis representation).
*/
public int Representation
{
get
{
return this.representation;
}
}
/**
* @return the degree <code>m</code> of the reduction polynomial
* <code>f(z)</code>.
*/
public int M
{
get
{
return this.m;
}
}
/**
* @return Tpb: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br/>
* Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
public int K1
{
get
{
return this.ks[0];
}
}
/**
* @return Tpb: Always returns <code>0</code><br/>
* Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
public int K2
{
get
{
return this.ks.Length >= 2 ? this.ks[1] : 0;
}
}
/**
* @return Tpb: Always set to <code>0</code><br/>
* Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
public int K3
{
get
{
return this.ks.Length >= 3 ? this.ks[2] : 0;
}
}
public override bool Equals(
object obj)
{
if(obj == this)
return true;
F2mFieldElement other = obj as F2mFieldElement;
if(other == null)
return false;
return Equals(other);
}
public virtual bool Equals(
F2mFieldElement other)
{
return ((this.m == other.m)
&& (this.representation == other.representation)
&& Arrays.AreEqual(this.ks, other.ks)
&& (this.x.Equals(other.x)));
}
public override int GetHashCode()
{
return x.GetHashCode() ^ m ^ Arrays.GetHashCode(ks);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.Security.Principal;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime;
using System.ServiceModel.Diagnostics;
using System.Runtime.Diagnostics;
namespace System.ServiceModel.Security
{
public abstract class IdentityVerifier
{
protected IdentityVerifier()
{
// empty
}
public static IdentityVerifier CreateDefault()
{
return DefaultIdentityVerifier.Instance;
}
public abstract bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext);
public abstract bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity);
private static void AdjustAddress(ref EndpointAddress reference, Uri via)
{
// if we don't have an identity and we have differing Uris, we should use the Via
if (reference.Identity == null && reference.Uri != via)
{
reference = new EndpointAddress(via);
}
}
internal bool TryGetIdentity(EndpointAddress reference, Uri via, out EndpointIdentity identity)
{
AdjustAddress(ref reference, via);
return this.TryGetIdentity(reference, out identity);
}
internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, Uri via, AuthorizationContext authorizationContext)
{
AdjustAddress(ref serviceReference, via);
this.EnsureIdentity(serviceReference, authorizationContext, SRServiceModel.IdentityCheckFailedForOutgoingMessage);
}
internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
{
if (authorizationPolicies == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
}
AuthorizationContext ac = AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies);
EnsureIdentity(serviceReference, ac, SRServiceModel.IdentityCheckFailedForOutgoingMessage);
}
private void EnsureIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext, String errorString)
{
if (authorizationContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext");
}
EndpointIdentity identity;
if (!TryGetIdentity(serviceReference, out identity))
{
SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authorizationContext, this.GetType());
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(string.Format(errorString, identity, serviceReference)));
}
else
{
if (!CheckAccess(identity, authorizationContext))
{
// CheckAccess performs a Trace on failure, no need to do it twice
Exception e = CreateIdentityCheckException(identity, authorizationContext, errorString, serviceReference);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(e);
}
}
}
private Exception CreateIdentityCheckException(EndpointIdentity identity, AuthorizationContext authorizationContext, string errorString, EndpointAddress serviceReference)
{
Exception result;
if (identity.IdentityClaim != null
&& identity.IdentityClaim.ClaimType == ClaimTypes.Dns
&& identity.IdentityClaim.Right == Rights.PossessProperty
&& identity.IdentityClaim.Resource is string)
{
string expectedDnsName = (string)identity.IdentityClaim.Resource;
string actualDnsName = null;
for (int i = 0; i < authorizationContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = authorizationContext.ClaimSets[i];
foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Dns, Rights.PossessProperty))
{
if (claim.Resource is string)
{
actualDnsName = (string)claim.Resource;
break;
}
}
if (actualDnsName != null)
{
break;
}
}
if (SRServiceModel.IdentityCheckFailedForIncomingMessage.Equals(errorString))
{
if (actualDnsName == null)
{
result = new MessageSecurityException(string.Format(SRServiceModel.DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim, expectedDnsName));
}
else
{
result = new MessageSecurityException(string.Format(SRServiceModel.DnsIdentityCheckFailedForIncomingMessage, expectedDnsName, actualDnsName));
}
}
else if (SRServiceModel.IdentityCheckFailedForOutgoingMessage.Equals(errorString))
{
if (actualDnsName == null)
{
result = new MessageSecurityException(string.Format(SRServiceModel.DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim, expectedDnsName));
}
else
{
result = new MessageSecurityException(string.Format(SRServiceModel.DnsIdentityCheckFailedForOutgoingMessage, expectedDnsName, actualDnsName));
}
}
else
{
result = new MessageSecurityException(string.Format(errorString, identity, serviceReference));
}
}
else
{
result = new MessageSecurityException(string.Format(errorString, identity, serviceReference));
}
return result;
}
private class DefaultIdentityVerifier : IdentityVerifier
{
private static readonly DefaultIdentityVerifier s_instance = new DefaultIdentityVerifier();
public static DefaultIdentityVerifier Instance
{
get { return s_instance; }
}
public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity)
{
if (reference == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reference");
identity = reference.Identity;
if (identity == null)
{
identity = this.TryCreateDnsIdentity(reference);
}
if (identity == null)
{
SecurityTraceRecordHelper.TraceIdentityDeterminationFailure(reference, typeof(DefaultIdentityVerifier));
return false;
}
else
{
SecurityTraceRecordHelper.TraceIdentityDeterminationSuccess(reference, identity, typeof(DefaultIdentityVerifier));
return true;
}
}
private EndpointIdentity TryCreateDnsIdentity(EndpointAddress reference)
{
Uri toAddress = reference.Uri;
if (!toAddress.IsAbsoluteUri)
return null;
return EndpointIdentity.CreateDnsIdentity(toAddress.DnsSafeHost);
}
internal Claim CheckDnsEquivalence(ClaimSet claimSet, string expectedSpn)
{
// host/<machine-name> satisfies the DNS identity claim
IEnumerable<Claim> claims = claimSet.FindClaims(ClaimTypes.Spn, Rights.PossessProperty);
foreach (Claim claim in claims)
{
if (expectedSpn.Equals((string)claim.Resource, StringComparison.OrdinalIgnoreCase))
{
return claim;
}
}
return null;
}
public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
{
EventTraceActivity eventTraceActivity = null;
if (identity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
if (authContext == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext");
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null);
}
for (int i = 0; i < authContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = authContext.ClaimSets[i];
if (claimSet.ContainsClaim(identity.IdentityClaim))
{
SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, this.GetType());
return true;
}
// try Claim equivalence
string expectedSpn = null;
if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
{
expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
Claim claim = CheckDnsEquivalence(claimSet, expectedSpn);
if (claim != null)
{
SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
return true;
}
}
// Allow a Sid claim to support UPN, and SPN identities
// SID claims not available yet
//SecurityIdentifier identitySid = null;
//if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Sid");
//}
//else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Upn");
//}
//else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Spn");
//}
//else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Dns");
//}
//if (identitySid != null)
//{
// Claim claim = CheckSidEquivalence(identitySid, claimSet);
// if (claim != null)
// {
// SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
// return true;
// }
//}
}
SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, this.GetType());
if (WcfEventSource.Instance.SecurityIdentityVerificationFailureIsEnabled())
{
WcfEventSource.Instance.SecurityIdentityVerificationFailure(eventTraceActivity);
}
return false;
}
}
}
}
| |
#if !(UNITY_WINRT || UNITY_WP8 || UNITY_PS3 || UNITY_WIIU)
using System;
using System.Collections;
using System.Net;
using UnityEngine;
/// <summary>
/// This script is automatically added to the PhotonHandler gameobject by PUN.
/// It will auto-ping the ExitGames cloud regions via Awake.
/// This is done only once per client and the result is saved in PlayerPrefs.
/// Use PhotonNetwork.ConnectToBestCloudServer(gameVersion) to connect to cloud region with best ping.
/// </summary>
public class PingCloudRegions : MonoBehaviour
{
public static string ClosestRegion;
public static bool ClosestRegionAvailable { get { return !string.IsNullOrEmpty(ClosestRegion); } }
public static PingCloudRegions Instance;
private bool isPinging = false;
private int lowestRegionAverage = -1;
private const string PlayerPrefsKey = "PUNCloudBestRegion";
public void Awake()
{
Instance = this;
// load settings and ping only if none available AND if we should ping on Awake
bool loadedRegion = LoadRegion(out ClosestRegion); // this sets ClosestRegion. no need to set it on success!
if (!loadedRegion && PhotonNetwork.PhotonServerSettings.PingCloudServersOnAwake)
{
RefreshCloudServerRating();
}
}
public static void RefreshCloudServerRating()
{
if (Instance != null)
{
if (Instance.isPinging)
{
Debug.Log("RefreshCloudServerRating already in process. Skipping this call.");
return;
}
Instance.StartCoroutine(Instance.PingAllRegions());
}
}
// Ping all PUN cloud regions (unless offline mode)
private IEnumerator PingAllRegions()
{
ServerSettings settings = (ServerSettings)Resources.Load(PhotonNetwork.serverSettingsAssetFile, typeof(ServerSettings));
if (settings.HostType == ServerSettings.HostingOption.OfflineMode)
yield break;
ClosestRegion = null;
isPinging = true;
lowestRegionAverage = -1;
foreach (CloudServerRegion region in System.Enum.GetValues(typeof(CloudServerRegion)))
{
yield return StartCoroutine(PingRegion(region));
}
isPinging = false;
}
/// <summary>
/// Pings a server several times to get an average RTT. If that's lower than the current best, the region becomes closestRegion.
/// </summary>
/// <param name="region"></param>
/// <returns></returns>
IEnumerator PingRegion(CloudServerRegion region)
{
string hostname = ServerSettings.FindServerAddressForRegion(region);
string regionIp = ResolveHost(hostname);
if (string.IsNullOrEmpty(regionIp))
{
Debug.LogError("Could not resolve host: " + hostname);
yield break;
}
int pingSum = 0;
int tries = 3;
int skipped = 0;
float timeout = 0.700f; // 700 milliseconds is our max, after this we assume a timeout.
for (int i = 0; i < tries; i++)
{
float startTime = Time.time;
Ping ping = new Ping(regionIp);
while (!ping.isDone && Time.time < startTime + timeout)
{
// sometimes Unity ping never returns, so we use a timeout here
yield return 0;
}
if (ping.time == -1)
{
if (skipped > 5)
{
pingSum += (int)(timeout * 1000) * tries;
break;
}
else
{
i -= 1; //Sometimes Unity ping doesnt return, we therefor retry a few times..
skipped++;
continue;
}
}
pingSum += ping.time;
}
int pingAverage = pingSum / tries;
//Debug.LogWarning (hostname + ": " + regionAverage + "ms");
if (pingAverage < lowestRegionAverage || lowestRegionAverage == -1)
{
lowestRegionAverage = pingAverage;
SaveAndSetRegion(region.ToString());
}
}
public static void ConnectToBestRegion()
{
Instance.StartCoroutine(Instance.ConnectToBestRegionInternal());
}
IEnumerator ConnectToBestRegionInternal()
{
CloudServerRegion bestRegion;
if (!ClosestRegionAvailable || !ServerSettings.TryParseCloudServerRegion(ClosestRegion, out bestRegion))
{
RefreshCloudServerRating();
}
while (isPinging)
{
yield return 0; // wait until pinging finished (offline mode won't ping)
}
ServerSettings.TryParseCloudServerRegion(ClosestRegion, out bestRegion);
string bestServerAddress = ServerSettings.FindServerAddressForRegion(bestRegion);
string bestServerFullAddress = bestServerAddress + ":" + ServerSettings.DefaultMasterPort;
PhotonNetwork.networkingPeer.MasterServerAddress = bestServerFullAddress;
PhotonNetwork.networkingPeer.Connect(bestServerFullAddress, ServerConnection.MasterServer);
}
/// <summary>
/// Loads the region shortcut from PlayerPrefs or initializes the region as empty string.
/// </summary>
/// <returns>True of any player pref was set and loaded.</returns>
private static bool LoadRegion(out string region)
{
region = PlayerPrefs.GetString(PlayerPrefsKey, "");
return !string.IsNullOrEmpty(region);
}
/// <summary>Sets ClosestRegion and saves it in a PlayerPref setting.</summary>
private static void SaveAndSetRegion(string region)
{
ClosestRegion = region;
PlayerPrefs.SetString(PlayerPrefsKey, region);
}
/// <summary>Removes the PlayerPref setting for "best region".</summary>
public static void DeleteRegionPref()
{
if (Instance != null && Instance.isPinging)
{
Debug.LogWarning("DeleteRegionPref can't delete region while pining is going on.");
return;
}
ClosestRegion = null;
PlayerPrefs.DeleteKey(PlayerPrefsKey);
}
public static void OverrideRegion(CloudServerRegion region)
{
SaveAndSetRegion(region.ToString());
}
/// <summary>
/// Attempts to resolve a hostname into an IP string or returns empty string if that fails.
/// </summary>
/// <param name="hostName">Hostname to resolve.</param>
/// <returns>IP string or empty string if resolution fails</returns>
public static string ResolveHost(string hostName)
{
try
{
IPAddress[] address = Dns.GetHostAddresses(hostName);
if (address.Length == 1)
{
return address[0].ToString();
}
// if we got more addresses, try to pick a IPv4 one
for (int index = 0; index < address.Length; index++)
{
IPAddress ipAddress = address[index];
if (ipAddress != null)
{
string ipString = ipAddress.ToString();
if (ipString.IndexOf('.') >= 0)
{
return ipString;
}
}
}
}
catch (System.Exception e)
{
Debug.Log("Exception caught! " + e.Source + " Message: " + e.Message);
}
return string.Empty;
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ConvertToVector128Int32Vector128Double()
{
var test = new SimpleUnaryOpConvTest__ConvertToVector128Int32Vector128Double();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpConvTest__ConvertToVector128Int32Vector128Double
{
private struct TestStruct
{
public Vector128<Double> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpConvTest__ConvertToVector128Int32Vector128Double testClass)
{
var result = Sse2.ConvertToVector128Int32(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar;
private Vector128<Double> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Double> _dataTable;
static SimpleUnaryOpConvTest__ConvertToVector128Int32Vector128Double()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleUnaryOpConvTest__ConvertToVector128Int32Vector128Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Double>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ConvertToVector128Int32(
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ConvertToVector128Int32(
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ConvertToVector128Int32(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Int32), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Int32), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Int32), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ConvertToVector128Int32(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr);
var result = Sse2.ConvertToVector128Int32(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse2.ConvertToVector128Int32(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse2.ConvertToVector128Int32(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpConvTest__ConvertToVector128Int32Vector128Double();
var result = Sse2.ConvertToVector128Int32(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ConvertToVector128Int32(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ConvertToVector128Int32(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (int)Math.Round(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((i < 2) ? (int)Math.Round(firstOp[i]) : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ConvertToVector128Int32)}<Int32>(Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using Marqueone.TimeAndMaterials.Api.DataAccess;
using Marqueone.TimeAndMaterials.Api.DataAccess.Services;
using Marqueone.TimeAndMaterials.Api.Models.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Marqueone.TimeAndMaterials.Api.Controllers
{
[Route("_api/[controller]")]
[Produces("application/json")]
public class EmployeeController : Controller
{
private TamContext _context { get; }
private ILogger<EmployeeController> _logger;
private EmployeeService _service { get; set; }
public EmployeeController(ILogger<EmployeeController> logger,
TamContext context,
EmployeeService service)
{
_context = context;
_logger = logger;
_service = service;
}
[HttpGet]
[Route("")]
public async Task<IActionResult> GetEmployees()
{
try
{
return Ok(await _service.GetEmployees());
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500);
}
}
[HttpGet]
[Route("by-id/{id}")]
public async Task<IActionResult> GetEmployeeById(int id)
{
try
{
return Ok(await _service.GetById(id));
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500, new { Message = ex.Message, Status = 500 });
}
}
[HttpPost]
[Route("add")]
public async Task<IActionResult> Add([FromBody]NewEmployeeViewModel model)
{
try
{
if (!ModelState.IsValid)
{
return StatusCode(400, ModelState);
}
var result = await _service.Add(firstName: model.FirstName,
lastName: model.LastName,
employeeType: model.Type,
contacts: model.Contacts,
trades: model.Trades);
if (!result)
{
return StatusCode(400, new { Message = $"Unable to add new Employee: {model.FirstName} {model.LastName}", Status = 400 });
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500);
}
}
/*[HttpPost]
[Route("update")]
public async Task<IActionResult> Update([FromBody] UpdateEmployeeViewModel model)
{
try
{
if (!ModelState.IsValid)
{
return StatusCode(400, ModelState);
}
var result = await _service.Update(id: model.Id,
firstName: model.FirstName,
lastName: model.LastName,
employeeType: model.Type,
contacts: model.Contacts,
trades: model.Trades);
if (!result)
{
return StatusCode(400, new { Message = $"Unable to update Employee: {model.FirstName} {model.LastName}", Status = 400});
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500);
}
}
[HttpPost]
[Route("delete/{id}")]
[Produces("application/json")]
public async Task<IActionResult> Delete(int id)
{
try
{
if(id == 0)
{
return StatusCode(400, new { Message = $"Invalid id provided", Status = 400});
}
var result = await _service.Delete(id: id);
if (!result)
{
return StatusCode(400, new { Message = $"Unable to delete Equipment with id: {id}", Status = 400});
}
return Ok(id);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500, new { Message = ex.Message, Status = 500});
}
}*/
[HttpPost]
[Route("add/contact")]
public async Task<IActionResult> AddEmployeeContactMethod([FromBody] NewEmployeeContactMethodViewModel model)
{
try
{
if (!ModelState.IsValid)
{
return StatusCode(400, ModelState);
}
var result = await _service.AddContactMethod(employeeId: model.EmployeeId, contactType: model.Type, value: model.Value, isPrivate: model.IsPrivate);
if (!result)
{
return StatusCode(400, new { Message = $"Unable to add new Employee Contact Method", Status = 400 });
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500);
}
}
[HttpPost]
[Route("update/contact")]
public async Task<IActionResult> UpdateEmployeeContactMethod([FromBody] UpdateEmployeeContactMethodViewModel model)
{
try
{
if (!ModelState.IsValid)
{
return StatusCode(400, ModelState);
}
var result = await _service.UpdateEmployeeContact(id: model.Id, contactType: model.Type, value: model.Value, isPrivate: model.IsPrivate);
if (!result)
{
return StatusCode(400, new { Message = $"Unable to update Employee Contact", Status = 400 });
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500);
}
}
[HttpPost]
[Route("delete/contact/{id}")]
public async Task<IActionResult> Delete(int id)
{
try
{
if(id == 0)
{
return StatusCode(400, new { Message = $"Invalid id provided", Status = 400});
}
var result = await _service.DeleteEmployeeContact(id: id);
if (!result)
{
return StatusCode(400, new { Message = $"Unable to delete Employee Contact with id: {id}", Status = 400});
}
return Ok(id);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500, new { Message = ex.Message, Status = 500});
}
}
[HttpPost]
[Route("add/trade")]
public async Task<IActionResult> AddTrade([FromBody] AddEmployeeTradeViewModel model)
{
try
{
if (!ModelState.IsValid)
{
return StatusCode(400, ModelState);
}
var result = await _service.AddEmployeeTrade(employeeId: model.EmployeeId, tradeId: model.TradeId);
if (!result)
{
return StatusCode(400, new { Message = $"Unable to add new Trade to Employee", Status = 400 });
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500);
}
}
[HttpPost]
[Route("remove/trade")]
public async Task<IActionResult> RemoveTrade([FromBody] RemoveEmployeeTradeViewModel model)
{
try
{
if (!ModelState.IsValid)
{
return StatusCode(400, ModelState);
}
var result = await _service.RemoveEmployeeTrade(employeeId: model.EmployeeId, tradeId: model.TradeId);
if (!result)
{
return StatusCode(400, new { Message = $"Unable to remove Trade from Employee", Status = 400 });
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_logger.LogError(ex.StackTrace);
return StatusCode(500);
}
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2015 Secret Lab Pty. Ltd. and Yarn Spinner contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Comment out to not catch exceptions
#define CATCH_EXCEPTIONS
using System;
using System.Collections.Generic;
using Json;
namespace Yarn {
internal class Loader {
private Dialogue dialogue;
public Program program { get; private set; }
// Prints out the list of tokens that the tokeniser found for this node
void PrintTokenList(IEnumerable<Token> tokenList) {
// Sum up the result
var sb = new System.Text.StringBuilder();
foreach (var t in tokenList) {
sb.AppendLine (string.Format("{0} ({1} line {2})", t.ToString (), t.context, t.lineNumber));
}
// Let's see what we got
dialogue.LogDebugMessage("Tokens:");
dialogue.LogDebugMessage(sb.ToString());
}
// Prints the parse tree for the node
void PrintParseTree(Yarn.Parser.ParseNode rootNode) {
dialogue.LogDebugMessage("Parse Tree:");
dialogue.LogDebugMessage(rootNode.PrintTree(0));
}
// Prepares a loader. 'implementation' is used for logging.
public Loader(Dialogue dialogue) {
if (dialogue == null)
throw new ArgumentNullException ("dialogue");
this.dialogue = dialogue;
}
// Given a bunch of raw text, load all nodes that were inside it.
// You can call this multiple times to append to the collection of nodes,
// but note that new nodes will replace older ones with the same name.
// Returns the number of nodes that were loaded.
public Program Load(string text, Library library, string fileName, Program includeProgram, bool showTokens, bool showParseTree, string onlyConsiderNode) {
// The final parsed nodes that were in the file we were given
Dictionary<string, Yarn.Parser.Node> nodes = new Dictionary<string, Parser.Node>();
// Load the raw data and get the array of node title-text pairs
var nodeInfos = ParseInput (text);
int nodesLoaded = 0;
foreach (NodeInfo nodeInfo in nodeInfos) {
if (onlyConsiderNode != null && nodeInfo.title != onlyConsiderNode)
continue;
// Attempt to parse every node; log if we encounter any errors
#if CATCH_EXCEPTIONS
try {
#endif
if (nodes.ContainsKey(nodeInfo.title)) {
throw new InvalidOperationException("Attempted to load a node called "+
nodeInfo.title+", but a node with that name has already been loaded!");
}
var lexer = new Lexer ();
var tokens = lexer.Tokenise (nodeInfo.title, nodeInfo.text);
if (showTokens)
PrintTokenList (tokens);
var node = new Parser (tokens, library).Parse();
// If this node is tagged "rawText", then preserve its source
if (string.IsNullOrEmpty(nodeInfo.tags) == false &&
nodeInfo.tags.Contains("rawText")) {
node.source = nodeInfo.text;
}
node.name = nodeInfo.title;
if (showParseTree)
PrintParseTree(node);
nodes[nodeInfo.title] = node;
nodesLoaded++;
#if CATCH_EXCEPTIONS
} catch (Yarn.TokeniserException t) {
// Add file information
var message = string.Format ("In file {0}: Error reading node {1}: {2}", fileName, nodeInfo.title, t.Message);
throw new Yarn.TokeniserException (message);
} catch (Yarn.ParseException p) {
var message = string.Format ("In file {0}: Error parsing node {1}: {2}", fileName, nodeInfo.title, p.Message);
throw new Yarn.ParseException (message);
} catch (InvalidOperationException e) {
var message = string.Format ("In file {0}: Error reading node {1}: {2}", fileName, nodeInfo.title, e.Message);
throw new InvalidOperationException (message);
}
#endif
}
var compiler = new Yarn.Compiler(fileName);
foreach (var node in nodes) {
compiler.CompileNode (node.Value);
}
if (includeProgram != null) {
compiler.program.Include (includeProgram);
}
return compiler.program;
}
// The raw text of the Yarn node, plus metadata
struct NodeInfo {
public string title;
public string text;
public string tags;
public NodeInfo(string title, string text, string tags) {
this.title = title;
this.text = text;
this.tags = tags;
}
}
// Given either Twine, JSON or XML input, return an array
// containing info about the nodes in that file
NodeInfo[] ParseInput(string text)
{
// All the nodes we found in this file
var nodes = new List<NodeInfo> ();
if (text.IndexOf("//") == 0) {
// If it starts with a comment, treat it as a single-node file
nodes.Add (new NodeInfo ("Start", text, null));
} else {
// Blindly assume it's JSON! \:D/
try {
// First, parse the raw text
var loadedJSON = JsonParser.FromJson (text);
// Process each item that was found (probably just a single one)
foreach (var item in loadedJSON) {
// We expect it to be an array of dictionaries
var list = item.Value as IList<object>;
// For each dictionary in the list..
foreach (IDictionary<string,object> nodeJSON in list) {
// Pull out the node's title and body, and use that
nodes.Add(
new NodeInfo(
nodeJSON["title"] as string,
nodeJSON["body"] as string,
nodeJSON["tags"] as string
)
);
}
}
} catch (InvalidCastException) {
dialogue.LogErrorMessage ("Error parsing Yarn input: it's valid JSON, but " +
"it didn't match the data layout I was expecting.");
} catch (InvalidJsonException e) {
dialogue.LogErrorMessage ("Error parsing Yarn input: " + e.Message);
}
}
// hooray we're done
return nodes.ToArray();
}
}
}
| |
/*
* CID0010.cs - it culture handler.
*
* Copyright (c) 2003 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "it.txt".
namespace I18N.West
{
using System;
using System.Globalization;
using I18N.Common;
public class CID0010 : RootCulture
{
public CID0010() : base(0x0010) {}
public CID0010(int culture) : base(culture) {}
public override String Name
{
get
{
return "it";
}
}
public override String ThreeLetterISOLanguageName
{
get
{
return "ita";
}
}
public override String ThreeLetterWindowsLanguageName
{
get
{
return "ITA";
}
}
public override String TwoLetterISOLanguageName
{
get
{
return "it";
}
}
public override DateTimeFormatInfo DateTimeFormat
{
get
{
DateTimeFormatInfo dfi = base.DateTimeFormat;
dfi.AMDesignator = "m.";
dfi.PMDesignator = "p.";
dfi.AbbreviatedDayNames = new String[] {"dom", "lun", "mar", "mer", "gio", "ven", "sab"};
dfi.DayNames = new String[] {"domenica", "luned\u00EC", "marted\u00EC", "mercoled\u00EC", "gioved\u00EC", "venerd\u00EC", "sabato"};
dfi.AbbreviatedMonthNames = new String[] {"gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic", ""};
dfi.MonthNames = new String[] {"gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre", ""};
dfi.DateSeparator = "/";
dfi.TimeSeparator = ":";
dfi.LongDatePattern = "dd MMMM yyyy";
dfi.LongTimePattern = "HH:mm:ss z";
dfi.ShortDatePattern = "dd/MM/yy";
dfi.ShortTimePattern = "HH:mm";
dfi.FullDateTimePattern = "dddd d MMMM yyyy HH:mm:ss z";
dfi.I18NSetDateTimePatterns(new String[] {
"d:dd/MM/yy",
"D:dddd d MMMM yyyy",
"f:dddd d MMMM yyyy HH:mm:ss z",
"f:dddd d MMMM yyyy HH:mm:ss z",
"f:dddd d MMMM yyyy HH:mm:ss",
"f:dddd d MMMM yyyy HH:mm",
"F:dddd d MMMM yyyy HH:mm:ss",
"g:dd/MM/yy HH:mm:ss z",
"g:dd/MM/yy HH:mm:ss z",
"g:dd/MM/yy HH:mm:ss",
"g:dd/MM/yy HH:mm",
"G:dd/MM/yy HH:mm:ss",
"m:MMMM dd",
"M:MMMM dd",
"r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"s:yyyy'-'MM'-'dd'T'HH':'mm':'ss",
"t:HH:mm:ss z",
"t:HH:mm:ss z",
"t:HH:mm:ss",
"t:HH:mm",
"T:HH:mm:ss",
"u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
"U:dddd, dd MMMM yyyy HH:mm:ss",
"y:yyyy MMMM",
"Y:yyyy MMMM",
});
return dfi;
}
set
{
base.DateTimeFormat = value; // not used
}
}
public override NumberFormatInfo NumberFormat
{
get
{
NumberFormatInfo nfi = base.NumberFormat;
nfi.CurrencyDecimalSeparator = ",";
nfi.CurrencyGroupSeparator = ".";
nfi.NumberGroupSeparator = ".";
nfi.PercentGroupSeparator = ".";
nfi.NegativeSign = "-";
nfi.NumberDecimalSeparator = ",";
nfi.PercentDecimalSeparator = ",";
nfi.PercentSymbol = "%";
nfi.PerMilleSymbol = "\u2030";
return nfi;
}
set
{
base.NumberFormat = value; // not used
}
}
public override String ResolveLanguage(String name)
{
switch(name)
{
case "it": return "italiano";
}
return base.ResolveLanguage(name);
}
public override String ResolveCountry(String name)
{
switch(name)
{
case "IT": return "Italia";
case "CH": return "Svizzera";
}
return base.ResolveCountry(name);
}
private class PrivateTextInfo : _I18NTextInfo
{
public PrivateTextInfo(int culture) : base(culture) {}
public override int EBCDICCodePage
{
get
{
return 20280;
}
}
public override int OEMCodePage
{
get
{
return 850;
}
}
public override String ListSeparator
{
get
{
return ";";
}
}
}; // class PrivateTextInfo
public override TextInfo TextInfo
{
get
{
return new PrivateTextInfo(LCID);
}
}
}; // class CID0010
public class CNit : CID0010
{
public CNit() : base() {}
}; // class CNit
}; // namespace I18N.West
| |
using UnityEngine;
using UnityEditor;
namespace Anima2D
{
public class RectHandles
{
private static Rect s_StartRect;
private static Rect s_CurrentRect;
private static Vector3 s_StartPosition;
private static Vector2 s_StartPivot;
private static Vector3[] s_TempVectors = new Vector3[0];
public static void Do(ref Rect handleRect,ref Vector3 handlePosition, ref Quaternion handleRectRotation, bool usePivot = true, bool anchorPivot = false)
{
GUI.color = Color.white;
RenderRect(handleRect,handlePosition,handleRectRotation,new Color(0.25f, 0.5f, 1f, 1f), 0.05f, 0.8f);
handleRect = MoveHandlesGUI(handleRect, ref handlePosition, handleRectRotation, anchorPivot || !usePivot);
if(usePivot)
{
handleRect = PivotHandleGUI(handleRect, ref handlePosition, handleRectRotation);
}
handleRect = ResizeHandlesGUI(handleRect,ref handlePosition, handleRectRotation, anchorPivot || !usePivot);
if(usePivot)
{
handleRectRotation = RotationHandlesGUI(handleRect, handlePosition, handleRectRotation);
}
}
static Vector2 GetLocalRectPoint(Rect rect, int index)
{
switch (index)
{
case 0:
return new Vector2(rect.xMin, rect.yMax);
case 1:
return new Vector2(rect.xMax, rect.yMax);
case 2:
return new Vector2(rect.xMax, rect.yMin);
case 3:
return new Vector2(rect.xMin, rect.yMin);
default:
return Vector3.zero;
}
}
static Vector3 GetRectPointInWorld(Rect rect, Vector3 pivot, Quaternion rotation, int xHandle, int yHandle)
{
Vector3 point = new Vector2(Mathf.Lerp(rect.xMin, rect.xMax, (float)xHandle * 0.5f), Mathf.Lerp(rect.yMin, rect.yMax, (float)yHandle * 0.5f));
return rotation * point + pivot;
}
static Vector2 GetNormalizedPivot(Rect rect)
{
return new Vector2(-rect.position.x/rect.width, -rect.position.y/rect.height);
}
static Rect ResizeHandlesGUI(Rect rect,ref Vector3 position, Quaternion rotation, bool anchorPivot = false)
{
if (Event.current.type == EventType.MouseDown)
{
s_StartRect = rect;
s_CurrentRect = rect;
s_StartPosition = position;
s_StartPivot = GetNormalizedPivot(rect);
}
Vector3 scale = Vector3.one;
Quaternion inverseRotation = Quaternion.Inverse(rotation);
for (int i = 0; i <= 2; i++)
{
for (int j = 0; j <= 2; j++)
{
if (i != 1 || j != 1)
{
Vector3 startWorldPoint = GetRectPointInWorld(s_StartRect, s_StartPosition, rotation, i, j);
Vector3 currentWorldPoint = GetRectPointInWorld(s_CurrentRect, s_StartPosition, rotation, i, j);
Vector3 rectWorldPoint = GetRectPointInWorld(rect, position, rotation, i, j);
int controlID = GUIUtility.GetControlID("RectResizeHandles".GetHashCode(), FocusType.Passive);
EventType eventType = Event.current.GetTypeForControl(controlID);
if (GUI.color.a > 0f || GUIUtility.hotControl == controlID)
{
EditorGUI.BeginChangeCheck();
Vector3 newPosition = Vector3.zero;
MouseCursor cursor = MouseCursor.Arrow;
if (i == 1 || j == 1)
{
Vector3 sideVector = (i != 1) ? (rotation * Vector3.up * rect.height) : (rotation * Vector3.right * rect.width);
Vector3 direction = (i != 1) ? (rotation * Vector3.right) : (rotation * Vector3.up);
newPosition = SideSlider(controlID, currentWorldPoint, sideVector, direction, null);
if(!Event.current.alt && eventType == EventType.Layout)
{
Vector3 normalized2 = sideVector.normalized;
Vector3 p1 = rectWorldPoint + sideVector * 0.5f;
Vector3 p2 = rectWorldPoint - sideVector * 0.5f;
Vector3 offset = - normalized2 * HandleUtility.GetHandleSize(p1) / 20f;
Vector3 offset2 = normalized2 * HandleUtility.GetHandleSize(p2) / 20f;
HandleUtility.AddControl(controlID, HandleUtility.DistanceToLine(p1 + offset, p2 + offset2));
}
cursor = GetScaleCursor(direction);
}
else
{
HandlesExtra.DotCap(controlID,rectWorldPoint, Quaternion.identity, 1f, eventType);
newPosition = HandlesExtra.Slider2D(controlID, currentWorldPoint,null);
if(!Event.current.alt && eventType == EventType.Layout)
{
HandleUtility.AddControl(controlID, HandleUtility.DistanceToCircle(rectWorldPoint, HandleUtility.GetHandleSize(rectWorldPoint) / 20f));
}
Vector3 outwardsDir = rotation * Vector3.right * (float)(i - 1);
Vector3 outwardsDir2 = rotation * Vector3.up * (float)(j - 1);
cursor = GetScaleCursor(outwardsDir + outwardsDir2);
}
if(eventType == EventType.Repaint)
{
if ((HandleUtility.nearestControl == controlID && GUIUtility.hotControl == 0) || GUIUtility.hotControl == controlID)
{
Rect cursorRect = new Rect(0,0, 20f, 20f);
cursorRect.center = Event.current.mousePosition;
EditorGUIUtility.AddCursorRect(cursorRect, cursor, controlID);
}
}
if (EditorGUI.EndChangeCheck())
{
Vector3 scalePivot = Vector3.zero;
Vector2 scalePivotLocal = Vector2.one;
bool alt = Event.current.alt;
bool actionKey = EditorGUI.actionKey;
bool shiftDown = Event.current.shift && !actionKey;
if (!alt)
{
scalePivot = GetRectPointInWorld(s_StartRect, s_StartPosition, rotation, 2 - i, 2 - j);
scalePivotLocal = inverseRotation * (scalePivot - s_StartPosition);
}
Vector3 localRectPoint = inverseRotation * (startWorldPoint - scalePivot);
Vector3 localNewPosition = inverseRotation * (newPosition - scalePivot);
if (i != 1)
{
scale.x = localNewPosition.x / localRectPoint.x;
}
if (j != 1)
{
scale.y = localNewPosition.y / localRectPoint.y;
}
if (shiftDown)
{
float d = (i != 1) ? scale.x : scale.y;
scale = Vector3.one * d;
}
if (actionKey && i == 1)
{
if (Event.current.shift)
{
scale.x = (scale.z = 1f / Mathf.Sqrt(Mathf.Max(scale.y, 0.0001f)));
}
else
{
scale.x = 1f / Mathf.Max(scale.y, 0.0001f);
}
}
if (shiftDown)
{
float d2 = (i != 1) ? scale.x : scale.y;
scale = Vector3.one * d2;
}
if (actionKey && i == 1)
{
if (Event.current.shift)
{
scale.x = (scale.z = 1f / Mathf.Sqrt(Mathf.Max(scale.y, 0.0001f)));
}
else
{
scale.x = 1f / Mathf.Max(scale.y, 0.0001f);
}
}
if (actionKey && j == 1)
{
if (Event.current.shift)
{
scale.y = (scale.z = 1f / Mathf.Sqrt(Mathf.Max(scale.x, 0.0001f)));
}
else
{
scale.y = 1f / Mathf.Max(scale.x, 0.0001f);
}
}
s_CurrentRect.min = Vector2.Scale(scale,s_StartRect.min - scalePivotLocal) + scalePivotLocal;
s_CurrentRect.max = Vector2.Scale(scale,s_StartRect.max - scalePivotLocal) + scalePivotLocal;
if(anchorPivot)
{
rect.min = s_CurrentRect.min;
rect.max = s_CurrentRect.max;
}else{
rect.position = Vector2.Scale(scale,s_StartRect.position);
rect.size = Vector2.Scale(scale,s_StartRect.size);
Vector2 newPivot = new Vector2(s_CurrentRect.xMin + (s_CurrentRect.xMax - s_CurrentRect.xMin) * s_StartPivot.x,
s_CurrentRect.yMin + (s_CurrentRect.yMax - s_CurrentRect.yMin) * s_StartPivot.y);
position = s_StartPosition + rotation * newPivot;
}
}
}
}
}
}
return rect;
}
static Rect MoveHandlesGUI(Rect rect, ref Vector3 position, Quaternion rotation, bool anchorPivot = false)
{
int controlID = GUIUtility.GetControlID("RectMoveHandles".GetHashCode(), FocusType.Passive);
EventType eventType = Event.current.GetTypeForControl(controlID);
if(eventType == EventType.MouseDown)
{
s_StartRect = rect;
}
EditorGUI.BeginChangeCheck();
Vector3 newPosition = HandlesExtra.Slider2D(controlID, position, null);
if(EditorGUI.EndChangeCheck())
{
if(anchorPivot)
{
Vector2 delta = Quaternion.Inverse(rotation) * (newPosition - position);
rect.min = s_StartRect.min + delta;
rect.max = s_StartRect.max + delta;
}else{
position = newPosition;
}
}
if(eventType == EventType.Layout)
{
Vector2 mousePositionRectSpace = Vector2.zero;
mousePositionRectSpace = Quaternion.Inverse(rotation) * (HandlesExtra.GUIToWorld(Event.current.mousePosition) - position);
if(rect.Contains(mousePositionRectSpace,true))
{
HandleUtility.AddControl(controlID, 0f);
}
}
if(eventType == EventType.Repaint)
{
if((!Event.current.alt &&
HandleUtility.nearestControl == controlID &&
GUIUtility.hotControl == 0) ||
GUIUtility.hotControl == controlID)
{
Rect cursorRect = new Rect(0f,0f,20f,20f);
cursorRect.center = Event.current.mousePosition;
EditorGUIUtility.AddCursorRect(cursorRect, MouseCursor.MoveArrow, controlID);
}
}
return rect;
}
static Quaternion RotationHandlesGUI(Rect rect, Vector3 pivot, Quaternion rotation)
{
Vector3 eulerAngles = rotation.eulerAngles;
for (int i = 0; i <= 2; i += 2)
{
for (int j = 0; j <= 2; j += 2)
{
Vector3 rectPointInWorld = GetRectPointInWorld(rect, pivot, rotation, i, j);
float handleSize = 0.05f * Handles.matrix.m00;
int controlID = GUIUtility.GetControlID("RectRotationHandles".GetHashCode(), FocusType.Passive);
EditorGUI.BeginChangeCheck();
Vector3 outwardsDir = rotation * Vector3.right * (float)(i - 1) * Mathf.Sign(rect.width);
Vector3 outwardsDir2 = rotation * Vector3.up * (float)(j - 1) * Mathf.Sign(rect.height);
float num = RotationSlider(controlID, rectPointInWorld, eulerAngles.z, pivot, rotation * Vector3.forward, outwardsDir, outwardsDir2, handleSize, null, Vector2.zero);
if (EditorGUI.EndChangeCheck())
{
if (Event.current.shift)
{
num = Mathf.Round((num - eulerAngles.z) / 15f) * 15f + eulerAngles.z;
}
eulerAngles.z = num;
rotation = Quaternion.Euler(eulerAngles);
}
}
}
return rotation;
}
public static void RenderRect(Rect rect, Vector3 position, Quaternion rotation, Color color, float rectAlpha, float outlineAlpha)
{
if (Event.current.type != EventType.Repaint)
{
return;
}
Vector3[] corners = new Vector3[4];
for (int i = 0; i < 4; i++)
{
Vector3 point = GetLocalRectPoint(rect, i);
corners[i] = rotation * point + position;
}
Vector3[] points = new Vector3[]
{
corners[0],
corners[1],
corners[2],
corners[3],
corners[0]
};
Color l_color = Handles.color;
Handles.color = color;
Vector2 offset = new Vector2(1f, 1f);
if(!Camera.current)
{
offset.y *= -1;
}
DrawPolyLineWithOffset(color * 0.5f, new Vector2(1f, 1f), points);
Handles.DrawSolidRectangleWithOutline(points,new Color(1f,1f,1f,rectAlpha),new Color(1f,1f,1f,outlineAlpha));
Handles.color = l_color;
}
static void DrawPolyLineWithOffset(Color lineColor, Vector2 screenOffset, params Vector3[] points)
{
if (Event.current.type != EventType.Repaint)
{
return;
}
if (s_TempVectors.Length != points.Length)
{
s_TempVectors = new Vector3[points.Length];
}
for (int i = 0; i < points.Length; i++)
{
s_TempVectors[i] = (Vector3)HandlesExtra.GUIToWorld(HandleUtility.WorldToGUIPoint(points[i]) + screenOffset);
}
Color color = Handles.color;
Handles.color = lineColor;
DrawPolyLine(s_TempVectors);
Handles.color = color;
}
static void DrawPolyLine(params Vector3[] points)
{
if (Event.current.type != EventType.Repaint)
{
return;
}
Color c = Handles.color;
HandlesExtra.ApplyWireMaterial();
GL.PushMatrix ();
GL.MultMatrix (Handles.matrix);
GL.Begin (1);
GL.Color (c);
for (int i = 1; i < points.Length; i++)
{
GL.Vertex (points [i]);
GL.Vertex (points [i - 1]);
}
GL.End ();
GL.PopMatrix ();
}
static Rect PivotHandleGUI(Rect rect, ref Vector3 position, Quaternion rotation)
{
int controlID = GUIUtility.GetControlID("RectPivotHandle".GetHashCode(), FocusType.Passive);
EventType eventType = Event.current.GetTypeForControl(controlID);
EditorGUI.BeginChangeCheck();
Vector3 newPosition = HandlesExtra.Slider2D(controlID, position, HandlesExtra.PivotCap);
if (EditorGUI.EndChangeCheck())
{
Vector3 pivotDelta = (newPosition - position);
Vector2 pivotDeltaLocal = Quaternion.Inverse(rotation) * pivotDelta;
position = newPosition;
rect.position -= pivotDeltaLocal;
}
if(eventType == EventType.Layout)
{
float radius = HandleUtility.GetHandleSize(position) / 2f;
if(Camera.current)
{
radius = HandleUtility.GetHandleSize(position) / 10f;
}
HandleUtility.AddControl(controlID, HandleUtility.DistanceToCircle(position,radius));
}
if(eventType == EventType.Repaint)
{
if ((HandleUtility.nearestControl == controlID && GUIUtility.hotControl == 0) || GUIUtility.hotControl == controlID)
{
Rect cursorRect = new Rect(0,0, 20f, 20f);
cursorRect.center = Event.current.mousePosition;
EditorGUIUtility.AddCursorRect(cursorRect, MouseCursor.Arrow, controlID);
}
}
return rect;
}
static float AngleAroundAxis(Vector3 dirA, Vector3 dirB, Vector3 axis)
{
dirA = Vector3.ProjectOnPlane(dirA, axis);
dirB = Vector3.ProjectOnPlane(dirB, axis);
float num = Vector3.Angle(dirA, dirB);
return num * (float)((Vector3.Dot(axis, Vector3.Cross(dirA, dirB)) >= 0f) ? 1 : -1);
}
static float RotationSlider(int controlID, Vector3 cornerPos, float rotation, Vector3 pivot, Vector3 handleDir, Vector3 outwardsDir1, Vector3 outwardsDir2, float handleSize, HandlesExtra.CapFunction drawFunc, Vector2 snap)
{
EventType eventType = Event.current.GetTypeForControl(controlID);
Vector3 b = outwardsDir1 + outwardsDir2;
Vector3 guiCornerPos = HandleUtility.WorldToGUIPoint(cornerPos);
Vector3 b2 = ((Vector3)HandleUtility.WorldToGUIPoint(cornerPos + b) - guiCornerPos).normalized * 15f;
cornerPos = HandlesExtra.GUIToWorld(guiCornerPos + b2);
Vector3 newPosition = HandlesExtra.Slider2D(controlID, cornerPos, drawFunc);
rotation = rotation - AngleAroundAxis(newPosition - pivot, cornerPos - pivot, handleDir);
if(eventType == EventType.Layout)
{
HandleUtility.AddControl(controlID, HandleUtility.DistanceToCircle(cornerPos, HandleUtility.GetHandleSize(cornerPos + b) / 10f));
}
if(eventType == EventType.Repaint)
{
if((HandleUtility.nearestControl == controlID && GUIUtility.hotControl == 0) || GUIUtility.hotControl == controlID)
{
Rect cursorRect = new Rect(0, 0, 20f, 20f);
cursorRect.center = Event.current.mousePosition;
EditorGUIUtility.AddCursorRect(cursorRect, MouseCursor.RotateArrow, controlID);
}
}
return rotation;
}
static Vector3 SideSlider(int controlID, Vector3 position, Vector3 sideVector, Vector3 direction, HandlesExtra.CapFunction drawFunc)
{
Vector3 vector = HandlesExtra.Slider2D(controlID, position,drawFunc);
vector = position + Vector3.Project(vector - position, direction);
return vector;
}
static MouseCursor GetScaleCursor(Vector2 direction)
{
float num = Mathf.Atan2(direction.x, direction.y) * 57.29578f;
if (num < 0f)
{
num = 360f + num;
}
if (num < 27.5f)
{
return MouseCursor.ResizeVertical;
}
if (num < 72.5f)
{
return MouseCursor.ResizeUpRight;
}
if (num < 117.5f)
{
return MouseCursor.ResizeHorizontal;
}
if (num < 162.5f)
{
return MouseCursor.ResizeUpLeft;
}
if (num < 207.5f)
{
return MouseCursor.ResizeVertical;
}
if (num < 252.5f)
{
return MouseCursor.ResizeUpRight;
}
if (num < 297.5f)
{
return MouseCursor.ResizeHorizontal;
}
if (num < 342.5f)
{
return MouseCursor.ResizeUpLeft;
}
return MouseCursor.ResizeVertical;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Java.Lang;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Media;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace Parse.Internal {
/// <summary>
/// A simple implementation of the NotificationCompat class from Android.Support.V4.
/// </summary>
/// <remarks>
/// It only differentiates between devices before and after JellyBean because the only extra feature
/// that we currently support between the two device types is BigTextStyle notifications.
/// This class takes advantage of lazy class loading to eliminate warnings of type
/// 'Could not find class...'
/// </remarks>
internal class NotificationCompat {
#pragma warning disable 612, 618
public const int PriorityDefault = 0;
private static NotificationCompatImpl impl;
private static NotificationCompatImpl Impl {
get {
if (impl == null) {
if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.JellyBean) {
impl = new NotificationCompatPostJellyBean();
} else {
impl = new NotificationCompatImplBase();
}
}
return impl;
}
}
public interface NotificationCompatImpl {
Notification Build(Builder b);
}
internal class NotificationCompatImplBase : NotificationCompatImpl {
public Notification Build(Builder b) {
Notification result = b.Notification;
result.SetLatestEventInfo(b.Context, b.ContentTitle, b.ContentText, b.ContentIntent);
return result;
}
}
internal class NotificationCompatPostJellyBean : NotificationCompatImpl {
public Notification Build(Builder b) {
Notification.Builder builder = new Notification.Builder(b.Context);
builder.SetContentTitle(b.ContentTitle)
.SetContentText(b.ContentText)
.SetTicker(b.Notification.TickerText)
.SetSmallIcon(b.Notification.Icon, b.Notification.IconLevel)
.SetContentIntent(b.ContentIntent)
.SetDeleteIntent(b.Notification.DeleteIntent)
.SetAutoCancel((b.Notification.Flags & NotificationFlags.AutoCancel) != 0)
.SetLargeIcon(b.LargeIcon)
.SetDefaults(b.Notification.Defaults);
if (b.Style != null) {
if (b.Style is BigTextStyle) {
BigTextStyle staticStyle = b.Style as BigTextStyle;
Notification.BigTextStyle style = new Notification.BigTextStyle(builder);
style.SetBigContentTitle(staticStyle.BigContentTitle)
.BigText(staticStyle.bigText);
if (staticStyle.SummaryTextSet) {
style.SetSummaryText(staticStyle.SummaryText);
}
}
}
return builder.Build();
}
}
/// <summary>
/// Builder class for <see cref="NotificationCompat"/> objects.
/// </summary>
/// <seealso href="http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html"/>
/// <remarks>
/// Allows easier control over all the flags, as well as help constructing the typical notification layouts.
/// </remarks>
public class Builder {
private const int MaxCharSequenceLength = 5 * 1024;
public Context Context { get; private set; }
public ICharSequence ContentTitle { get; private set; }
public ICharSequence ContentText { get; private set; }
public PendingIntent ContentIntent { get; private set; }
public Bitmap LargeIcon { get; private set; }
public int Priority { get; private set; }
public Style Style { get; private set; }
[Obsolete]
public Notification Notification { get; private set; }
public Builder(Context context) {
Context = context;
Notification = new Notification();
Notification.When = Java.Lang.JavaSystem.CurrentTimeMillis();
Notification.AudioStreamType = Stream.NotificationDefault;
Priority = PriorityDefault;
}
public Builder SetWhen(long when) {
Notification.When = when;
return this;
}
public Builder SetSmallIcon(int icon) {
Notification.Icon = icon;
return this;
}
public Builder SetSmallIcon(int icon, int iconLevel) {
Notification.Icon = icon;
Notification.IconLevel = iconLevel;
return this;
}
public Builder SetContentTitle(ICharSequence title) {
ContentTitle = limitCharSequenceLength(title);
return this;
}
public Builder SetContentText(ICharSequence text) {
ContentText = limitCharSequenceLength(text);
return this;
}
public Builder SetContentIntent(PendingIntent intent) {
ContentIntent = intent;
return this;
}
public Builder SetDeleteIntent(PendingIntent intent) {
Notification.DeleteIntent = intent;
return this;
}
public Builder SetTicker(ICharSequence tickerText) {
Notification.TickerText = limitCharSequenceLength(tickerText);
return this;
}
public Builder SetLargeIcon(Bitmap icon) {
LargeIcon = icon;
return this;
}
public Builder SetAutoCancel(bool autoCancel) {
setFlag(NotificationFlags.AutoCancel, autoCancel);
return this;
}
public Builder SetDefaults(NotificationDefaults defaults) {
Notification.Defaults = defaults;
if ((defaults & NotificationDefaults.Lights) != 0) {
Notification.Flags |= NotificationFlags.ShowLights;
}
return this;
}
private void setFlag(NotificationFlags mask, bool value) {
if (value) {
Notification.Flags |= mask;
} else {
Notification.Flags &= ~mask;
}
}
public Builder SetPriority(int pri) {
Priority = pri;
return this;
}
public Builder SetStyle(Style style) {
if (Style != style) {
Style = style;
if (Style != null) {
Style.SetBuilder(this);
}
}
return this;
}
public Notification Build() {
return Impl.Build(this);
}
private static ICharSequence limitCharSequenceLength(ICharSequence cs) {
if (cs == null) {
return cs;
}
if (cs.Length() > MaxCharSequenceLength) {
cs = cs.SubSequenceFormatted(0, MaxCharSequenceLength);
}
return cs;
}
}
/// <summary>
/// An object that can apply a rich notification style to a <see cref="NotificationCompat.Builder"/> object.
/// </summary>
public abstract class Style {
protected Builder builder;
public ICharSequence BigContentTitle { get; protected set; }
public ICharSequence SummaryText { get; protected set; }
private bool summaryTextSet = false;
public bool SummaryTextSet {
get { return summaryTextSet; }
protected set { summaryTextSet = value; }
}
public void SetBuilder(Builder builder) {
if (this.builder != builder) {
this.builder = builder;
if (this.builder != null) {
this.builder.SetStyle(this);
}
}
}
public Notification Build() {
Notification notification = null;
if (builder != null) {
notification = builder.Build();
}
return notification;
}
}
public class BigTextStyle : Style {
internal ICharSequence bigText;
public BigTextStyle() {
}
public BigTextStyle(Builder builder) {
SetBuilder(builder);
}
/// <summary>
/// Overrides <see cref="Builder.ContentTitle"/> in the big form of the template.
/// </summary>
/// <remarks>
/// This defaults to the value passed to SetContentTitle().
/// </remarks>
/// <param name="title"></param>
/// <returns></returns>
public BigTextStyle SetBigContentTitle(ICharSequence title) {
BigContentTitle = title;
return this;
}
/// <summary>
/// Set the first line of text after the detail section in the big form of the template.
/// </summary>
/// <param name="summaryText"></param>
/// <returns></returns>
public BigTextStyle SetSummaryText(ICharSequence summaryText) {
SummaryText = summaryText;
SummaryTextSet = true;
return this;
}
/// <summary>
/// Provide the longer text to be displayed in the big form of the
/// template in place of the content text.
/// </summary>
/// <param name="bigText"></param>
/// <returns></returns>
public BigTextStyle BigText(ICharSequence bigText) {
this.bigText = bigText;
return this;
}
}
}
#pragma warning restore 612, 618
}
| |
using Newtonsoft.Json.Linq;
using RedditSharp.Things;
using System;
using System.Net;
using System.Security.Authentication;
using System.Text;
namespace RedditSharp
{
public class AuthProvider
{
public const string AccessUrl = "https://ssl.reddit.com/api/v1/access_token";
private const string OauthGetMeUrl = "https://oauth.reddit.com/api/v1/me";
private const string RevokeUrl = "https://www.reddit.com/api/v1/revoke_token";
public static string OAuthToken { get; set; }
public static string RefreshToken { get; set; }
[Flags]
public enum Scope
{
none = 0x0,
identity = 0x1,
edit = 0x2,
flair = 0x4,
history = 0x8,
modconfig = 0x10,
modflair = 0x20,
modlog = 0x40,
modposts = 0x80,
modwiki = 0x100,
mysubreddits = 0x200,
privatemessages = 0x400,
read = 0x800,
report = 0x1000,
save = 0x2000,
submit = 0x4000,
subscribe = 0x8000,
vote = 0x10000,
wikiedit = 0x20000,
wikiread = 0x40000
}
private IWebAgent _webAgent;
private readonly string _redirectUri;
private readonly string _clientId;
private readonly string _clientSecret;
/// <summary>
/// Allows use of reddit's OAuth interface, using an app set up at https://ssl.reddit.com/prefs/apps/.
/// </summary>
/// <param name="clientId">Granted by reddit as part of app.</param>
/// <param name="clientSecret">Granted by reddit as part of app.</param>
/// <param name="redirectUri">Selected as part of app. Reddit will send users back here.</param>
public AuthProvider(string clientId, string clientSecret, string redirectUri)
{
_clientId = clientId;
_clientSecret = clientSecret;
_redirectUri = redirectUri;
_webAgent = new WebAgent();
}
/// <summary>
/// Allows use of reddit's OAuth interface, using an app set up at https://ssl.reddit.com/prefs/apps/.
/// </summary>
/// <param name="clientId">Granted by reddit as part of app.</param>
/// <param name="clientSecret">Granted by reddit as part of app.</param>
/// <param name="redirectUri">Selected as part of app. Reddit will send users back here.</param>
/// <param name="agent">Implementation of IWebAgent to use to make requests.</param>
public AuthProvider(string clientId, string clientSecret, string redirectUri,IWebAgent agent)
{
_clientId = clientId;
_clientSecret = clientSecret;
_redirectUri = redirectUri;
_webAgent = agent;
}
/// <summary>
/// Creates the reddit OAuth2 Url to redirect the user to for authorization.
/// </summary>
/// <param name="state">Used to verify that the user received is the user that was sent</param>
/// <param name="scope">Determines what actions can be performed against the user.</param>
/// <param name="permanent">Set to true for access lasting longer than one hour.</param>
/// <returns></returns>
public string GetAuthUrl(string state, Scope scope, bool permanent = false)
{
return string.Format("https://ssl.reddit.com/api/v1/authorize?client_id={0}&response_type=code&state={1}&redirect_uri={2}&duration={3}&scope={4}", _clientId, state, _redirectUri, permanent ? "permanent" : "temporary", scope.ToString().Replace(" ",""));
}
/// <summary>
/// Gets the OAuth token for the user associated with the provided code.
/// </summary>
/// <param name="code">Sent by reddit as a parameter in the return uri.</param>
/// <param name="isRefresh">Set to true for refresh requests.</param>
/// <returns></returns>
public string GetOAuthToken(string code, bool isRefresh = false)
{
if (Type.GetType("Mono.Runtime") != null)
ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true;
_webAgent.Cookies = new CookieContainer();
var request = _webAgent.CreatePost(AccessUrl);
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(_clientId + ":" + _clientSecret));
var stream = request.GetRequestStream();
if (isRefresh)
{
_webAgent.WritePostBody(stream, new
{
grant_type = "refresh_token",
refresh_token = code
});
}
else
{
_webAgent.WritePostBody(stream, new
{
grant_type = "authorization_code",
code,
redirect_uri = _redirectUri
});
}
stream.Close();
var json = _webAgent.ExecuteRequest(request);
if (json["access_token"] != null)
{
if (json["refresh_token"] != null)
RefreshToken = json["refresh_token"].ToString();
OAuthToken = json["access_token"].ToString();
return json["access_token"].ToString();
}
throw new AuthenticationException("Could not log in.");
}
/// <summary>
/// Gets the OAuth token for the user.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The user's password.</param>
/// <returns>The access token</returns>
public string GetOAuthToken(string username, string password)
{
if (Type.GetType("Mono.Runtime") != null)
ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true;
_webAgent.Cookies = new CookieContainer();
var request = _webAgent.CreatePost(AccessUrl);
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(_clientId + ":" + _clientSecret));
var stream = request.GetRequestStream();
_webAgent.WritePostBody(stream, new
{
grant_type = "password",
username,
password,
redirect_uri = _redirectUri
});
stream.Close();
var json = _webAgent.ExecuteRequest(request);
if (json["access_token"] != null)
{
if (json["refresh_token"] != null)
RefreshToken = json["refresh_token"].ToString();
OAuthToken = json["access_token"].ToString();
return json["access_token"].ToString();
}
throw new AuthenticationException("Could not log in.");
}
/// <summary>
/// revokes an oauth token
/// </summary>
/// <param name="token">The oauth token..</param>
/// <param name="isRefresh">Set to true for refresh token.</param>
/// <returns>The access token</returns>
public void RevokeToken(string token, bool isRefresh)
{
string tokenType = isRefresh ? "refresh_token" : "access_token";
var request = _webAgent.CreatePost(RevokeUrl);
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(_clientId + ":" + _clientSecret));
var stream = request.GetRequestStream();
_webAgent.WritePostBody(stream, new
{
token = token,
token_type = tokenType
});
stream.Close();
_webAgent.ExecuteRequest(request);
}
/// <summary>
/// Gets a user authenticated by OAuth2.
/// </summary>
/// <param name="accessToken">Obtained using GetOAuthToken</param>
/// <returns></returns>
[Obsolete("Reddit.InitOrUpdateUser is preferred")]
public AuthenticatedUser GetUser(string accessToken)
{
var request = _webAgent.CreateGet(OauthGetMeUrl);
request.Headers["Authorization"] = string.Format("bearer {0}", accessToken);
var response = (HttpWebResponse)request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var thingjson = "{\"kind\": \"t2\", \"data\": " + result + "}";
var json = JObject.Parse(thingjson);
return new AuthenticatedUser().Init(new Reddit(), json, _webAgent);
}
}
}
| |
using System;
using UnityEngine;
public class FxmTestMain : MonoBehaviour
{
public static FxmTestMain inst;
public GUISkin m_GuiMainSkin;
public FxmTestMouse m_FXMakerMouse;
public FxmTestControls m_FXMakerControls;
public AnimationCurve m_SimulateArcCurve;
public GameObject m_GroupList;
public int m_CurrentGroupIndex;
public GameObject m_PrefabList;
public int m_CurrentPrefabIndex;
public bool m_bAutoChange = true;
public bool m_bAutoSetting = true;
protected GameObject m_OriginalEffectObject;
protected GameObject m_InstanceEffectObject;
private FxmTestMain()
{
FxmTestMain.inst = this;
}
public FxmTestMouse GetFXMakerMouse()
{
if (this.m_FXMakerMouse == null)
{
this.m_FXMakerMouse = base.GetComponentInChildren<FxmTestMouse>();
}
return this.m_FXMakerMouse;
}
public FxmTestControls GetFXMakerControls()
{
if (this.m_FXMakerControls == null)
{
this.m_FXMakerControls = base.GetComponent<FxmTestControls>();
}
return this.m_FXMakerControls;
}
private void Awake()
{
NgUtil.LogDevelop("Awake - FXMakerMain");
this.GetFXMakerControls().enabled = true;
}
private void OnEnable()
{
NgUtil.LogDevelop("OnEnable - FXMakerMain");
}
private void Start()
{
if (0 < this.m_GroupList.transform.childCount)
{
this.m_PrefabList = this.m_GroupList.transform.GetChild(0).gameObject;
}
if (this.m_PrefabList != null && 0 < this.m_PrefabList.transform.childCount)
{
this.m_OriginalEffectObject = this.m_PrefabList.transform.GetChild(0).gameObject;
this.CreateCurrentInstanceEffect(true);
}
}
private void Update()
{
}
public void OnGUI()
{
GUI.skin = this.m_GuiMainSkin;
float num = (float)(Screen.width / 7);
float num2 = (float)(Screen.height / 10);
this.m_FXMakerControls.OnGUIControl();
if (GUI.Button(new Rect(0f, 0f, num, num2), "GPrev"))
{
this.ChangeGroup(false);
}
if (GUI.Button(new Rect(num + 10f, 0f, num, num2), "GNext"))
{
this.ChangeGroup(true);
}
GUI.Box(new Rect(0f, num2 + 10f, num * 2f + 10f, 20f), this.m_GroupList.transform.GetChild(this.m_CurrentGroupIndex).name, GUI.skin.FindStyle("Hierarchy_Button"));
if (GUI.Button(new Rect((float)Screen.width - num * 2f - 10f, 0f, num, num2), "EPrev"))
{
this.ChangeEffect(false);
}
if (GUI.Button(new Rect((float)Screen.width - num, 0f, num, num2), "ENext"))
{
this.ChangeEffect(true);
}
this.m_bAutoChange = GUI.Toggle(new Rect((float)Screen.width - num, num2 + 10f, num, 20f), this.m_bAutoChange, "AutoChange");
bool flag = GUI.Toggle(new Rect((float)Screen.width - num * 2f - 10f, num2 + 10f, num, 20f), this.m_bAutoSetting, "AutoSetting");
if (flag != this.m_bAutoSetting)
{
this.m_bAutoSetting = flag;
if (!flag)
{
this.m_FXMakerControls.SetDefaultSetting();
}
}
float num3 = GUI.VerticalSlider(new Rect(10f, num2 + 10f + 30f, 25f, (float)Screen.height - (num2 + 10f + 50f) - this.GetFXMakerControls().GetActionToolbarRect().height), this.GetFXMakerMouse().m_fDistance, this.GetFXMakerMouse().m_fDistanceMin, this.GetFXMakerMouse().m_fDistanceMax);
if (num3 != this.GetFXMakerMouse().m_fDistance)
{
this.GetFXMakerMouse().SetDistance(num3);
}
}
public void ChangeEffect(bool bNext)
{
if (this.m_PrefabList == null)
{
return;
}
if (bNext)
{
if (this.m_CurrentPrefabIndex >= this.m_PrefabList.transform.childCount - 1)
{
this.ChangeGroup(true);
return;
}
this.m_CurrentPrefabIndex++;
}
else
{
if (this.m_CurrentPrefabIndex == 0)
{
this.ChangeGroup(false);
return;
}
this.m_CurrentPrefabIndex--;
}
this.m_OriginalEffectObject = this.m_PrefabList.transform.GetChild(this.m_CurrentPrefabIndex).gameObject;
this.CreateCurrentInstanceEffect(true);
}
public bool ChangeGroup(bool bNext)
{
if (bNext)
{
if (this.m_CurrentGroupIndex < this.m_GroupList.transform.childCount - 1)
{
this.m_CurrentGroupIndex++;
}
else
{
this.m_CurrentGroupIndex = 0;
}
}
else if (this.m_CurrentGroupIndex == 0)
{
this.m_CurrentGroupIndex = this.m_GroupList.transform.childCount - 1;
}
else
{
this.m_CurrentGroupIndex--;
}
this.m_PrefabList = this.m_GroupList.transform.GetChild(this.m_CurrentGroupIndex).gameObject;
if (this.m_PrefabList != null && 0 < this.m_PrefabList.transform.childCount)
{
this.m_CurrentPrefabIndex = 0;
this.m_OriginalEffectObject = this.m_PrefabList.transform.GetChild(this.m_CurrentPrefabIndex).gameObject;
this.CreateCurrentInstanceEffect(true);
return true;
}
return true;
}
public bool IsCurrentEffectObject()
{
return this.m_OriginalEffectObject != null;
}
public GameObject GetOriginalEffectObject()
{
return this.m_OriginalEffectObject;
}
public void ChangeRoot_OriginalEffectObject(GameObject newRoot)
{
this.m_OriginalEffectObject = newRoot;
}
public void ChangeRoot_InstanceEffectObject(GameObject newRoot)
{
this.m_InstanceEffectObject = newRoot;
}
public GameObject GetInstanceEffectObject()
{
return this.m_InstanceEffectObject;
}
public void ClearCurrentEffectObject(GameObject effectRoot, bool bClearEventObject)
{
if (bClearEventObject)
{
GameObject instanceRoot = this.GetInstanceRoot();
if (instanceRoot != null)
{
NgObject.RemoveAllChildObject(instanceRoot, true);
}
}
NgObject.RemoveAllChildObject(effectRoot, true);
this.m_OriginalEffectObject = null;
this.CreateCurrentInstanceEffect(null);
}
public void CreateCurrentInstanceEffect(bool bRunAction)
{
FxmTestSetting component = this.m_PrefabList.GetComponent<FxmTestSetting>();
if (this.m_bAutoSetting && component != null)
{
this.m_FXMakerControls.AutoSetting(component.m_nPlayIndex, component.m_nTransIndex, component.m_nTransAxis, component.m_fDistPerTime, component.m_nRotateIndex, component.m_nMultiShotCount, component.m_fTransRate, component.m_fStartPosition);
}
NgUtil.LogDevelop("CreateCurrentInstanceEffect() - bRunAction - " + bRunAction);
bool flag = this.CreateCurrentInstanceEffect(this.m_OriginalEffectObject);
if (flag && bRunAction)
{
this.m_FXMakerControls.RunActionControl();
}
}
public GameObject GetInstanceRoot()
{
return NcEffectBehaviour.GetRootInstanceEffect();
}
private bool CreateCurrentInstanceEffect(GameObject gameObj)
{
NgUtil.LogDevelop("CreateCurrentInstanceEffect() - gameObj - " + gameObj);
GameObject instanceRoot = this.GetInstanceRoot();
NgObject.RemoveAllChildObject(instanceRoot, true);
if (gameObj != null)
{
GameObject gameObject = (GameObject)UnityEngine.Object.Instantiate(gameObj);
NcEffectBehaviour.PreloadTexture(gameObject);
gameObject.transform.parent = instanceRoot.transform;
this.m_InstanceEffectObject = gameObject;
NgObject.SetActiveRecursively(gameObject, true);
this.m_FXMakerControls.SetStartTime();
return true;
}
this.m_InstanceEffectObject = null;
return false;
}
private void OnDestroy()
{
this.m_SimulateArcCurve = null;
this.m_GroupList = null;
this.m_PrefabList = null;
this.m_OriginalEffectObject = null;
this.m_InstanceEffectObject = null;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Caching.Resources;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Diagnostics;
// Every member of this class is thread-safe.
//
// Derived classes begin monitoring during construction, so that a user can know if the
// dependency changed any time after construction. For example, suppose we have a
// FileChangeMonitor class that derives from ChangeMonitor. A user might create an instance
// of FileChangeMonitor for an XML file, and then read the file to populate an object representation.
// The user would then cache the object with the FileChangeMonitor. The user could optionally check the
// HasChanged property of the FileChangeMonitor, to see if the XML file changed while the object
// was being populated, and if it had changed, they could call Dispose and start over, without
// inserting the item into the cache. However, in a multi-threaded environment, for cleaner, easier
// to maintain code, it's usually appropriate to just insert without checking HasChanged, since the
// cache implementer will handle this for you, and the next thread to attempt to get the object
// will recreate and insert it.
//
// The following contract must be followed by derived classes, cache implementers, and users of the
// derived class:
//
// 1. The constructor of a derived class must set UniqueId, begin monitoring for dependency
// changes, and call InitializationComplete before returning. If a dependency changes
// before initialization is complete, for example, if a dependent cache key is not found
// in the cache, the constructor must invoke OnChanged. The constructor can only call
// Dispose after InitializationComplete is called, because Dispose will throw
// InvalidOperationException if initialization is not complete.
// 2. Once constructed, the user must either insert the ChangeMonitor into an ObjectCache, or
// if they're not going to use it, they must call Dispose.
// 3. Once inserted into an ObjectCache, the ObjectCache implementation must ensure that the
// ChangeMonitor is eventually disposed. Even if the insert is invalid, and results in an
// exception being thrown, the ObjectCache implementation must call Dispose. If this we're not
// a requirement, users of the ChangeMonitor would need exception handling around each insert
// into the cache that carefully ensures the dependency is disposed. While this would work, we
// think it is better to put this burden on the ObjectCache implementer, since users are far more
// numerous than cache implementers.
// 4. After the ChangeMonitor is inserted into a cache, the ObjectCache implementer must call
// NotifyOnChanged, passing in an OnChangedCallback. NotifyOnChanged can only be called once,
// and will throw InvalidOperationException on subsequent calls. If the dependency has already
// changed, the OnChangedCallback will be called when NotifyOnChanged is called. Otherwise, the
// OnChangedCallback will be called exactly once, when OnChanged is invoked or when Dispose
// is invoked, which ever happens first.
// 5. The OnChangedCallback provided by the cache implementer should remove the cache entry, and specify
// a reason of CacheEntryRemovedReason.DependencyChanged. Care should be taken to remove the specific
// entry having this dependency, and not it's replacement, which will have the same key.
// 6. In general, it is okay for OnChanged to be called at any time. If OnChanged is called before
// NotifyOnChanged is called, the "state" from the original call to OnChanged will be saved, and the
// callback to NotifyOnChange will be called immediately when NotifyOnChanged is invoked.
// 7. A derived class must implement Dispose(bool disposing) to release all managed and unmanaged
// resources when "disposing" is true. Dispose(true) is only called once, when the instance is
// disposed. The derived class must not call Dispose(true) directly--it should only be called by
// the ChangeMonitor class, when disposed. Although a derived class could implement a finalizer and
// invoke Dispose(false), this is generally not necessary. Dependency monitoring is typically performed
// by a service that maintains a reference to the ChangeMonitor, preventing it from being garbage collected,
// and making finalizers useless. To help prevent leaks, when a dependency changes, OnChanged disposes
// the ChangeMonitor, unless initialization has not yet completed.
// 8. Dispose() must be called, and is designed to be called, in one of the following three ways:
// - The user must call Dispose() if they decide not to insert the ChangeMonitor into a cache. Otherwise,
// the ChangeMonitor will continue monitoring for changes and be unavailable for garbage collection.
// - The cache implementor is responsible for calling Dispose() once an attempt is made to insert it.
// Even if the insert throws, the cache implementor must dispose the dependency.
// Even if the entry is removed, the cache implementor must dispose the dependency.
// - The OnChanged method will automatically call Dispose if initialization is complete. Otherwise, when
// the derived class' constructor calls InitializationComplete, the instance will be automatically disposed.
//
// Before inserted into the cache, the user must ensure the dependency is disposed. Once inserted into the
// cache, the cache implementer must ensure that Dispose is called, even if the insert fails. After being inserted
// into a cache, the user should not dispose the dependency. When Dispose is called, it is treated as if the dependency
// changed, and OnChanged is automatically invoked.
// 9. HasChanged will be true after OnChanged is called by the derived class, regardless of whether an OnChangedCallback has been set
// by a call to NotifyOnChanged.
namespace System.Runtime.Caching
{
public abstract class ChangeMonitor : IDisposable
{
private const int INITIALIZED = 0x01; // initialization complete
private const int CHANGED = 0x02; // dependency changed
private const int INVOKED = 0x04; // OnChangedCallback has been invoked
private const int DISPOSED = 0x08; // Dispose(true) called, or about to be called
private readonly static object s_NOT_SET = new object();
private SafeBitVector32 _flags;
private OnChangedCallback _onChangedCallback;
private object _onChangedState = s_NOT_SET;
// The helper routines (OnChangedHelper and DisposeHelper) are used to prevent
// an infinite loop, where Dispose calls OnChanged and OnChanged calls Dispose.
[SuppressMessage("Microsoft.Performance", "CA1816:DisposeMethodsShouldCallSuppressFinalize", Justification = "Grandfathered suppression from original caching code checkin")]
private void DisposeHelper()
{
// if not initialized, return without doing anything.
if (_flags[INITIALIZED])
{
if (_flags.ChangeValue(DISPOSED, true))
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
// The helper routines (OnChangedHelper and DisposeHelper) are used to prevent
// an infinite loop, where Dispose calls OnChanged and OnChanged calls Dispose.
private void OnChangedHelper(object state)
{
_flags[CHANGED] = true;
// the callback is only invoked once, after NotifyOnChanged is called, so
// remember "state" on the first call and use it when invoking the callback
Interlocked.CompareExchange(ref _onChangedState, state, s_NOT_SET);
OnChangedCallback onChangedCallback = _onChangedCallback;
if (onChangedCallback != null)
{
// only invoke the callback once
if (_flags.ChangeValue(INVOKED, true))
{
onChangedCallback(_onChangedState);
}
}
}
//
// protected members
//
// Derived classes must implement this. When "disposing" is true,
// all managed and unmanaged resources are disposed and any references to this
// object are released so that the ChangeMonitor can be garbage collected.
// It is guaranteed that ChangeMonitor.Dispose() will only invoke
// Dispose(bool disposing) once.
protected abstract void Dispose(bool disposing);
// Derived classes must call InitializationComplete
protected void InitializationComplete()
{
_flags[INITIALIZED] = true;
// If the dependency has already changed, or someone tried to dispose us, then call Dispose now.
Debug.Assert(_flags[INITIALIZED], "It is critical that INITIALIZED is set before CHANGED is checked below");
if (_flags[CHANGED])
{
Dispose();
}
}
// Derived classes call OnChanged when the dependency changes. Optionally,
// they may pass state which will be passed to the OnChangedCallback. The
// OnChangedCallback is only invoked once, and only after NotifyOnChanged is
// called by the cache implementer. OnChanged is also invoked when the instance
// is disposed, but only has an affect if the callback has not already been invoked.
protected void OnChanged(object state)
{
OnChangedHelper(state);
// OnChanged will also invoke Dispose, but only after initialization is complete
Debug.Assert(_flags[CHANGED], "It is critical that CHANGED is set before INITIALIZED is checked below.");
if (_flags[INITIALIZED])
{
DisposeHelper();
}
}
//
// public members
//
// set to true when the dependency changes, specifically, when OnChanged is called.
public bool HasChanged { get { return _flags[CHANGED]; } }
// set to true when this instance is disposed, specifically, after
// Dispose(bool disposing) is called by Dispose().
public bool IsDisposed { get { return _flags[DISPOSED]; } }
// a unique ID representing this ChangeMonitor, typically consisting of
// the dependency names and last-modified times.
public abstract string UniqueId { get; }
// Dispose must be called to release the ChangeMonitor. In order to
// prevent derived classes from overriding Dispose, it is not an explicit
// interface implementation.
//
// Before cache insertion, if the user decides not to do a cache insert, they
// must call this to dispose the dependency; otherwise, the ChangeMonitor will
// be referenced and unable to be garbage collected until the dependency changes.
//
// After cache insertion, the cache implementer must call this when the cache entry
// is removed, for whatever reason. Even if an exception is thrown during insert.
//
// After cache insertion, the user should not call Dispose. However, since there's
// no way to prevent this, doing so will invoke the OnChanged event handler, if it
// hasn't already been invoked, and the cache entry will be notified as if the
// dependency has changed.
//
// Dispose() will only invoke the Dispose(bool disposing) method of derived classes
// once, the first time it is called. Subsequent calls to Dispose() perform no
// operation. After Dispose is called, the IsDisposed property will be true.
[SuppressMessage("Microsoft.Performance", "CA1816:DisposeMethodsShouldCallSuppressFinalize", Justification = "Grandfathered suppression from original caching code checkin")]
public void Dispose()
{
OnChangedHelper(null);
// If not initialized, throw, so the derived class understands that it must call InitializeComplete before Dispose.
Debug.Assert(_flags[CHANGED], "It is critical that CHANGED is set before INITIALIZED is checked below.");
if (!_flags[INITIALIZED])
{
throw new InvalidOperationException(SR.Init_not_complete);
}
DisposeHelper();
}
// Cache implementers must call this to be notified of any dependency changes.
// NotifyOnChanged can only be invoked once, and will throw InvalidOperationException
// on subsequent calls. The OnChangedCallback is guaranteed to be called exactly once.
// It will be called when the dependency changes, or if it has already changed, it will
// be called immediately (on the same thread??).
public void NotifyOnChanged(OnChangedCallback onChangedCallback)
{
if (onChangedCallback == null)
{
throw new ArgumentNullException(nameof(onChangedCallback));
}
if (Interlocked.CompareExchange(ref _onChangedCallback, onChangedCallback, null) != null)
{
throw new InvalidOperationException(SR.Method_already_invoked);
}
// if it already changed, raise the event now.
if (_flags[CHANGED])
{
OnChanged(null);
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections;
using System.Xml;
using System.Diagnostics.Contracts;
namespace System.Xml.Schema
{
// Summary:
// Contains a cache of XML Schema definition language (XSD) schemas.
public class XmlSchemaSet
{
#if SILVERLIGHT_4_0_WP
internal XmlSchemaSet() {}
#elif SILVERLIGHT
private XmlSchemaSet() {}
#endif
// Summary:
// Initializes a new instance of the System.Xml.Schema.XmlSchemaSet class.
//public XmlSchemaSet();
//
// Summary:
// Initializes a new instance of the System.Xml.Schema.XmlSchemaSet class with
// the specified System.Xml.XmlNameTable.
//
// Parameters:
// nameTable:
// The System.Xml.XmlNameTable object to use.
//
// Exceptions:
// System.ArgumentNullException:
// The System.Xml.XmlNameTable object passed as a parameter is null.
#if !SILVERLIGHT
public XmlSchemaSet(XmlNameTable nameTable)
{
Contract.Requires(nameTable != null);
}
#endif
// Summary:
// Gets or sets the System.Xml.Schema.XmlSchemaCompilationSettings for the System.Xml.Schema.XmlSchemaSet.
//
// Returns:
// The System.Xml.Schema.XmlSchemaCompilationSettings for the System.Xml.Schema.XmlSchemaSet.
// The default is an System.Xml.Schema.XmlSchemaCompilationSettings instance
// with the System.Xml.Schema.XmlSchemaCompilationSettings.EnableUpaCheck property
// set to true.
//public XmlSchemaCompilationSettings CompilationSettings { get; set; }
//
// Summary:
// Gets the number of logical XML Schema definition language (XSD) schemas in
// the System.Xml.Schema.XmlSchemaSet.
//
// Returns:
// The number of logical schemas in the System.Xml.Schema.XmlSchemaSet.
#if !SILVERLIGHT
public int Count
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return default(int);
}
}
#endif
//
// Summary:
// Gets all the global attributes in all the XML Schema definition language
// (XSD) schemas in the System.Xml.Schema.XmlSchemaSet.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectTable.
#if !SILVERLIGHT
public XmlSchemaObjectTable GlobalAttributes
{
get
{
Contract.Ensures(Contract.Result<XmlSchemaObjectTable>() != null);
return default(XmlSchemaObjectTable);
}
}
#endif
//
// Summary:
// Gets all the global elements in all the XML Schema definition language (XSD)
// schemas in the System.Xml.Schema.XmlSchemaSet.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectTable.
#if !SILVERLIGHT
public XmlSchemaObjectTable GlobalElements
{
get
{
Contract.Ensures(Contract.Result<XmlSchemaObjectTable>() != null);
return default(XmlSchemaObjectTable);
}
}
#endif
//
// Summary:
// Gets all of the global simple and complex types in all the XML Schema definition
// language (XSD) schemas in the System.Xml.Schema.XmlSchemaSet.
//
// Returns:
// An System.Xml.Schema.XmlSchemaObjectTable.
#if !SILVERLIGHT
public XmlSchemaObjectTable GlobalTypes
{
get
{
Contract.Ensures(Contract.Result<XmlSchemaObjectTable>() != null);
return default(XmlSchemaObjectTable);
}
}
#endif
//
// Summary:
// Indicates if the XML Schema definition language (XSD) schemas in the System.Xml.Schema.XmlSchemaSet
// have been compiled.
//
// Returns:
// Returns true if the schemas in the System.Xml.Schema.XmlSchemaSet have been
// compiled since the last time a schema was added or removed from the System.Xml.Schema.XmlSchemaSet;
// otherwise, false.
//public bool IsCompiled { get; }
//
// Summary:
// Gets the default System.Xml.XmlNameTable used by the System.Xml.Schema.XmlSchemaSet
// when loading new XML Schema definition language (XSD) schemas.
//
// Returns:
// An System.Xml.XmlNameTable.
//public XmlNameTable NameTable { get; }
//
// Summary:
// Sets the System.Xml.XmlResolver used to resolve namespaces or locations referenced
// in include and import elements of a schema.
//
// Returns:
// The System.Xml.XmlResolver used to resolve namespaces or locations referenced
// in include and import elements of a schema.
//public XmlResolver XmlResolver { set; }
// Summary:
// Sets an event handler for receiving information about XML Schema definition
// language (XSD) schema validation errors.
// public event ValidationEventHandler ValidationEventHandler;
#if !SILVERLIGHT
// Summary:
// Adds the given System.Xml.Schema.XmlSchema to the System.Xml.Schema.XmlSchemaSet.
//
// Parameters:
// schema:
// The System.Xml.Schema.XmlSchema object to add to the System.Xml.Schema.XmlSchemaSet.
//
// Returns:
// An System.Xml.Schema.XmlSchema object if the schema is valid. If the schema
// is not valid and a System.Xml.Schema.ValidationEventHandler is specified,
// then null is returned and the appropriate validation event is raised. Otherwise
// an System.Xml.Schema.XmlSchemaException is thrown.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// The schema is not valid.
//
// System.ArgumentNullException:
// The System.Xml.Schema.XmlSchema object passed as a parameter is null.
public XmlSchema Add(XmlSchema schema)
{
Contract.Requires(schema != null);
return default(XmlSchema);
}
//
// Summary:
// Adds all the XML Schema definition language (XSD) schemas in the given System.Xml.Schema.XmlSchemaSet
// to the System.Xml.Schema.XmlSchemaSet.
//
// Parameters:
// schemas:
// The System.Xml.Schema.XmlSchemaSet object.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// A schema in the System.Xml.Schema.XmlSchemaSet is not valid.
//
// System.ArgumentNullException:
// The System.Xml.Schema.XmlSchemaSet object passed as a parameter is null.
public void Add(XmlSchemaSet schemas)
{
Contract.Requires(schemas != null);
}
//
// Summary:
// Adds the XML Schema definition language (XSD) schema at the URL specified
// to the System.Xml.Schema.XmlSchemaSet.
//
// Parameters:
// targetNamespace:
// The schema targetNamespace property, or null to use the targetNamespace specified
// in the schema.
//
// schemaUri:
// The URL that specifies the schema to load.
//
// Returns:
// An System.Xml.Schema.XmlSchema object if the schema is valid. If the schema
// is not valid and a System.Xml.Schema.ValidationEventHandler is specified,
// then null is returned and the appropriate validation event is raised. Otherwise,
// an System.Xml.Schema.XmlSchemaException is thrown.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// The schema is not valid.
//
// System.ArgumentNullException:
// The URL passed as a parameter is null or System.String.Empty.
public XmlSchema Add(string targetNamespace, string schemaUri)
{
return default(XmlSchema);
}
//
// Summary:
// Adds the XML Schema definition language (XSD) schema contained in the System.Xml.XmlReader
// to the System.Xml.Schema.XmlSchemaSet.
//
// Parameters:
// targetNamespace:
// The schema targetNamespace property, or null to use the targetNamespace specified
// in the schema.
//
// schemaDocument:
// The System.Xml.XmlReader object.
//
// Returns:
// An System.Xml.Schema.XmlSchema object if the schema is valid. If the schema
// is not valid and a System.Xml.Schema.ValidationEventHandler is specified,
// then null is returned and the appropriate validation event is raised. Otherwise,
// an System.Xml.Schema.XmlSchemaException is thrown.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// The schema is not valid.
//
// System.ArgumentNullException:
// The System.Xml.XmlReader object passed as a parameter is null.
public XmlSchema Add(string targetNamespace, XmlReader schemaDocument)
{
Contract.Requires(schemaDocument != null);
return default(XmlSchema);
}
#endif
//
// Summary:
// Compiles the XML Schema definition language (XSD) schemas added to the System.Xml.Schema.XmlSchemaSet
// into one logical schema.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// An error occurred when validating and compiling the schemas in the System.Xml.Schema.XmlSchemaSet.
//public void Compile();
//
// Summary:
// Indicates whether an XML Schema definition language (XSD) schema with the
// specified target namespace URI is in the System.Xml.Schema.XmlSchemaSet.
//
// Parameters:
// targetNamespace:
// The schema targetNamespace property.
//
// Returns:
// Returns true if a schema with the specified target namespace URI is in the
// System.Xml.Schema.XmlSchemaSet; otherwise, false.
//public bool Contains(string targetNamespace);
//
// Summary:
// Indicates whether the specified XML Schema definition language (XSD) System.Xml.Schema.XmlSchema
// object is in the System.Xml.Schema.XmlSchemaSet.
//
// Parameters:
// schema:
// The System.Xml.Schema.XmlSchema object.
//
// Returns:
// Returns true if the System.Xml.Schema.XmlSchema object is in the System.Xml.Schema.XmlSchemaSet;
// otherwise, false.
//
// Exceptions:
// System.ArgumentNullException:
// The System.Xml.Schema.XmlSchemaSet passed as a parameter is null.
#if !SILVERLIGHT
public bool Contains(XmlSchema schema)
{
Contract.Requires(schema != null);
return default(bool);
}
#endif
//
// Summary:
// Copies all the System.Xml.Schema.XmlSchema objects from the System.Xml.Schema.XmlSchemaSet
// to the given array, starting at the given index.
//
// Parameters:
// schemas:
// The array to copy the objects to.
//
// index:
// The index in the array where copying will begin.
#if !SILVERLIGHT
public void CopyTo(XmlSchema[] schemas, int index)
{
Contract.Requires(schemas != null);
Contract.Requires(index >= 0);
Contract.Requires(index < schemas.Length);
}
#endif
//
// Summary:
// Removes the specified XML Schema definition language (XSD) schema from the
// System.Xml.Schema.XmlSchemaSet.
//
// Parameters:
// schema:
// The System.Xml.Schema.XmlSchema object to remove from the System.Xml.Schema.XmlSchemaSet.
//
// Returns:
// The System.Xml.Schema.XmlSchema object removed from the System.Xml.Schema.XmlSchemaSet
// or null if the schema was not found in the System.Xml.Schema.XmlSchemaSet.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// The schema is not a valid schema.
//
// System.ArgumentNullException:
// The System.Xml.Schema.XmlSchema passed as a parameter is null.
#if !SILVERLIGHT
public XmlSchema Remove(XmlSchema schema)
{
Contract.Requires(schema != null);
return default(XmlSchema);
}
#endif
//
// Summary:
// Removes the specified XML Schema definition language (XSD) schema and all
// the schemas it imports from the System.Xml.Schema.XmlSchemaSet.
//
// Parameters:
// schemaToRemove:
// The System.Xml.Schema.XmlSchema object to remove from the System.Xml.Schema.XmlSchemaSet.
//
// Returns:
// Returns true if the System.Xml.Schema.XmlSchema object and all its imports
// were successfully removed; otherwise, false.
//
// Exceptions:
// System.ArgumentNullException:
// The System.Xml.Schema.XmlSchema passed as a parameter is null.
#if !SILVERLIGHT
public bool RemoveRecursive(XmlSchema schemaToRemove)
{
Contract.Requires(schemaToRemove != null);
return default(bool);
}
#endif
//
// Summary:
// Reprocesses an XML Schema definition language (XSD) schema that already exists
// in the System.Xml.Schema.XmlSchemaSet.
//
// Parameters:
// schema:
// The schema to reprocess.
//
// Returns:
// An System.Xml.Schema.XmlSchema object if the schema is a valid schema. If
// the schema is not valid and a System.Xml.Schema.ValidationEventHandler is
// specified, null is returned and the appropriate validation event is raised.
// Otherwise, an System.Xml.Schema.XmlSchemaException is thrown.
//
// Exceptions:
// System.Xml.Schema.XmlSchemaException:
// The schema is not valid.
//
// System.ArgumentNullException:
// The System.Xml.Schema.XmlSchema object passed as a parameter is null.
//
// System.ArgumentException:
// The System.Xml.Schema.XmlSchema object passed as a parameter does not already
// exist in the System.Xml.Schema.XmlSchemaSet.
#if !SILVERLIGHT
public XmlSchema Reprocess(XmlSchema schema)
{
Contract.Requires(schema != null);
return default(XmlSchema);
}
#endif
//
// Summary:
// Returns a collection of all the XML Schema definition language (XSD) schemas
// in the System.Xml.Schema.XmlSchemaSet.
//
// Returns:
// An System.Collections.ICollection object containing all the schemas that
// have been added to the System.Xml.Schema.XmlSchemaSet. If no schemas have
// been added to the System.Xml.Schema.XmlSchemaSet, an empty System.Collections.ICollection
// object is returned.
#if !SILVERLIGHT
public ICollection Schemas()
{
Contract.Ensures(Contract.Result<ICollection>() != null);
return default(ICollection);
}
//
// Summary:
// Returns a collection of all the XML Schema definition language (XSD) schemas
// in the System.Xml.Schema.XmlSchemaSet that belong to the given namespace.
//
// Parameters:
// targetNamespace:
// The schema targetNamespace property.
//
// Returns:
// An System.Collections.ICollection object containing all the schemas that
// have been added to the System.Xml.Schema.XmlSchemaSet that belong to the
// given namespace. If no schemas have been added to the System.Xml.Schema.XmlSchemaSet,
// an empty System.Collections.ICollection object is returned.
public ICollection Schemas(string targetNamespace)
{
Contract.Ensures(Contract.Result<ICollection>() != null);
return default(ICollection);
}
#endif
}
}
| |
/**************************************
*Script Name: Toolbar *
*Author: Joeku AKA Demortris *
*For use with RunUO 2.0 *
*Client Tested with: 5.0.7.1 *
*Version: 1.3 *
*Initial Release: 08/23/06 *
*Revision Date: 01/22/07 *
***************************************
*Changed by Nerun *
*For use with RunUO 2.1 and 2.2 *
*Client Tested with: from 7.0.8.2 up *
* to 7.0.18.0 *
**************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using Server;
using Server.Accounting;
using Server.Commands;
using Server.Gumps;
using Server.Network;
namespace Joeku
{
public class ToolbarHelper
{
public static int Version = 130; // Version identification
public static string ReleaseDate = "January 22, 2007"; // release date =D
public static ToolbarInfos Infos = null; // DO NOT CHANGE THIS! Used for the persistance item...
public static void Initialize()
{
if( Infos == null )
Infos = new ToolbarInfos();
CommandHandlers.Register("Toolbar", AccessLevel.Counselor, new CommandEventHandler(Toolbar_OnCommand));
EventSink.Login += new LoginEventHandler(OnLogin);
// Talow and AlphaDragon fix 1/3
// http://www.runuo.com/community/threads/joeku-toolbar-after-gm-death.477771/#post-3722174
EventSink.PlayerDeath += new PlayerDeathEventHandler(OnPlayerDeath);
}
/// <summary>
/// Sends a toolbar to staff members upon death.
/// </summary>
// Talow and AlphaDragon fix 2/3
public static void OnPlayerDeath(PlayerDeathEventArgs e)
{
if (e.Mobile.AccessLevel >= AccessLevel.Counselor)
{
e.Mobile.CloseGump(typeof(Toolbar));
object[] arg = new object[] {e.Mobile};
Timer.DelayCall( TimeSpan.FromSeconds( 2.0 ), new TimerStateCallback( SendToolbar ), arg);
}
}
/// <summary>
/// Sends a toolbar to staff members upon login.
/// </summary>
private static void OnLogin(LoginEventArgs e)
{
if (e.Mobile.AccessLevel >= AccessLevel.Counselor)
{
e.Mobile.CloseGump(typeof(Toolbar));
SendToolbar(e.Mobile);
}
}
[Usage("Toolbar")]
public static void Toolbar_OnCommand(CommandEventArgs e)
{
e.Mobile.CloseGump(typeof(Toolbar));
SendToolbar(e.Mobile);
}
/// <summary>
/// Sends a toolbar to the mobile
/// </summary>
public static void SendToolbar(Mobile mob)
{
ToolbarInfo info;
ReadInfo(mob, out info);
mob.SendGump(new Toolbar(info));
}
// Talow and AlphaDragon fix 3/3
public static void SendToolbar(object state)
{
object[] states = (object[])state;
Mobile m = (Mobile)states[0];
SendToolbar(m);
}
/// <summary>
/// Reads the information in the persistance item and exports it into a new ToolbarInfo class.
/// </summary>
public static void ReadInfo(Mobile mob, out ToolbarInfo info)
{
EnsureMaxed( mob );
Account acc = mob.Account as Account;
info = null;
for(int i = 0; i < ToolbarHelper.Infos.Info.Count; i++)
{
if(ToolbarHelper.Infos.Info[i].Account == acc.Username)
info = ToolbarHelper.Infos.Info[i];
}
if(info == null)
info = ToolbarInfo.CreateNew(mob, acc);
}
public static void EnsureMaxed( Mobile mob )
{
//AccessLevel level = (AccessLevel)ToolbarInfo.GetAccess( mob.Account as Account );
if( mob.AccessLevel > ((Account)mob.Account).AccessLevel )
{
mob.Account.AccessLevel = mob.AccessLevel;
//else if( mob.AccessLevel < acc.AccessLevel )
//mob.AccessLevel = level;
Console.WriteLine("***TOOLBAR*** Account {0}, Mobile {1}: AccessLevel resolved to {2}.", ((Account)mob.Account).Username, mob, mob.AccessLevel );
}
}
}
public class ToolbarInfos : Item
{
private List<ToolbarInfo> p_ToolbarInfo = new List<ToolbarInfo>();
public List<ToolbarInfo> Info{ get{ return p_ToolbarInfo; } set{ p_ToolbarInfo = value; }}
public ToolbarInfos(){}
public ToolbarInfos(Serial serial) : base( serial ){}
public override void Delete(){ return; }
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int) ToolbarHelper.Version);
writer.Write((int) Info.Count);
for(int i = 0; i < Info.Count; i++)
{
ToolbarInfo t = Info[i] as ToolbarInfo;
// Version 1.3
writer.Write((int)t.Font );
writer.Write((bool)t.Phantom );
writer.Write((bool)t.Stealth );
writer.Write((bool)t.Reverse );
writer.Write((bool)t.Lock );
// Version 1.0
writer.Write((string) t.Account);
writer.Write((int) t.Dimensions.Count);
for(int j = 0; j < t.Dimensions.Count; j++)
writer.Write((int) t.Dimensions[j]);
writer.Write((int) t.Entries.Count);
for(int k = 0; k < t.Entries.Count; k++)
writer.Write((string) t.Entries[k]);
writer.Write((int) t.Skin);
writer.Write((int) t.Points.Count);
for(int l = 0; l < t.Points.Count; l++)
writer.Write((Point3D) t.Points[l]);
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
ToolbarHelper.Infos = this;
int count = reader.ReadInt();
// Version 1.3
int font = 0;
bool phantom = true, stealth = false, reverse = false, locked = true;
// Version 1.0
string account;
List<int> dimensions;
List<string> entries;
int subcount, skin;
List<Point3D> points;
for(int i = 0; i < count; i++)
{
switch(version)
{
case 130:
{
font = reader.ReadInt();
phantom = reader.ReadBool();
stealth = reader.ReadBool();
reverse = reader.ReadBool();
locked = reader.ReadBool();
goto case 100;
}
default:
case 100:
{
account = reader.ReadString();
dimensions = new List<int>();
subcount = reader.ReadInt();
for(int j = 0; j < subcount; j++)
dimensions.Add(reader.ReadInt());
entries = new List<string>();
subcount = reader.ReadInt();
for(int k = 0; k < subcount; k++)
entries.Add(reader.ReadString());
skin = reader.ReadInt();
points = new List<Point3D>();
subcount = reader.ReadInt();
for(int l = 0; l < subcount; l++)
points.Add(reader.ReadPoint3D());
break;
}
}
ToolbarInfo info = new ToolbarInfo(account, dimensions, entries, skin, points, font, new bool[]{ phantom, stealth, reverse, locked });
}
}
}
public class ToolbarInfo
{
// Version 1.3
private int p_Font;
public int Font{ get{ return p_Font; } set{ p_Font = value; }}
private bool p_Phantom;
public bool Phantom{ get{ return p_Phantom; } set{ p_Phantom = value; }}
private bool p_Stealth;
public bool Stealth{ get{ return p_Stealth; } set{ p_Stealth = value; }}
private bool p_Reverse;
public bool Reverse{ get{ return p_Reverse; } set{ p_Reverse = value; }}
private bool p_Lock;
public bool Lock{ get{ return p_Lock; } set{ p_Lock = value; }}
// Version 1.0
private string p_Account;
public string Account{ get{ return p_Account; } set{ p_Account = value; }}
private List<int> p_Dimensions;
public List<int> Dimensions{ get{ return p_Dimensions; } set{ p_Dimensions = value; }}
private List<string> p_Entries;
public List<string> Entries{ get{ return p_Entries; } set{ p_Entries = value; }}
private int p_Skin;
public int Skin{ get{ return p_Skin; } set{ p_Skin= value; }}
private List<Point3D> p_Points; // Marker
public List<Point3D> Points{ get{ return p_Points; } set{ p_Points = value; }}
public ToolbarInfo(string account, List<int> dimensions, List<string> entries, int skin, List<Point3D> points, int font, bool[] switches )
{
p_Dimensions = new List<int>();
p_Entries = new List<string>();
p_Points = new List<Point3D>();
SetAttributes(account, dimensions, entries, skin, points, font, switches);
ToolbarHelper.Infos.Info.Add(this);
}
/// <summary>
/// Sets the attributes of a ToolbarInfo.
/// </summary>
public void SetAttributes(string account, List<int> dimensions, List<string> entries, int skin, List<Point3D> points, int font, bool[] switches )
{
// Version 1.3
p_Font = font;
p_Phantom = switches[0];
p_Stealth = switches[1];
p_Reverse = switches[2];
p_Lock = switches[3];
// Version 1.0
p_Account = account;
p_Dimensions = dimensions;
p_Entries = entries;
p_Skin = skin;
p_Points = points;
}
/// <summary>
/// Creates a new ToolbarInfo...
/// </summary>
public static ToolbarInfo CreateNew(Mobile mob, Account acc)
{
string account = acc.Username;
int access = (int)mob.AccessLevel;
List<int> dimensions = DefaultDimensions( access );
List<string> entries = DefaultEntries( access );
int skin = 0;
List<Point3D> points = new List<Point3D>();
for( int i = entries.Count; i <= 135; i++ )
entries.Add("-*UNUSED*-");
return new ToolbarInfo(account, dimensions, entries, skin, points, 0, new bool[]{ true, false, false, true } );
}
/// <summary>
/// Gets the highest accesslevel of a character on an account.
/// </summary>
/*public static int GetAccess( Account acc )
{
int access = 0;
for( int i = 0; i < 6; i++ )
{
if( ((Mobile)acc[i]) == null )
break;
if( (int)((Mobile)acc[i]).AccessLevel > access )
access = (int)((Mobile)acc[i]).AccessLevel;
}
return access;
}*/
/// <summary>
/// Calculates the default command entries based on one's AccessLevel.
/// </summary>
public static List<string> DefaultEntries( int i )
{
List<string> entries = new List<string>();
switch(i)
{
case 0: // Player
break;
case 1: // Counselor
entries.Add(".GMBody"); entries.Add(".StaffRunebook"); entries.Add(".Stuck"); entries.Add(".M Tele"); for( int j = 0; j < 5; j++ ){entries.Add("-");}
entries.Add(".Where"); entries.Add(".who"); entries.Add(".Self Hide"); entries.Add(".Self Unhide");
break;
case 2: // GameMaster
entries.Add(".GMBody"); entries.Add(".StaffRunebook"); entries.Add(".Props"); entries.Add(".M Tele"); entries.Add(".Where"); entries.Add(".Who"); entries.Add(".Self Hide"); for( int j = 0; j < 2; j++ ){entries.Add("-");}
entries.Add(".SpawnEditor"); entries.Add(".Move"); entries.Add(".M Remove"); entries.Add(".Wipe"); entries.Add(".Kill"); entries.Add(".Recover"); entries.Add(".Self Unhide");
break;
case 3: // Seer
goto case 2;
case 4: // Administrator
entries.Add(".Admin"); entries.Add(".GMBody"); entries.Add(".StaffRunebook"); entries.Add(".StaEx MyDeco"); entries.Add(".M Tele"); entries.Add(".Where"); entries.Add(".Who"); entries.Add(".Self Hide"); for( int j = 0; j < 1; j++ ){entries.Add("-");}
entries.Add(".PremiumSpawner"); entries.Add(".SpawnEditor"); entries.Add(".Move"); entries.Add(".M Remove"); entries.Add(".Wipe"); entries.Add(".Props"); entries.Add(".Recover"); entries.Add(".Self Unhide"); for( int j = 0; j < 1; j++ ){entries.Add("-");}
entries.Add(".AddonGen"); entries.Add(".Get Location"); entries.Add(".Get ItemID"); entries.Add(".AddDoor");
break;
case 5: // Developer
goto case 4;
case 6: // Owner
goto case 4;
}
return entries;
}
public static List<int> DefaultDimensions( int i )
{
List<int> dimensions = new List<int>();
switch(i)
{
case 0: // Player
dimensions.Add(0); dimensions.Add(0);
break;
case 1: // Counselor
dimensions.Add(4); dimensions.Add(2);
break;
case 2: // GameMaster
dimensions.Add(7); dimensions.Add(2);
break;
case 3: // Seer
goto case 2;
case 4: // Administrator
dimensions.Add(8); dimensions.Add(3);
break;
case 5: // Developer
goto case 4;
case 6: // Owner
goto case 4;
}
return dimensions;
}
}
public class Toolbar : Gump
{
/*******************
* BUTTON ID'S
* 0 - Close
* 1 - Edit
*******************/
private ToolbarInfo p_Info;
// Version 1.3
private int p_Font;
public int Font{ get{ return p_Font; } set{ p_Font = value; } }
private bool p_Phantom, p_Stealth, p_Reverse, p_Lock;
public bool Phantom{ get{ return p_Phantom; } set{ p_Phantom = value; } }
public bool Stealth{ get{ return p_Stealth; } set{ p_Stealth = value; } }
public bool Reverse{ get{ return p_Reverse; } set{ p_Reverse = value; } }
public bool Lock{ get{ return p_Lock; } set{ p_Lock = value; } }
// Version 1.0
private List<string> p_Commands;
private int p_Skin, p_Columns, p_Rows;
public List<string> Commands{ get{ return p_Commands; } set{ p_Commands = value; } }
public int Skin{ get{ return p_Skin; } set{ p_Skin = value; } }
public int Columns{ get{ return p_Columns; } set{ p_Columns = value; } }
public int Rows{ get{ return p_Rows; } set{ p_Rows = value; } }
public int InitOptsW, InitOptsH;
public Toolbar(ToolbarInfo info) : base(0, 28)
{
p_Info = info;
// Version 1.3
p_Font = info.Font;
p_Phantom = info.Phantom;
p_Stealth = info.Stealth;
p_Reverse = info.Reverse;
p_Lock = info.Lock;
// Version 1.0
p_Commands = info.Entries;
p_Skin = info.Skin;
p_Columns = info.Dimensions[0];
p_Rows = info.Dimensions[1];
//original
// if( Lock )
// Closable = false;
//AlphaDragon's mod:
if( Lock )
{
Closable = false;
Disposable = false;
}
//I moded end so that will remain even when editing house
int offset = GumpIDs.Misc[(int)GumpIDs.MiscIDs.ButtonOffset].Content[p_Skin,0];
int bx = ((offset * 2) + (Columns * 110)), by = ((offset * 2) + (Rows * 24)), byx = by, cy = 0;
SetCoords( offset );
if( Reverse )
{
cy = InitOptsH;
by = 0;
}
AddPage( 0 );
AddPage( 1 );
if( Stealth )
{
AddMinimized( by, offset );
AddPage( 2 );
}
AddInitOpts( by, offset );
AddBackground(0, cy, bx, byx, GumpIDs.Misc[(int)GumpIDs.MiscIDs.Background].Content[p_Skin,0]);
string font = GumpIDs.Fonts[Font];
if( Phantom )
font += "<BASEFONT COLOR=#FFFFFF>";
int temp = 0, x = 0, y = 0;
for(int i = 0; i < Columns*Rows; i++)
{
x = offset + ((i % Columns) * 110);
y = offset + (int)(Math.Floor((double)(i / Columns)) * 24) + cy;
AddButton(x + 1, y, 2445, 2445, temp + 10, GumpButtonType.Reply, 0);
AddBackground(x, y, 110, 24, GumpIDs.Misc[(int)GumpIDs.MiscIDs.Buttonground].Content[p_Skin,0]);
if( Phantom )
{
AddImageTiled( x + 2, y + 2, 106, 20, 2624 ); // Alpha Area 1_1
AddAlphaRegion( x + 2, y + 2, 106, 20 ); // Alpha Area 1_2
}
AddHtml( x + 5, y + 3, 100, 20, String.Format( "<center>{0}{1}", font, Commands[temp]), false, false );
//AddLabelCropped(x + 5, y + 3, 100, 20, GumpIDs.Misc[(int)GumpIDs.MiscIDs.Color].Content[p_Skin,0], Commands[temp]);
if( i%Columns == Columns-1 )
temp += 9-Columns;
temp++;
}
/*TEST---
0%5 == 0
1%5 == 1
2%5 == 2
3%5 == 3
4%5 == 4
5%5 == 0
END TEST---*/
if( !Stealth )
{
AddPage(2);
AddMinimized( by, offset );
}
}
public override void OnResponse(NetState sender, RelayInfo info)
{
Mobile mob = sender.Mobile;
switch(info.ButtonID)
{
default: // Command
mob.SendGump(this);
if(Commands[info.ButtonID - 10].StartsWith(CommandSystem.Prefix))
{
mob.SendMessage( Commands[info.ButtonID - 10]);
CommandSystem.Handle(mob, Commands[info.ButtonID - 10]);
}
else
{
//SpeechEventArgs args = new SpeechEventArgs( mob, Commands[info.ButtonID - 10], MessageType.Regular, mob.SpeechHue, null );
mob.DoSpeech( Commands[info.ButtonID - 10], new int[0], MessageType.Regular, mob.SpeechHue );
//mob.Say(Commands[info.ButtonID - 10]);
}
break;
case 0: // Close
break;
case 1: // Edit
mob.SendGump(this);
mob.CloseGump( typeof( ToolbarEdit ) );
mob.SendGump(new ToolbarEdit( p_Info ));
break;
}
}
/// <summary>
/// Sets coordinates and sizes.
/// </summary>
public void SetCoords( int offset )
{
InitOptsW = 50 + (offset * 2) + GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Minimize].Content[p_Skin,2] + 5 + GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Customize].Content[p_Skin,2];
InitOptsH = (offset * 2) + GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Minimize].Content[p_Skin,3];
if(GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Customize].Content[p_Skin,3] + (offset * 2) > InitOptsH)
InitOptsH = GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Customize].Content[p_Skin,3] + (offset * 2);
}
/// <summary>
/// Adds initial options.
/// </summary>
public void AddInitOpts( int y, int offset )
{
AddBackground(0, y, InitOptsW, InitOptsH, GumpIDs.Misc[(int)GumpIDs.MiscIDs.Background].Content[p_Skin,0]);
AddButton(offset, y + offset, GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Minimize].Content[p_Skin,0], GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Minimize].Content[p_Skin,1], 0, GumpButtonType.Page, Stealth ? 1 : 2);
AddButton(offset + GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Minimize].Content[p_Skin,2] + 5, y + offset, GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Customize].Content[p_Skin,0], GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Customize].Content[p_Skin,1], 1, GumpButtonType.Reply, 0); // 1 Edit
}
/// <summary>
/// Adds minimized page.
/// </summary>
public void AddMinimized( int y, int offset )
{
AddBackground(0, y, InitOptsW, InitOptsH, GumpIDs.Misc[(int)GumpIDs.MiscIDs.Background].Content[p_Skin,0]);
AddButton(offset, y + offset, GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Maximize].Content[p_Skin,0], GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Maximize].Content[p_Skin,1], 0, GumpButtonType.Page, Stealth ? 2 : 1);
AddButton(offset + GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Minimize].Content[p_Skin,2] + 5, y + offset, GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Customize].Content[p_Skin,0], GumpIDs.Buttons[(int)GumpIDs.ButtonIDs.Customize].Content[p_Skin,1], 1, GumpButtonType.Reply, 0); // 1 Edit
}
}
public class ToolbarEdit : Gump
{
public static string HTML = String.Format( "<center><u>Command Toolbar v{0}</u><br>Made by Joeku AKA Demortris<br>{1}<br>- Customized to Nerun's Distro -</center><br> This toolbar is extremely versatile. You can switch skins and increase or decrease columns or rows. The toolbar operates like a spreadsheet; you can use the navigation menu to scroll through different commands and bind them. Enjoy!<br><p>If you have questions, concerns, or bug reports, please <A HREF=\"mailto:demortris@adelphia.net\">e-mail me</A>.", ((double)ToolbarHelper.Version) / 100, ToolbarHelper.ReleaseDate);
private bool p_Expanded;
private int p_ExpandedInt;
private int p_Font;
public int Font{ get{ return p_Font; } set{ p_Font = value; } }
private bool p_Phantom, p_Stealth, p_Reverse, p_Lock;
public bool Phantom{ get{ return p_Phantom; } set{ p_Phantom = value; } }
public bool Stealth{ get{ return p_Stealth; } set{ p_Stealth = value; } }
public bool Reverse{ get{ return p_Reverse; } set{ p_Reverse = value; } }
public bool Lock{ get{ return p_Lock; } set{ p_Lock = value; } }
private List<string> p_Commands;
private int p_Skin, p_Columns, p_Rows;
private ToolbarInfo p_Info;
private List<TextRelay> TextRelays = null;
public List<string> Commands{ get{ return p_Commands; } set{ p_Commands = value; } }
public int Skin{ get{ return p_Skin; } set{ p_Skin = value; } }
public int Columns{ get{ return p_Columns; } set{ p_Columns = value; } }
public int Rows{ get{ return p_Rows; } set{ p_Rows = value; } }
public ToolbarEdit( ToolbarInfo info ) : this( info, false ){}
public ToolbarEdit( ToolbarInfo info, bool expanded ) : this( info, expanded, info.Entries, info.Skin, info.Dimensions[0], info.Dimensions[1], info.Font, new bool[]{ info.Phantom, info.Stealth, info.Reverse, info.Lock } ){}
public ToolbarEdit( ToolbarInfo info, List<string> commands, int skin, int columns, int rows, int font, bool[] switches ) : this( info, false, commands, skin, columns, rows, font, switches ){}
public ToolbarEdit( ToolbarInfo info, bool expanded, List<string> commands, int skin, int columns, int rows, int font, bool[] switches ) : base(0, 28)
{
p_Info = info;
p_Expanded = expanded;
p_ExpandedInt = expanded ? 2 : 1;
p_Font = font;
p_Phantom = switches[0];
p_Stealth = switches[1];
p_Reverse = switches[2];
p_Lock = switches[3];
p_Commands = commands;
p_Skin = skin;
p_Columns = columns;
p_Rows = rows;
AddInit();
AddControls();
AddNavigation();
AddResponses();
AddEntries();
}
public override void OnResponse(NetState sender, RelayInfo info)
{
Mobile m = sender.Mobile;
TextRelays = CreateList( info.TextEntries );
bool[] switches = new bool[4]
{
info.IsSwitched( 21 ),
info.IsSwitched( 23 ),
info.IsSwitched( 25 ),
info.IsSwitched( 27 )
};
switch( info.ButtonID )
{
case 0: break;
case 1: m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin + 1, Columns, Rows, Font, switches )); break;
case 2: m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin - 1, Columns, Rows, Font, switches )); break;
case 3: m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows + 1, Font, switches )); break;
case 4: m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows - 1, Font, switches )); break;
case 5: m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns + 1, Rows, Font, switches )); break;
case 6: m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns - 1, Rows, Font, switches )); break;
//case 7:
//m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows, Font, switches ));
//m.SendMessage( 32, "The Marker utility is not an active feature yet; please be patient." );
//goto case 0;
case 9: // Default
List<string> toolbarinfo = ToolbarInfo.DefaultEntries( (int)m.AccessLevel );
CombineEntries( toolbarinfo );
toolbarinfo.AddRange( AnalyzeEntries( toolbarinfo.Count ) );
m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, toolbarinfo, Skin, Columns, Rows, Font, switches ));
break;
case 10: // Okay
goto case 12;
case 11: // Cancel
goto case 0;
case 12: // Apply
Account acc = m.Account as Account;
ToolbarInfo infos = null;
for(int i = 0; i < ToolbarHelper.Infos.Info.Count; i++)
{
if(ToolbarHelper.Infos.Info[i].Account == acc.Username)
infos = ToolbarHelper.Infos.Info[i];
}
if(infos == null)
infos = ToolbarInfo.CreateNew(m, acc);
List<int> dims = new List<int>();
dims.Add( Columns );
dims.Add( Rows );
infos.SetAttributes(acc.Username, dims, AnalyzeEntries(), Skin, infos.Points, Font, switches );
if( info.ButtonID == 12 )
m.SendGump( new ToolbarEdit( infos, this.p_Expanded ) );
m.CloseGump( typeof( Toolbar ) );
m.SendGump( new Toolbar( infos ) );
break;
case 18: m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows, Font + 1, switches )); break;
case 19: m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows, Font - 1, switches )); break;
case 20:
m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows, Font, switches ));
m.SendMessage( 2101, "Phantom mode turns the toolbar semi-transparent." );
break;
case 22:
m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows, Font, switches ));
m.SendMessage( 2101, "Stealth mode makes the toolbar automatically minimize when you click a button." );
break;
case 24:
m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows, Font, switches ));
m.SendMessage( 2101, "Reverse mode puts the minimize bar above the toolbar instead of below." );
break;
case 26:
m.SendGump( new ToolbarEdit( p_Info, this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows, Font, switches ));
m.SendMessage( 2101, "Lock mode disables closing the toolbar with right-click." );
break;
case 28: // Expand
m.SendGump( new ToolbarEdit( p_Info, !this.p_Expanded, AnalyzeEntries(), Skin, Columns, Rows, Font, switches ));
m.SendMessage( 2101, "Expanded view {0}activated.", this.p_Expanded ? "de" : "" );
break;
}
}
/// <summary>
/// Takes the gump relay entries and converts them from an Array into a List.
/// </summary>
public static List<TextRelay> CreateList( TextRelay[] entries )
{
List<TextRelay> list = new List<TextRelay>();
for( int i = 0; i < entries.Length; i++ )
list.Add( entries[i] );
return list;
}
public void CombineEntries( List<string> list )
{
string temp;
for( int i = 0; i < list.Count; i++ )
{
if( list[i] == "-*UNUSED*-" && (temp = GetEntry( i+13, this ).Text) != "" )
list[i] = temp;
}
}
public List<string> AnalyzeEntries()
{ return AnalyzeEntries( 0 ); }
/// <summary>
/// Organizes the gump relay entries into a usable collection.
/// </summary>
public List<string> AnalyzeEntries( int i )
{
List<string> list = new List<string>();
string temp;
for( int j = i; j < 135; j++ )
{
if( (temp = GetEntry( j+13, this ).Text) == "" )
list.Add( "-*UNUSED*-" );
else
list.Add( temp );
}
return list;
}
/// <summary>
/// Gets entry # in the gump relay.
/// </summary>
public static TextRelay GetEntry( int entryID, ToolbarEdit gump )
{
int temp = 0;
TextRelay relay = null;
for( int i = 0; i < gump.TextRelays.Count; i++ )
{
if( gump.TextRelays[i].EntryID == entryID )
{
temp = i;
relay = gump.TextRelays[i];
}
}
gump.TextRelays.RemoveAt( temp );
return relay;
}
/// <summary>
/// Adds the skeleton gump.
/// </summary>
public void AddInit()
{
AddPage(0);
AddBackground(0, 0, 620, 120, 9200);
AddHtml(10, 10, 240, 100, HTML, true, true);
}
/// <summary>
/// Adds other dynamic options.
/// </summary>
public void AddControls()
{
AddBackground(260, 0, 240, 120, 9200);
AddLabel(274, 11, 0, String.Format("Skin - {0}", p_Skin + 1 ));
if( p_Skin < GumpIDs.Skins - 1 )
AddButton(359, 10, 2435, 2436, 1, GumpButtonType.Reply, 0);
if( p_Skin > 0 )
AddButton(359, 21, 2437, 2438, 2, GumpButtonType.Reply, 0);
AddLabel(274, 36, 0, String.Format("Rows - {0}", p_Rows ));
if( p_Rows < 15 )
AddButton(359, 35, 2435, 2436, 3, GumpButtonType.Reply, 0);
if( p_Rows > 1 )
AddButton(359, 46, 2437, 2438, 4, GumpButtonType.Reply, 0);
AddLabel(274, 61, 0, String.Format("Columns - {0}", p_Columns ));
if( p_Columns < 9 )
AddButton(359, 60, 2435, 2436, 5, GumpButtonType.Reply, 0);
if( p_Columns > 1 )
AddButton(359, 71, 2437, 2438, 6, GumpButtonType.Reply, 0);
AddHtml( 276, 87, 100, 20, String.Format("{0}Font - {1}", GumpIDs.Fonts[p_Font], p_Font+1), false, false );
if( p_Font < GumpIDs.Fonts.Length-1 )
AddButton(359, 85, 2435, 2436, 18, GumpButtonType.Reply, 0);
if( p_Font > 0 )
AddButton(359, 96, 2437, 2438, 19, GumpButtonType.Reply, 0);
/*AddLabel(274, 86, 0, "Marker");
AddButton(326, 88, 22153, 22155, 7, GumpButtonType.Reply, 0);
AddCheck(349, 86, 210, 211, true, 8); */
// Version 1.3
AddLabel(389, 11, 0, "Phantom");
AddButton(446, 13, 22153, 22155, 20, GumpButtonType.Reply, 0);
AddCheck(469, 11, 210, 211, Phantom, 21);
AddLabel(389, 36, 0, "Stealth");
AddButton(446, 38, 22153, 22155, 22, GumpButtonType.Reply, 0);
AddCheck(469, 36, 210, 211, Stealth, 23);
AddLabel(389, 61, 0, "Reverse");
AddButton(446, 63, 22153, 22155, 24, GumpButtonType.Reply, 0);
AddCheck(469, 61, 210, 211, Reverse, 25);
AddLabel(389, 86, 0, "Lock");
AddButton(446, 88, 22153, 22155, 26, GumpButtonType.Reply, 0);
AddCheck(469, 86, 210, 211, Lock, 27);
}
/// <summary>
/// Adds the skeleton navigation section.
/// </summary>
public void AddNavigation()
{
AddBackground(500, 0, 120, 120, 9200);
AddHtml(500, 10, 120, 20, @"<center><u>Navigation</u></center>", false, false);
AddLabel( 508, 92, 0, "Expanded View" );
AddButton( 595, 95, this.p_Expanded ? 5603 : 5601, this.p_Expanded ? 5607 : 5605, 28, GumpButtonType.Reply, 0 );
}
/// <summary>
/// Adds response buttons.
/// </summary>
public void AddResponses()
{
int temp = 170 + (p_ExpandedInt * 100);
AddBackground(0, temp, 500, 33, 9200);
AddButton( 50, temp + 5, 246, 244, 9, GumpButtonType.Reply, 0 ); // Default
AddButton( 162, temp + 5, 249, 248, 10, GumpButtonType.Reply, 0 ); // Okay
AddButton( 275, temp + 5, 243, 241, 11, GumpButtonType.Reply, 0 ); // Cancel
AddButton( 387, temp + 5, 239, 240, 12, GumpButtonType.Reply, 0 ); // Apply
}
/// <summary>
/// Adds the actual command/phrase entries.
/// </summary>
public void AddEntries()
{
int buffer = 2;
// CALC
int entryX = p_ExpandedInt * 149, entryY = p_ExpandedInt * 20;
int bgX = 10 + 4 + (buffer * 3) + (entryX * 3), bgY = 10 + 8 + (entryY * 5);
int divX = bgX - 10, divY = bgY - 10;
// ENDCALC
AddBackground(0, 120, 33 + bgX, 32 + bgY, 9200);
AddBackground(33, 152, bgX, bgY, 9200);
// Add vertical dividers
for( int m = 1; m <= 2; m++ )
AddImageTiled( 38 + ( m * entryX ) + buffer + ((m-1)*4), 157, 2, divY, 10004);
// Add horizontal dividers
for( int n = 1; n <= 4; n++ )
AddImageTiled( 38, 155 + (n * ( entryY + 2)), divX, 2, 10001);
int start = -3, temp = 0;
for( int i = 1; i <= 9; i++ )
{
start += 3;
if( i == 4 )
start = 45;
else if( i == 7 )
start = 90;
temp = start;
/********
* PAGES *
*-------*
* 1 2 3 *
* 4 5 6 *
* 7 8 9 *
********/
AddPage(i);
CalculatePages(i);
// Add column identifiers
for( int j = 0; j < 3; j++ )
AddHtml( 38 + buffer + ((j % 3) * (buffer + entryX + 2)), 128, entryX, 20, String.Format("<center>Column {0}</center>", (j+1) + CalculateColumns(i) ), false, false);
AddHtml( 2, 128, 30, 20, "<center>Row</center>", false, false );
int tempInt = 0;
if( p_Expanded )
tempInt = 11;
// Add row identifiers
for( int k = 0; k < 5; k++ )
AddHtml(0, 157 + (k * (entryY + 2)) + tempInt, 32, 20, String.Format("<center>{0}</center>", (k+1) + CalculateRows(i) ), false, false);
// Add command entries
for( int l = 0; l < 15; l++ )
{
AddTextEntry( 38 + buffer + ((l % 3) * ((buffer*2) + entryX )), 157 + ((int)Math.Floor((double)l / 3) * (entryY + 2)), entryX-1, entryY, 2101, temp+13, Commands[temp] /*,int size*/);
if( l%3 == 2 )
temp += 6;
temp++;
}
}
}
/// <summary>
/// Calculates what navigation button takes you to what page.
/// </summary>
public void CalculatePages( int i )
{
int up = 0, down = 0, left = 0, right = 0;
switch( i )
{
case 1: down = 4; right = 2; break;
case 2: down = 5; left = 1; right = 3; break;
case 3: down = 6; left = 2; break;
case 4: up = 1; down = 7; right = 5; break;
case 5: up = 2; down = 8; left = 4; right = 6; break;
case 6: up = 3; down = 9; left = 5; break;
case 7: up = 4; right = 8; break;
case 8: up = 5; left = 7; right = 9; break;
case 9: up = 6; left = 8; break;
}
AddNavigation( up, down, left, right );
}
/// <summary>
/// Adds navigation buttons for each page.
/// </summary>
public void AddNavigation( int up, int down, int left, int right )
{
if( up > 0 )
AddButton(549, 34, 9900, 9902, 0, GumpButtonType.Page, up);
if( down > 0 )
AddButton(549, 65, 9906, 9908, 0, GumpButtonType.Page, down);
if( left > 0 )
AddButton(523, 50, 9909, 9911, 0, GumpButtonType.Page, left);
if( right > 0 )
AddButton(575, 50, 9903, 9905, 0, GumpButtonType.Page, right);
}
/// <summary>
/// Damn I've forgotten...
/// </summary>
public static int CalculateColumns( int i )
{
if( i == 1 || i == 4 || i == 7 )
return 0;
else if( i == 2 || i == 5 || i == 8 )
return 3;
else
return 6;
}
/// <summary>
/// Same as above! =(
/// </summary>
public static int CalculateRows( int i )
{
if( i >= 1 && i <= 3 )
return 0;
else if( i >= 4 && i <= 6 )
return 5;
else
return 10;
}
}
public class GumpIDs
{
public enum MiscIDs
{
Background = 0,
Color = 1,
Buttonground = 2,
ButtonOffset = 3,
}
public enum ButtonIDs
{
Minimize = 0,
Maximize = 1,
Customize = 2,
SpecialCommand = 3,
Send = 4,
Teleport = 5,
Gate = 6,
}
private int p_ID;
public int ID{ get{ return p_ID; } set{ p_ID = value; }}
private int[,] p_Content;
public int[,] Content{ get{ return p_Content; } set{ p_Content = value; }}
private string p_Name;
public string Name{ get{ return p_Name; } set{ p_Name = value; }}
public GumpIDs(int iD, string name, int[,] content)
{
p_ID = iD;
p_Content = content;
p_Name = name;
}
private static string[] p_Fonts = new string[]
{ "", "<b>", "<i>", "<b><i>", "<small>", "<b><small>", "<i><small>", "<b><i><small>", "<big>", "<b><big>", "<i><big>", "<b><i><big>" };
public static string[] Fonts{ get{ return p_Fonts; } set{ p_Fonts = value; }}
public static int Skins = 2;
private static GumpIDs[] m_Misc = new GumpIDs[]
{
new GumpIDs( 0, "Background", new int[2,1]{{ 9200 }, { 9270 }}),
new GumpIDs( 1, "Color", new int[2,1]{{ 0 }, { 0 }}),
new GumpIDs( 2, "Buttonground", new int[2,1]{{ 9200 }, { 9350 }}),
new GumpIDs( 3, "ButtonOffset", new int[2,1]{{ 5 }, { 7 }}),
};
public static GumpIDs[] Misc{ get{ return m_Misc; } set{ m_Misc = value; }}
private static GumpIDs[] m_Buttons = new GumpIDs[]
{
new GumpIDs( 0, "Minimize", new int[2,4]{{ 5603, 5607, 16, 16 }, { 5537, 5539, 19, 21 }}),
new GumpIDs( 1, "Maximize", new int[2,4]{{ 5601, 5605, 16, 16 }, { 5540, 5542, 19, 21 }}),
new GumpIDs( 2, "Customize", new int[2,4]{{ 22153, 22155, 16, 16 }, { 5525, 5527, 62, 24 }}),
new GumpIDs( 3, "SpecialCommand", new int[2,4]{{ 2117, 2118, 15, 15 }, { 9720, 9722, 29, 29 }}),
new GumpIDs( 4, "Send", new int[2,4]{{ 2360, 2360, 11, 11 }, { 2360, 2360, 11, 11 }}),
new GumpIDs( 5, "Teleport", new int[2,4]{{ 2361, 2361, 11, 11 }, { 2361, 2361, 11, 11 }}),
new GumpIDs( 6, "Gate", new int[2,4]{{ 2362, 2362, 11, 11 }, { 2361, 2361, 11, 11 }}),
};
public static GumpIDs[] Buttons{ get{ return m_Buttons; } set{ m_Buttons = value; }}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace Invoices.Business
{
/// <summary>
/// ProductInfo (read only object).<br/>
/// This is a generated <see cref="ProductInfo"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="ProductList"/> collection.
/// </remarks>
[Serializable]
public partial class ProductInfo : ReadOnlyBase<ProductInfo>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="ProductId"/> property.
/// </summary>
public static readonly PropertyInfo<Guid> ProductIdProperty = RegisterProperty<Guid>(p => p.ProductId, "Product Id", Guid.NewGuid());
/// <summary>
/// Gets the Product Id.
/// </summary>
/// <value>The Product Id.</value>
public Guid ProductId
{
get { return GetProperty(ProductIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ProductCode"/> property.
/// </summary>
public static readonly PropertyInfo<string> ProductCodeProperty = RegisterProperty<string>(p => p.ProductCode, "Product Code", null);
/// <summary>
/// Gets the Product Code.
/// </summary>
/// <value>The Product Code.</value>
public string ProductCode
{
get { return GetProperty(ProductCodeProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name");
/// <summary>
/// Gets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return GetProperty(NameProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ProductTypeId"/> property.
/// </summary>
public static readonly PropertyInfo<int> ProductTypeIdProperty = RegisterProperty<int>(p => p.ProductTypeId, "Product Type Id");
/// <summary>
/// Gets the Product Type Id.
/// </summary>
/// <value>The Product Type Id.</value>
public int ProductTypeId
{
get { return GetProperty(ProductTypeIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="UnitCost"/> property.
/// </summary>
public static readonly PropertyInfo<string> UnitCostProperty = RegisterProperty<string>(p => p.UnitCost, "Unit Cost");
/// <summary>
/// Gets the Unit Cost.
/// </summary>
/// <value>The Unit Cost.</value>
public string UnitCost
{
get { return GetProperty(UnitCostProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="StockByteNull"/> property.
/// </summary>
public static readonly PropertyInfo<byte?> StockByteNullProperty = RegisterProperty<byte?>(p => p.StockByteNull, "Stock Byte Null", null);
/// <summary>
/// Gets the Stock Byte Null.
/// </summary>
/// <value>The Stock Byte Null.</value>
public byte? StockByteNull
{
get { return GetProperty(StockByteNullProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="StockByte"/> property.
/// </summary>
public static readonly PropertyInfo<byte> StockByteProperty = RegisterProperty<byte>(p => p.StockByte, "Stock Byte");
/// <summary>
/// Gets the Stock Byte.
/// </summary>
/// <value>The Stock Byte.</value>
public byte StockByte
{
get { return GetProperty(StockByteProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="StockShortNull"/> property.
/// </summary>
public static readonly PropertyInfo<short?> StockShortNullProperty = RegisterProperty<short?>(p => p.StockShortNull, "Stock Short Null", null);
/// <summary>
/// Gets the Stock Short Null.
/// </summary>
/// <value>The Stock Short Null.</value>
public short? StockShortNull
{
get { return GetProperty(StockShortNullProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="StockShort"/> property.
/// </summary>
public static readonly PropertyInfo<short> StockShortProperty = RegisterProperty<short>(p => p.StockShort, "Stock Short");
/// <summary>
/// Gets the Stock Short.
/// </summary>
/// <value>The Stock Short.</value>
public short StockShort
{
get { return GetProperty(StockShortProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="StockIntNull"/> property.
/// </summary>
public static readonly PropertyInfo<int?> StockIntNullProperty = RegisterProperty<int?>(p => p.StockIntNull, "Stock Int Null", null);
/// <summary>
/// Gets the Stock Int Null.
/// </summary>
/// <value>The Stock Int Null.</value>
public int? StockIntNull
{
get { return GetProperty(StockIntNullProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="StockInt"/> property.
/// </summary>
public static readonly PropertyInfo<int> StockIntProperty = RegisterProperty<int>(p => p.StockInt, "Stock Int");
/// <summary>
/// Gets the Stock Int.
/// </summary>
/// <value>The Stock Int.</value>
public int StockInt
{
get { return GetProperty(StockIntProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="StockLongNull"/> property.
/// </summary>
public static readonly PropertyInfo<long?> StockLongNullProperty = RegisterProperty<long?>(p => p.StockLongNull, "Stock Long Null", null);
/// <summary>
/// Gets the Stock Long Null.
/// </summary>
/// <value>The Stock Long Null.</value>
public long? StockLongNull
{
get { return GetProperty(StockLongNullProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="StockLong"/> property.
/// </summary>
public static readonly PropertyInfo<long> StockLongProperty = RegisterProperty<long>(p => p.StockLong, "Stock Long");
/// <summary>
/// Gets the Stock Long.
/// </summary>
/// <value>The Stock Long.</value>
public long StockLong
{
get { return GetProperty(StockLongProperty); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductInfo"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductInfo()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="ProductInfo"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Child_Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(ProductIdProperty, dr.GetGuid("ProductId"));
LoadProperty(ProductCodeProperty, dr.IsDBNull("ProductCode") ? null : dr.GetString("ProductCode"));
LoadProperty(NameProperty, dr.GetString("Name"));
LoadProperty(ProductTypeIdProperty, dr.GetInt32("ProductTypeId"));
LoadProperty(UnitCostProperty, dr.GetString("UnitCost"));
LoadProperty(StockByteNullProperty, (byte?)dr.GetValue("StockByteNull"));
LoadProperty(StockByteProperty, dr.GetByte("StockByte"));
LoadProperty(StockShortNullProperty, (short?)dr.GetValue("StockShortNull"));
LoadProperty(StockShortProperty, dr.GetInt16("StockShort"));
LoadProperty(StockIntNullProperty, (int?)dr.GetValue("StockIntNull"));
LoadProperty(StockIntProperty, dr.GetInt32("StockInt"));
LoadProperty(StockLongNullProperty, (long?)dr.GetValue("StockLongNull"));
LoadProperty(StockLongProperty, dr.GetInt64("StockLong"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.PythonTools.Repl {
[Export(typeof(IInteractiveWindowCommand))]
[ContentType(PythonCoreConstants.ContentType)]
class LoadReplCommand : IInteractiveWindowCommand {
const string _commentPrefix = "%%";
public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) {
var finder = new FileFinder(arguments);
var eval = window.GetPythonEvaluator();
if (eval != null) {
finder.Search(eval.Configuration.WorkingDirectory);
foreach (var p in eval.Configuration.SearchPaths.MaybeEnumerate()) {
finder.Search(p);
}
}
finder.ThrowIfNotFound();
string commandPrefix = "$";
string lineBreak = window.TextView.Options.GetNewLineCharacter();
IEnumerable<string> lines = File.ReadLines(finder.Filename);
IEnumerable<string> submissions;
if (eval != null) {
submissions = ReplEditFilter.JoinToCompleteStatements(lines, eval.LanguageVersion).Where(CommentPrefixPredicate);
} else {
// v1 behavior, will probably never be hit, but if someone was developing their own IReplEvaluator
// and using this class it would be hit.
var submissionList = new List<string>();
var currentSubmission = new List<string>();
foreach (var line in lines) {
if (line.StartsWithOrdinal(_commentPrefix, ignoreCase: true)) {
continue;
}
if (line.StartsWithOrdinal(commandPrefix, ignoreCase: true)) {
AddSubmission(submissionList, currentSubmission, lineBreak);
submissionList.Add(line);
currentSubmission.Clear();
} else {
currentSubmission.Add(line);
}
}
AddSubmission(submissionList, currentSubmission, lineBreak);
submissions = submissionList;
}
window.SubmitAsync(submissions);
return ExecutionResult.Succeeded;
}
private static bool CommentPrefixPredicate(string input) {
return !input.StartsWithOrdinal(_commentPrefix, ignoreCase: true);
}
private static void AddSubmission(List<string> submissions, List<string> lines, string lineBreak) {
string submission = String.Join(lineBreak, lines);
// skip empty submissions:
if (submission.Length > 0) {
submissions.Add(submission);
}
}
public string Description {
get { return Strings.ReplLoadCommandDescription; }
}
public string Command {
get { return "load"; }
}
public IEnumerable<ClassificationSpan> ClassifyArguments(ITextSnapshot snapshot, Span argumentsSpan, Span spanToClassify) {
yield break;
}
public string CommandLine {
get {
return "";
}
}
public IEnumerable<string> DetailedDescription {
get {
yield return Description;
}
}
public IEnumerable<KeyValuePair<string, string>> ParametersDescription {
get {
yield break;
}
}
public IEnumerable<string> Names {
get {
yield return Command;
}
}
class FileFinder {
private readonly string _baseName;
public FileFinder(string baseName) {
_baseName = (baseName ?? "").Trim(' ', '\"');
if (PathUtils.IsValidPath(_baseName) && Path.IsPathRooted(_baseName) && File.Exists(_baseName)) {
Found = true;
Filename = _baseName;
}
}
/// <summary>
/// Searches the specified path and changes <see cref="Found"/> to
/// true if the file exists. Returns true if the file was found in
/// the provided path.
/// </summary>
public bool Search(string path) {
if (Found) {
// File was found, but not in this path
return false;
}
if (!PathUtils.IsValidPath(path) || !Path.IsPathRooted(path)) {
return false;
}
var fullPath = PathUtils.GetAbsoluteFilePath(path, _baseName);
if (File.Exists(fullPath)) {
Found = true;
Filename = fullPath;
return true;
}
return false;
}
/// <summary>
/// Searches each path in the list of paths as if they had been
/// passed to <see cref="Search"/> individually.
/// </summary>
public bool SearchAll(string paths, char separator) {
if (Found) {
// File was found, but not in this path
return false;
}
if (string.IsNullOrEmpty(paths)) {
return false;
}
return SearchAll(paths.Split(separator));
}
/// <summary>
/// Searches each path in the sequence as if they had been passed
/// to <see cref="Search"/> individually.
/// </summary>
public bool SearchAll(IEnumerable<string> paths) {
if (Found) {
// File was found, but not in this path
return false;
}
if (paths == null) {
return false;
}
foreach (var path in paths) {
if (Search(path)) {
return true;
}
}
return false;
}
[DebuggerStepThrough, DebuggerHidden]
public void ThrowIfNotFound() {
if (!Found) {
throw new FileNotFoundException(Strings.ReplLoadCommandFileNotFoundException, _baseName);
}
}
public bool Found { get; private set; }
public string Filename { get; private set; }
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal abstract partial class AbstractCodeModelService : ICodeModelService
{
private readonly ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>> _treeToNodeKeyMaps =
new ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>>();
protected readonly ISyntaxFactsService SyntaxFactsService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly AbstractNodeNameGenerator _nodeNameGenerator;
private readonly AbstractNodeLocator _nodeLocator;
private readonly AbstractCodeModelEventCollector _eventCollector;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly IFormattingRule _lineAdjustmentFormattingRule;
private readonly IFormattingRule _endRegionFormattingRule;
protected AbstractCodeModelService(
HostLanguageServices languageServiceProvider,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IFormattingRule lineAdjustmentFormattingRule,
IFormattingRule endRegionFormattingRule)
{
Debug.Assert(languageServiceProvider != null);
Debug.Assert(editorOptionsFactoryService != null);
this.SyntaxFactsService = languageServiceProvider.GetService<ISyntaxFactsService>();
_editorOptionsFactoryService = editorOptionsFactoryService;
_lineAdjustmentFormattingRule = lineAdjustmentFormattingRule;
_endRegionFormattingRule = endRegionFormattingRule;
_refactorNotifyServices = refactorNotifyServices;
_nodeNameGenerator = CreateNodeNameGenerator();
_nodeLocator = CreateNodeLocator();
_eventCollector = CreateCodeModelEventCollector();
}
protected string GetNewLineCharacter(SourceText text)
{
return _editorOptionsFactoryService.GetEditorOptions(text).GetNewLineCharacter();
}
protected int GetTabSize(SourceText text)
{
var snapshot = text.FindCorrespondingEditorTextSnapshot();
return GetTabSize(snapshot);
}
protected int GetTabSize(ITextSnapshot snapshot)
{
if (snapshot == null)
{
throw new ArgumentNullException(nameof(snapshot));
}
var textBuffer = snapshot.TextBuffer;
return _editorOptionsFactoryService.GetOptions(textBuffer).GetTabSize();
}
protected SyntaxToken GetTokenWithoutAnnotation(SyntaxToken current, Func<SyntaxToken, SyntaxToken> nextTokenGetter)
{
while (current.ContainsAnnotations)
{
current = nextTokenGetter(current);
}
return current;
}
protected TextSpan GetEncompassingSpan(SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken)
{
var startPosition = startToken.SpanStart;
var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End;
return TextSpan.FromBounds(startPosition, endPosition);
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> BuildNodeKeyMap(SyntaxTree syntaxTree)
{
var nameOrdinalMap = new Dictionary<string, int>();
var nodeKeyMap = BidirectionalMap<SyntaxNodeKey, SyntaxNode>.Empty;
foreach (var node in GetFlattenedMemberNodes(syntaxTree))
{
var name = _nodeNameGenerator.GenerateName(node);
int ordinal;
if (!nameOrdinalMap.TryGetValue(name, out ordinal))
{
ordinal = 0;
}
nameOrdinalMap[name] = ++ordinal;
var key = new SyntaxNodeKey(name, ordinal);
nodeKeyMap = nodeKeyMap.Add(key, node);
}
return nodeKeyMap;
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> GetNodeKeyMap(SyntaxTree syntaxTree)
{
return _treeToNodeKeyMaps.GetValue(syntaxTree, BuildNodeKeyMap);
}
public SyntaxNodeKey GetNodeKey(SyntaxNode node)
{
var nodeKey = TryGetNodeKey(node);
if (nodeKey.IsEmpty)
{
throw new ArgumentException();
}
return nodeKey;
}
public SyntaxNodeKey TryGetNodeKey(SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(node.SyntaxTree);
SyntaxNodeKey nodeKey;
if (!nodeKeyMap.TryGetKey(node, out nodeKey))
{
return SyntaxNodeKey.Empty;
}
return nodeKey;
}
public SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
SyntaxNode node;
if (!nodeKeyMap.TryGetValue(nodeKey, out node))
{
throw new ArgumentException();
}
return node;
}
public bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
return nodeKeyMap.TryGetValue(nodeKey, out node);
}
public abstract bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope);
public abstract IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent);
protected IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxTree syntaxTree)
{
return GetMemberNodes(syntaxTree.GetRoot(), includeSelf: true, recursive: true, logicalFields: true, onlySupportedNodes: true);
}
protected IEnumerable<SyntaxNode> GetLogicalMemberNodes(SyntaxNode container)
{
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: false);
}
public IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container)
{
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: true);
}
/// <summary>
/// Retrieves the members of a specified <paramref name="container"/> node. The members that are
/// returned can be controlled by passing various parameters.
/// </summary>
/// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
/// <param name="includeSelf">If true, the container is returned as well.</param>
/// <param name="recursive">If true, members are recursed to return descendant members as well
/// as immediate children. For example, a namespace would return the namespaces and types within.
/// However, if <paramref name="recursive"/> is true, members with the namespaces and types would
/// also be returned.</param>
/// <param name="logicalFields">If true, field declarations are broken into their respective declarators.
/// For example, the field "int x, y" would return two declarators, one for x and one for y in place
/// of the field.</param>
/// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param>
public abstract IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes);
public abstract string Language { get; }
public abstract string AssemblyAttributeString { get; }
public EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Event:
return (EnvDTE.CodeElement)ExternalCodeEvent.Create(state, projectId, (IEventSymbol)symbol);
case SymbolKind.Field:
return (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, (IFieldSymbol)symbol);
case SymbolKind.Method:
return (EnvDTE.CodeElement)ExternalCodeFunction.Create(state, projectId, (IMethodSymbol)symbol);
case SymbolKind.Namespace:
return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, (INamespaceSymbol)symbol);
case SymbolKind.NamedType:
var namedType = (INamedTypeSymbol)symbol;
switch (namedType.TypeKind)
{
case TypeKind.Class:
case TypeKind.Module:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, namedType);
case TypeKind.Delegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, namedType);
case TypeKind.Enum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, namedType);
case TypeKind.Interface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, namedType);
case TypeKind.Struct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, namedType);
default:
throw Exceptions.ThrowEFail();
}
case SymbolKind.Property:
return (EnvDTE.CodeElement)ExternalCodeProperty.Create(state, projectId, (IPropertySymbol)symbol);
default:
throw Exceptions.ThrowEFail();
}
}
/// <summary>
/// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/>
/// </summary>
public abstract EnvDTE.CodeElement CreateInternalCodeElement(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNode node);
public EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.Pointer ||
typeSymbol.TypeKind == TypeKind.TypeParameter ||
typeSymbol.TypeKind == TypeKind.Submission)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Error ||
typeSymbol.TypeKind == TypeKind.Unknown)
{
return ExternalCodeUnknown.Create(state, projectId, typeSymbol);
}
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Dynamic)
{
var obj = project.GetCompilationAsync().Result.GetSpecialType(SpecialType.System_Object);
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, obj);
}
EnvDTE.CodeElement element;
if (TryGetElementFromSource(state, project, typeSymbol, out element))
{
return element;
}
EnvDTE.vsCMElement elementKind = GetElementKind(typeSymbol);
switch (elementKind)
{
case EnvDTE.vsCMElement.vsCMElementClass:
case EnvDTE.vsCMElement.vsCMElementModule:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementInterface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementDelegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementEnum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementStruct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, typeSymbol);
default:
Debug.Fail("Unsupported element kind: " + elementKind);
throw Exceptions.ThrowEInvalidArg();
}
}
public abstract EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type);
public abstract EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract bool IsParameterNode(SyntaxNode node);
public abstract bool IsAttributeNode(SyntaxNode node);
public abstract bool IsAttributeArgumentNode(SyntaxNode node);
public abstract bool IsOptionNode(SyntaxNode node);
public abstract bool IsImportNode(SyntaxNode node);
public ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId)
{
var project = workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
return symbolId.Resolve(project.GetCompilationAsync().Result).Symbol;
}
protected EnvDTE.CodeFunction CreateInternalCodeAccessorFunction(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
var accessorKind = GetAccessorKind(node);
return CodeAccessorFunction.Create(state, parentObj, accessorKind);
}
protected EnvDTE.CodeAttribute CreateInternalCodeAttribute(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = GetEffectiveParentForAttribute(node);
AbstractCodeElement parentObject;
if (IsParameterNode(parentNode))
{
var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
else
{
var nodeKey = parentNode.AncestorsAndSelf()
.Select(n => TryGetNodeKey(n))
.FirstOrDefault(nk => nk != SyntaxNodeKey.Empty);
if (nodeKey == SyntaxNodeKey.Empty)
{
// This is an assembly-level attribute.
parentNode = fileCodeModel.GetSyntaxRoot();
parentObject = null;
}
else
{
parentNode = fileCodeModel.LookupNode(nodeKey);
var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
}
string name;
int ordinal;
GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal);
return CodeAttribute.Create(state, fileCodeModel, parentObject, name, ordinal);
}
protected EnvDTE80.CodeImport CreateInternalCodeImport(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode;
string name;
GetImportParentAndName(node, out parentNode, out name);
AbstractCodeElement parentObj = null;
if (parentNode != null)
{
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObj = ComAggregate.GetManagedObject<AbstractCodeElement>(parent);
}
return CodeImport.Create(state, fileCodeModel, parentObj, name);
}
protected EnvDTE.CodeParameter CreateInternalCodeParameter(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string name = GetParameterName(node);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeParameter.Create(state, parentObj, name);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeOptionStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
string name;
int ordinal;
GetOptionNameAndOrdinal(node.Parent, node, out name, out ordinal);
return CodeOptionsStatement.Create(state, fileCodeModel, name, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeInheritsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string namespaceName;
int ordinal;
GetInheritsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeInheritsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeImplementsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string namespaceName;
int ordinal;
GetImplementsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeImplementsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeAttributeArgument CreateInternalCodeAttributeArgument(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode attributeNode;
int index;
GetAttributeArgumentParentAndIndex(node, out attributeNode, out index);
var codeAttribute = CreateInternalCodeAttribute(state, fileCodeModel, attributeNode);
var codeAttributeObj = ComAggregate.GetManagedObject<CodeAttribute>(codeAttribute);
return CodeAttributeArgument.Create(state, codeAttributeObj, index);
}
public abstract EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
public abstract EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel);
public abstract string GetUnescapedName(string name);
public abstract string GetName(SyntaxNode node);
public abstract SyntaxNode GetNodeWithName(SyntaxNode node);
public abstract SyntaxNode SetName(SyntaxNode node, string name);
public abstract string GetFullName(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetFullName(ISymbol symbol);
public abstract string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel);
public void Rename(ISymbol symbol, string newName, Solution solution)
{
// TODO: (tomescht) make this testable through unit tests.
// Right now we have to go through the project system to find all
// the outstanding CodeElements which might be affected by the
// rename. This is silly. This functionality should be moved down
// into the service layer.
var workspace = solution.Workspace as VisualStudioWorkspaceImpl;
if (workspace == null)
{
throw Exceptions.ThrowEFail();
}
// Save the node keys.
var nodeKeyValidation = new NodeKeyValidation();
foreach (var project in workspace.ProjectTracker.Projects)
{
nodeKeyValidation.AddProject(project);
}
var optionSet = workspace.Services.GetService<IOptionService>().GetOptions();
// Rename symbol.
var newSolution = Renamer.RenameSymbolAsync(solution, symbol, newName, optionSet).WaitAndGetResult(CancellationToken.None);
var changedDocuments = newSolution.GetChangedDocuments(solution);
// Notify third parties of the coming rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
// Update the workspace.
if (!workspace.TryApplyChanges(newSolution))
{
throw Exceptions.ThrowEFail();
}
// Notify third parties of the completed rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments);
// Update the node keys.
nodeKeyValidation.RestoreKeys();
}
public VirtualTreePoint? GetStartPoint(SyntaxNode node, EnvDTE.vsCMPart? part)
{
return _nodeLocator.GetStartPoint(node, part);
}
public VirtualTreePoint? GetEndPoint(SyntaxNode node, EnvDTE.vsCMPart? part)
{
return _nodeLocator.GetEndPoint(node, part);
}
public abstract EnvDTE.vsCMAccess GetAccess(ISymbol symbol);
public abstract EnvDTE.vsCMAccess GetAccess(SyntaxNode node);
public abstract SyntaxNode GetNodeWithModifiers(SyntaxNode node);
public abstract SyntaxNode GetNodeWithType(SyntaxNode node);
public abstract SyntaxNode GetNodeWithInitializer(SyntaxNode node);
public abstract SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access);
public abstract EnvDTE.vsCMElement GetElementKind(SyntaxNode node);
protected EnvDTE.vsCMElement GetElementKind(ITypeSymbol typeSymbol)
{
switch (typeSymbol.TypeKind)
{
case TypeKind.Array:
case TypeKind.Class:
return EnvDTE.vsCMElement.vsCMElementClass;
case TypeKind.Interface:
return EnvDTE.vsCMElement.vsCMElementInterface;
case TypeKind.Struct:
return EnvDTE.vsCMElement.vsCMElementStruct;
case TypeKind.Enum:
return EnvDTE.vsCMElement.vsCMElementEnum;
case TypeKind.Delegate:
return EnvDTE.vsCMElement.vsCMElementDelegate;
case TypeKind.Module:
return EnvDTE.vsCMElement.vsCMElementModule;
default:
Debug.Fail("Unexpected TypeKind: " + typeSymbol.TypeKind);
throw Exceptions.ThrowEInvalidArg();
}
}
protected bool TryGetElementFromSource(CodeModelState state, Project project, ITypeSymbol typeSymbol, out EnvDTE.CodeElement element)
{
element = null;
if (!typeSymbol.IsDefinition)
{
return false;
}
// Here's the strategy for determine what source file we'd try to return an element from.
// 1. Prefer source files that we don't heuristically flag as generated code.
// 2. If all of the source files are generated code, pick the first one.
var generatedCodeRecognitionService = project.Solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>();
Compilation compilation = null;
Tuple<DocumentId, Location> generatedCode = null;
DocumentId chosenDocumentId = null;
Location chosenLocation = null;
foreach (var location in typeSymbol.Locations)
{
if (location.IsInSource)
{
compilation = compilation ?? project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
if (compilation.ContainsSyntaxTree(location.SourceTree))
{
var document = project.GetDocument(location.SourceTree);
if (generatedCodeRecognitionService?.IsGeneratedCode(document) == false)
{
chosenLocation = location;
chosenDocumentId = document.Id;
break;
}
else
{
generatedCode = generatedCode ?? Tuple.Create(document.Id, location);
}
}
}
}
if (chosenDocumentId == null && generatedCode != null)
{
chosenDocumentId = generatedCode.Item1;
chosenLocation = generatedCode.Item2;
}
if (chosenDocumentId != null)
{
var fileCodeModel = state.Workspace.GetFileCodeModel(chosenDocumentId);
if (fileCodeModel != null)
{
var underlyingFileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModel);
element = underlyingFileCodeModel.CodeElementFromPosition(chosenLocation.SourceSpan.Start, GetElementKind(typeSymbol));
return element != null;
}
}
return false;
}
public abstract bool IsAccessorNode(SyntaxNode node);
public abstract MethodKind GetAccessorKind(SyntaxNode node);
public abstract bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode);
public abstract bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode);
public abstract bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode);
public abstract bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode);
public abstract bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode);
public abstract bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode);
public abstract bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode);
public abstract bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode);
public abstract void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal);
public abstract void GetInheritsNamespaceAndOrdinal(SyntaxNode inheritsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetImplementsNamespaceAndOrdinal(SyntaxNode implementsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal);
public abstract SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode);
public abstract string GetAttributeTarget(SyntaxNode attributeNode);
public abstract string GetAttributeValue(SyntaxNode attributeNode);
public abstract SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value);
public abstract SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value);
public abstract SyntaxNode GetNodeWithAttributes(SyntaxNode node);
public abstract SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node);
public abstract SyntaxNode CreateAttributeNode(string name, string value, string target = null);
public abstract void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index);
public abstract SyntaxNode CreateAttributeArgumentNode(string name, string value);
public abstract string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode);
public abstract string GetImportAlias(SyntaxNode node);
public abstract string GetImportNamespaceOrType(SyntaxNode node);
public abstract void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name);
public abstract SyntaxNode CreateImportNode(string name, string alias = null);
public abstract string GetParameterName(SyntaxNode node);
public virtual string GetParameterFullName(SyntaxNode node)
{
return GetParameterName(node);
}
public abstract EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node);
public abstract SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind);
public abstract SyntaxNode CreateParameterNode(string name, string type);
public abstract EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name);
public abstract bool SupportsEventThrower { get; }
public abstract bool GetCanOverride(SyntaxNode memberNode);
public abstract SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind);
public abstract string GetComment(SyntaxNode node);
public abstract SyntaxNode SetComment(SyntaxNode node, string value);
public abstract EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode);
public abstract SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind);
public abstract EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol);
public abstract SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind);
public abstract string GetDocComment(SyntaxNode node);
public abstract SyntaxNode SetDocComment(SyntaxNode node, string value);
public abstract EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol);
public abstract EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind);
public abstract bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value);
public abstract bool GetIsConstant(SyntaxNode variableNode);
public abstract SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value);
public abstract bool GetIsDefault(SyntaxNode propertyNode);
public abstract SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value);
public abstract bool GetIsGeneric(SyntaxNode memberNode);
public abstract bool GetIsPropertyStyleEvent(SyntaxNode eventNode);
public abstract bool GetIsShared(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsShared(SyntaxNode memberNode, bool value);
public abstract bool GetMustImplement(SyntaxNode memberNode);
public abstract SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode);
public abstract SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind);
public abstract EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode);
public abstract SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract Document Delete(Document document, SyntaxNode node);
public abstract string GetMethodXml(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetInitExpression(SyntaxNode node);
public abstract SyntaxNode AddInitExpression(SyntaxNode node, string value);
public abstract CodeGenerationDestination GetDestination(SyntaxNode containerNode);
protected abstract Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination);
public Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
{
// Note: Some EnvDTE.vsCMAccess members aren't "bitwise-mutually-exclusive"
// Specifically, vsCMAccessProjectOrProtected (12) is a combination of vsCMAccessProject (4) and vsCMAccessProtected (8)
// We therefore check for this first.
if ((access & EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
{
return Accessibility.ProtectedOrInternal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPrivate) != 0)
{
return Accessibility.Private;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProject) != 0)
{
return Accessibility.Internal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProtected) != 0)
{
return Accessibility.Protected;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPublic) != 0)
{
return Accessibility.Public;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessDefault) != 0)
{
return GetDefaultAccessibility(targetSymbolKind, destination);
}
else
{
throw new ArgumentException(ServicesVSResources.InvalidAccess, "access");
}
}
public bool GetWithEvents(EnvDTE.vsCMAccess access)
{
return (access & EnvDTE.vsCMAccess.vsCMAccessWithEvents) != 0;
}
protected SpecialType GetSpecialType(EnvDTE.vsCMTypeRef type)
{
// TODO(DustinCa): Verify this list against VB
switch (type)
{
case EnvDTE.vsCMTypeRef.vsCMTypeRefBool:
return SpecialType.System_Boolean;
case EnvDTE.vsCMTypeRef.vsCMTypeRefByte:
return SpecialType.System_Byte;
case EnvDTE.vsCMTypeRef.vsCMTypeRefChar:
return SpecialType.System_Char;
case EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal:
return SpecialType.System_Decimal;
case EnvDTE.vsCMTypeRef.vsCMTypeRefDouble:
return SpecialType.System_Double;
case EnvDTE.vsCMTypeRef.vsCMTypeRefFloat:
return SpecialType.System_Single;
case EnvDTE.vsCMTypeRef.vsCMTypeRefInt:
return SpecialType.System_Int32;
case EnvDTE.vsCMTypeRef.vsCMTypeRefLong:
return SpecialType.System_Int64;
case EnvDTE.vsCMTypeRef.vsCMTypeRefObject:
return SpecialType.System_Object;
case EnvDTE.vsCMTypeRef.vsCMTypeRefShort:
return SpecialType.System_Int16;
case EnvDTE.vsCMTypeRef.vsCMTypeRefString:
return SpecialType.System_String;
case EnvDTE.vsCMTypeRef.vsCMTypeRefVoid:
return SpecialType.System_Void;
default:
// TODO: Support vsCMTypeRef2? It doesn't appear that Dev10 C# does...
throw new ArgumentException();
}
}
private ITypeSymbol GetSpecialType(EnvDTE.vsCMTypeRef type, Compilation compilation)
{
return compilation.GetSpecialType(GetSpecialType(type));
}
protected abstract ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position);
public abstract ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation);
public ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position)
{
if (type is EnvDTE.CodeTypeRef)
{
return GetTypeSymbolFromPartialName(((EnvDTE.CodeTypeRef)type).AsString, semanticModel, position);
}
else if (type is EnvDTE.CodeType)
{
return GetTypeSymbolFromFullName(((EnvDTE.CodeType)type).FullName, semanticModel.Compilation);
}
ITypeSymbol typeSymbol;
if (type is EnvDTE.vsCMTypeRef || type is int)
{
typeSymbol = GetSpecialType((EnvDTE.vsCMTypeRef)type, semanticModel.Compilation);
}
else if (type is string)
{
typeSymbol = GetTypeSymbolFromPartialName((string)type, semanticModel, position);
}
else
{
throw new InvalidOperationException();
}
if (typeSymbol == null)
{
throw new ArgumentException();
}
return typeSymbol;
}
public abstract SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type);
protected abstract int GetAttributeIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified attribute.
/// </summary>
public int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeIndexInContainer,
GetAttributeNodes);
}
protected abstract int GetAttributeArgumentIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeArgumentIndexInContainer,
GetAttributeArgumentNodes);
}
protected abstract int GetImportIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetImportIndexInContainer,
GetImportNodes);
}
protected abstract int GetParameterIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetParameterIndexInContainer,
GetParameterNodes);
}
/// <summary>
/// Finds the index of the first child within the container for which <paramref name="predicate"/> returns true.
/// Note that the result is a 1-based as that is what code model expects. Returns -1 if no match is found.
/// </summary>
protected abstract int GetMemberIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified member.
/// </summary>
public int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetMemberIndexInContainer,
n => GetMemberNodes(n, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false));
}
private int PositionVariantToInsertionIndex(
object position,
SyntaxNode containerNode,
FileCodeModel fileCodeModel,
Func<SyntaxNode, Func<SyntaxNode, bool>, int> getIndexInContainer,
Func<SyntaxNode, IEnumerable<SyntaxNode>> getChildNodes)
{
int result;
if (position is int)
{
result = (int)position;
}
else if (position is EnvDTE.CodeElement)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(position);
if (codeElement == null || codeElement.FileCodeModel != fileCodeModel)
{
throw Exceptions.ThrowEInvalidArg();
}
var positionNode = codeElement.LookupNode();
if (positionNode == null)
{
throw Exceptions.ThrowEFail();
}
result = getIndexInContainer(containerNode, child => child == positionNode);
}
else if (position is string)
{
var name = (string)position;
result = getIndexInContainer(containerNode, child => GetName(child) == name);
}
else if (position == null || position == Type.Missing)
{
result = 0;
}
else
{
// Nothing we can handle...
throw Exceptions.ThrowEInvalidArg();
}
// -1 means to insert at the end, so we'll return the last child.
return result == -1
? getChildNodes(containerNode).ToArray().Length
: result;
}
protected abstract SyntaxNode GetFieldFromVariableNode(SyntaxNode variableNode);
protected abstract SyntaxNode GetVariableFromFieldNode(SyntaxNode fieldNode);
protected abstract SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode attributeDeclarationNode);
protected void GetNodesAroundInsertionIndex<TSyntaxNode>(
TSyntaxNode containerNode,
int childIndexToInsertAfter,
out TSyntaxNode insertBeforeNode,
out TSyntaxNode insertAfterNode)
where TSyntaxNode : SyntaxNode
{
var childNodes = GetLogicalMemberNodes(containerNode).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(childIndexToInsertAfter >= 0 && childIndexToInsertAfter <= childNodes.Length);
// Initialize the nodes that we'll insert the new member before and after.
insertBeforeNode = null;
insertAfterNode = null;
if (childIndexToInsertAfter == 0)
{
if (childNodes.Length > 0)
{
insertBeforeNode = (TSyntaxNode)childNodes[0];
}
}
else
{
insertAfterNode = (TSyntaxNode)childNodes[childIndexToInsertAfter - 1];
if (childIndexToInsertAfter < childNodes.Length)
{
insertBeforeNode = (TSyntaxNode)childNodes[childIndexToInsertAfter];
}
}
if (insertBeforeNode != null)
{
insertBeforeNode = (TSyntaxNode)GetFieldFromVariableNode(insertBeforeNode);
}
if (insertAfterNode != null)
{
insertAfterNode = (TSyntaxNode)GetFieldFromVariableNode(insertAfterNode);
}
}
private int GetMemberInsertionIndex(SyntaxNode container, int insertionIndex)
{
var childNodes = GetLogicalMemberNodes(container).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(insertionIndex >= 0 && insertionIndex <= childNodes.Length);
if (insertionIndex == 0)
{
return 0;
}
else
{
var nodeAtIndex = GetFieldFromVariableNode(childNodes[insertionIndex - 1]);
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false).ToList().IndexOf(nodeAtIndex) + 1;
}
}
private int GetAttributeArgumentInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetAttributeInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetImportInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetParameterInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
protected abstract bool IsCodeModelNode(SyntaxNode node);
protected abstract TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span);
protected abstract SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode attribute, SyntaxNode container);
protected abstract SyntaxNode InsertImportIntoContainer(int index, SyntaxNode import, SyntaxNode container);
protected abstract SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container);
private Document FormatAnnotatedNode(Document document, SyntaxAnnotation annotation, IEnumerable<IFormattingRule> additionalRules, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var annotatedNode = root.GetAnnotatedNodesAndTokens(annotation).Single().AsNode();
var formattingSpan = GetSpanToFormat(root, annotatedNode.FullSpan);
var formattingRules = Formatter.GetDefaultFormattingRules(document);
if (additionalRules != null)
{
formattingRules = additionalRules.Concat(formattingRules);
}
return Formatter.FormatAsync(
document,
new TextSpan[] { formattingSpan },
options: null,
rules: formattingRules,
cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
}
private SyntaxNode InsertNode(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode node,
Func<int, SyntaxNode, SyntaxNode, SyntaxNode> insertNodeIntoContainer,
CancellationToken cancellationToken,
out Document newDocument)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
var gen = SyntaxGenerator.GetGenerator(document);
node = node.WithAdditionalAnnotations(annotation);
if (gen.GetDeclarationKind(node) != DeclarationKind.NamespaceImport)
{
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
node = node.WithAdditionalAnnotations(Simplifier.Annotation);
}
var newContainerNode = insertNodeIntoContainer(insertionIndex, node, containerNode);
var newRoot = root.ReplaceNode(containerNode, newContainerNode);
document = document.WithSyntaxRoot(newRoot);
if (!batchMode)
{
document = Simplifier.ReduceAsync(document, annotation, optionSet: null, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
}
document = FormatAnnotatedNode(document, annotation, new[] { _lineAdjustmentFormattingRule, _endRegionFormattingRule }, cancellationToken);
// out param
newDocument = document;
// new node
return document
.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken)
.GetAnnotatedNodesAndTokens(annotation)
.Single()
.AsNode();
}
/// <summary>
/// Override to determine whether <param name="newNode"/> adds a method body to <param name="node"/>.
/// This is used to determine whether a blank line should be added inside the body when formatting.
/// </summary>
protected abstract bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode);
public Document UpdateNode(
Document document,
SyntaxNode node,
SyntaxNode newNode,
CancellationToken cancellationToken)
{
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
var annotatedNode = newNode.WithAdditionalAnnotations(annotation, Simplifier.Annotation);
var oldRoot = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var newRoot = oldRoot.ReplaceNode(node, annotatedNode);
document = document.WithSyntaxRoot(newRoot);
var additionalRules = AddBlankLineToMethodBody(node, newNode)
? SpecializedCollections.SingletonEnumerable(_lineAdjustmentFormattingRule)
: null;
document = FormatAnnotatedNode(document, annotation, additionalRules, cancellationToken);
return document;
}
public SyntaxNode InsertAttribute(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeInsertionIndex(containerNode, insertionIndex),
containerNode,
attributeNode,
InsertAttributeListIntoContainer,
cancellationToken,
out newDocument);
return GetAttributeFromAttributeDeclarationNode(finalNode);
}
public SyntaxNode InsertAttributeArgument(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeArgumentNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeArgumentInsertionIndex(containerNode, insertionIndex),
containerNode,
attributeArgumentNode,
InsertAttributeArgumentIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertImport(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode importNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetImportInsertionIndex(containerNode, insertionIndex),
containerNode,
importNode,
InsertImportIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertParameter(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode parameterNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetParameterInsertionIndex(containerNode, insertionIndex),
containerNode,
parameterNode,
InsertParameterIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertMember(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode memberNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetMemberInsertionIndex(containerNode, insertionIndex),
containerNode,
memberNode,
InsertMemberNodeIntoContainer,
cancellationToken,
out newDocument);
return GetVariableFromFieldNode(finalNode);
}
public Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree)
{
return _eventCollector.Collect(oldTree, newTree);
}
public abstract bool IsNamespace(SyntaxNode node);
public abstract bool IsType(SyntaxNode node);
public virtual IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel)
{
// descendants may override (particularly VB).
return SpecializedCollections.EmptyList<string>();
}
public virtual bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel)
{
// descendants may override (particularly VB).
return false;
}
public virtual Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendants may override (particularly VB).
return document;
}
public virtual Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendants may override (particularly VB).
return document;
}
public abstract string[] GetFunctionExtenderNames();
public abstract object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetPropertyExtenderNames();
public abstract object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetExternalTypeExtenderNames();
public abstract object GetExternalTypeExtender(string name, string externalLocation);
public abstract string[] GetTypeExtenderNames();
public abstract object GetTypeExtender(string name, AbstractCodeType codeType);
public abstract bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags);
public virtual void AttachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void DetachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void EnsureBufferFormatted(ITextBuffer buffer)
{
// can be override by languages if needed
}
}
}
| |
namespace Mapbox.Unity.MeshGeneration.Data
{
using UnityEngine;
using Mapbox.Unity.MeshGeneration.Enums;
using Mapbox.Unity.Utilities;
using Utils;
using Mapbox.Map;
using System;
using Mapbox.Unity.Map;
using System.Collections.Generic;
public class UnityTile : MonoBehaviour
{
[SerializeField]
Texture2D _rasterData;
float[] _heightData;
float _relativeScale;
Texture2D _heightTexture;
Texture2D _loadingTexture;
List<Tile> _tiles = new List<Tile>();
MeshRenderer _meshRenderer;
public MeshRenderer MeshRenderer
{
get
{
if (_meshRenderer == null)
{
_meshRenderer = GetComponent<MeshRenderer>();
}
return _meshRenderer;
}
}
private MeshFilter _meshFilter;
public MeshFilter MeshFilter
{
get
{
if (_meshFilter == null)
{
_meshFilter = GetComponent<MeshFilter>();
}
return _meshFilter;
}
}
private Collider _collider;
public Collider Collider
{
get
{
if (_collider == null)
{
_collider = GetComponent<Collider>();
}
return _collider;
}
}
// TODO: should this be a string???
string _vectorData;
public string VectorData
{
get { return _vectorData; }
set
{
_vectorData = value;
OnVectorDataChanged(this);
}
}
RectD _rect;
public RectD Rect
{
get
{
return _rect;
}
}
UnwrappedTileId _unwrappedTileId;
public UnwrappedTileId UnwrappedTileId
{
get
{
return _unwrappedTileId;
}
}
CanonicalTileId _canonicalTileId;
public CanonicalTileId CanonicalTileId
{
get
{
return _canonicalTileId;
}
}
public float TileScale { get; internal set; }
public TilePropertyState RasterDataState;
public TilePropertyState HeightDataState;
public TilePropertyState VectorDataState;
public event Action<UnityTile> OnHeightDataChanged = delegate { };
public event Action<UnityTile> OnRasterDataChanged = delegate { };
public event Action<UnityTile> OnVectorDataChanged = delegate { };
internal void Initialize(IMapReadable map, UnwrappedTileId tileId, float scale, Texture2D loadingTexture = null)
{
TileScale = scale;
_relativeScale = 1 / Mathf.Cos(Mathf.Deg2Rad * (float)map.CenterLatitudeLongitude.x);
_rect = Conversions.TileBounds(tileId);
_unwrappedTileId = tileId;
_canonicalTileId = tileId.Canonical;
_loadingTexture = loadingTexture;
gameObject.SetActive(true);
}
internal void Recycle()
{
if (_loadingTexture)
{
MeshRenderer.material.mainTexture = _loadingTexture;
}
gameObject.SetActive(false);
// Reset internal state.
RasterDataState = TilePropertyState.None;
HeightDataState = TilePropertyState.None;
VectorDataState = TilePropertyState.None;
OnHeightDataChanged = delegate { };
OnRasterDataChanged = delegate { };
OnVectorDataChanged = delegate { };
Cancel();
_tiles.Clear();
// HACK: this is for vector layer features and such.
// It's slow and wasteful, but a better solution will be difficult.
var childCount = transform.childCount;
if (childCount > 0)
{
for (int i = 0; i < childCount; i++)
{
Destroy(transform.GetChild(i).gameObject);
}
}
}
internal void SetHeightData(byte[] data, float heightMultiplier = 1f, bool useRelative = false)
{
// HACK: compute height values for terrain. We could probably do this without a texture2d.
if (_heightTexture == null)
{
_heightTexture = new Texture2D(0, 0);
}
_heightTexture.LoadImage(data);
byte[] rgbData = _heightTexture.GetRawTextureData();
// Get rid of this temporary texture. We don't need to bloat memory.
_heightTexture.LoadImage(null);
if (_heightData == null)
{
_heightData = new float[256 * 256];
}
var relativeScale = useRelative ? _relativeScale : 1f;
for (int xx = 0; xx < 256; ++xx)
{
for (int yy = 0; yy < 256; ++yy)
{
float r = rgbData[(xx * 256 + yy) * 4 + 1];
float g = rgbData[(xx * 256 + yy) * 4 + 2];
float b = rgbData[(xx * 256 + yy) * 4 + 3];
_heightData[xx * 256 + yy] = relativeScale * heightMultiplier * Conversions.GetAbsoluteHeightFromColor(r, g, b);
}
}
HeightDataState = TilePropertyState.Loaded;
OnHeightDataChanged(this);
}
public float QueryHeightData(float x, float y)
{
if (_heightData != null)
{
var intX = (int)Mathf.Clamp(x * 256, 0, 255);
var intY = (int)Mathf.Clamp(y * 256, 0, 255);
return _heightData[intY * 256 + intX] * TileScale;
}
return 0;
}
public void SetLoadingTexture(Texture2D texture)
{
MeshRenderer.material.mainTexture = texture;
}
public void SetRasterData(byte[] data, bool useMipMap, bool useCompression)
{
// Don't leak the texture, just reuse it.
if (_rasterData == null)
{
_rasterData = new Texture2D(0, 0, TextureFormat.RGB24, useMipMap);
_rasterData.wrapMode = TextureWrapMode.Clamp;
}
_rasterData.LoadImage(data);
if (useCompression)
{
// High quality = true seems to decrease image quality?
_rasterData.Compress(false);
}
MeshRenderer.material.mainTexture = _rasterData;
RasterDataState = TilePropertyState.Loaded;
OnRasterDataChanged(this);
}
public Texture2D GetRasterData()
{
return _rasterData;
}
internal void AddTile(Tile tile)
{
_tiles.Add(tile);
}
public void Cancel()
{
for (int i = 0, _tilesCount = _tiles.Count; i < _tilesCount; i++)
{
_tiles[i].Cancel();
}
}
void OnDestroy()
{
Cancel();
if (_heightTexture != null)
{
Destroy(_heightTexture);
}
if (_rasterData != null)
{
Destroy(_rasterData);
}
}
}
}
| |
// <copyright file="V97Network.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium.DevTools.V97.Fetch;
using OpenQA.Selenium.DevTools.V97.Network;
namespace OpenQA.Selenium.DevTools.V97
{
/// <summary>
/// Class providing functionality for manipulating network calls using version 89 of the DevTools Protocol
/// </summary>
public class V97Network : DevTools.Network
{
private FetchAdapter fetch;
private NetworkAdapter network;
/// <summary>
/// Initializes a new instance of the <see cref="V97Network"/> class.
/// </summary>
/// <param name="network">The adapter for the Network domain.</param>
/// <param name="fetch">The adapter for the Fetch domain.</param>
public V97Network(NetworkAdapter network, FetchAdapter fetch)
{
this.network = network;
this.fetch = fetch;
fetch.AuthRequired += OnFetchAuthRequired;
fetch.RequestPaused += OnFetchRequestPaused;
}
/// <summary>
/// Asynchronously disables network caching.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task DisableNetworkCaching()
{
await network.SetCacheDisabled(new SetCacheDisabledCommandSettings() { CacheDisabled = true });
}
/// <summary>
/// Asynchronously enables network caching.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task EnableNetworkCaching()
{
await network.SetCacheDisabled(new SetCacheDisabledCommandSettings() { CacheDisabled = false });
}
public override async Task EnableNetwork()
{
await network.Enable(new Network.EnableCommandSettings());
}
public override async Task DisableNetwork()
{
await network.Disable();
}
/// <summary>
/// Asynchronously enables the fetch domain for all URL patterns.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task EnableFetchForAllPatterns()
{
await fetch.Enable(new OpenQA.Selenium.DevTools.V97.Fetch.EnableCommandSettings()
{
Patterns = new OpenQA.Selenium.DevTools.V97.Fetch.RequestPattern[]
{
new OpenQA.Selenium.DevTools.V97.Fetch.RequestPattern() { UrlPattern = "*", RequestStage = RequestStage.Request },
new OpenQA.Selenium.DevTools.V97.Fetch.RequestPattern() { UrlPattern = "*", RequestStage = RequestStage.Response }
},
HandleAuthRequests = true
});
}
/// <summary>
/// Asynchronously diables the fetch domain.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task DisableFetch()
{
await fetch.Disable();
}
/// <summary>
/// Asynchronously sets the override of the user agent settings.
/// </summary>
/// <param name="userAgent">A <see cref="UserAgent"/> object containing the user agent values to override.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task SetUserAgentOverride(UserAgent userAgent)
{
await network.SetUserAgentOverride(new SetUserAgentOverrideCommandSettings()
{
UserAgent = userAgent.UserAgentString,
AcceptLanguage = userAgent.AcceptLanguage,
Platform = userAgent.Platform
});
}
/// <summary>
/// Asynchronously continues an intercepted network request.
/// </summary>
/// <param name="requestData">The <see cref="HttpRequestData"/> of the request.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueRequest(HttpRequestData requestData)
{
var commandSettings = new ContinueRequestCommandSettings()
{
RequestId = requestData.RequestId,
Method = requestData.Method,
Url = requestData.Url,
};
if (requestData.Headers.Count > 0)
{
List<HeaderEntry> headers = new List<HeaderEntry>();
foreach (KeyValuePair<string, string> headerPair in requestData.Headers)
{
headers.Add(new HeaderEntry() { Name = headerPair.Key, Value = headerPair.Value });
}
commandSettings.Headers = headers.ToArray();
}
if (!string.IsNullOrEmpty(requestData.PostData))
{
commandSettings.PostData = requestData.PostData;
}
await fetch.ContinueRequest(commandSettings);
}
/// <summary>
/// Asynchronously continues an intercepted network request.
/// </summary>
/// <param name="requestData">The <see cref="HttpRequestData"/> of the request.</param>
/// <param name="responseData">The <see cref="HttpResponseData"/> with which to respond to the request</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueRequestWithResponse(HttpRequestData requestData, HttpResponseData responseData)
{
var commandSettings = new FulfillRequestCommandSettings()
{
RequestId = requestData.RequestId,
ResponseCode = responseData.StatusCode,
};
if (responseData.Headers.Count > 0 || responseData.CookieHeaders.Count > 0)
{
List<HeaderEntry> headers = new List<HeaderEntry>();
foreach (KeyValuePair<string, string> headerPair in responseData.Headers)
{
headers.Add(new HeaderEntry() { Name = headerPair.Key, Value = headerPair.Value });
}
foreach (string cookieHeader in responseData.CookieHeaders)
{
headers.Add(new HeaderEntry() { Name = "Set-Cookie", Value = cookieHeader });
}
commandSettings.ResponseHeaders = headers.ToArray();
}
if (!string.IsNullOrEmpty(responseData.Body))
{
commandSettings.Body = Convert.ToBase64String(Encoding.UTF8.GetBytes(responseData.Body));
}
await fetch.FulfillRequest(commandSettings);
}
/// <summary>
/// Asynchronously contines an intercepted network call without modification.
/// </summary>
/// <param name="requestData">The <see cref="HttpRequestData"/> of the network call.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueRequestWithoutModification(HttpRequestData requestData)
{
await fetch.ContinueRequest(new ContinueRequestCommandSettings() { RequestId = requestData.RequestId });
}
/// <summary>
/// Asynchronously continues an intercepted network call using authentication.
/// </summary>
/// <param name="requestId">The ID of the network request for which to continue with authentication.</param>
/// <param name="userName">The user name with which to authenticate.</param>
/// <param name="password">The password with which to authenticate.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueWithAuth(string requestId, string userName, string password)
{
await fetch.ContinueWithAuth(new ContinueWithAuthCommandSettings()
{
RequestId = requestId,
AuthChallengeResponse = new V97.Fetch.AuthChallengeResponse()
{
Response = V97.Fetch.AuthChallengeResponseResponseValues.ProvideCredentials,
Username = userName,
Password = password
}
});
}
/// <summary>
/// Asynchronously cancels authorization of an intercepted network request.
/// </summary>
/// <param name="requestId">The ID of the network request for which to cancel authentication.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task CancelAuth(string requestId)
{
await fetch.ContinueWithAuth(new ContinueWithAuthCommandSettings()
{
RequestId = requestId,
AuthChallengeResponse = new OpenQA.Selenium.DevTools.V97.Fetch.AuthChallengeResponse()
{
Response = V97.Fetch.AuthChallengeResponseResponseValues.CancelAuth
}
});
}
/// <summary>
/// Asynchronously adds the response body to the provided <see cref="HttpResponseData"/> object.
/// </summary>
/// <param name="responseData">The <see cref="HttpResponseData"/> object to which to add the response body.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task AddResponseBody(HttpResponseData responseData)
{
// If the response is a redirect, retrieving the body will throw an error in CDP.
if (responseData.StatusCode < 300 || responseData.StatusCode > 399)
{
var bodyResponse = await fetch.GetResponseBody(new Fetch.GetResponseBodyCommandSettings() { RequestId = responseData.RequestId });
if (bodyResponse.Base64Encoded)
{
responseData.Body = Encoding.UTF8.GetString(Convert.FromBase64String(bodyResponse.Body));
}
else
{
responseData.Body = bodyResponse.Body;
}
}
}
/// <summary>
/// Asynchronously contines an intercepted network response without modification.
/// </summary>
/// <param name="responseData">The <see cref="HttpResponseData"/> of the network response.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ContinueResponseWithoutModification(HttpResponseData responseData)
{
await fetch.ContinueRequest(new ContinueRequestCommandSettings() { RequestId = responseData.RequestId });
}
private void OnFetchAuthRequired(object sender, Fetch.AuthRequiredEventArgs e)
{
AuthRequiredEventArgs wrapped = new AuthRequiredEventArgs()
{
RequestId = e.RequestId,
Uri = e.Request.Url
};
this.OnAuthRequired(wrapped);
}
private void OnFetchRequestPaused(object sender, Fetch.RequestPausedEventArgs e)
{
if (e.ResponseErrorReason == null && e.ResponseStatusCode == null)
{
RequestPausedEventArgs wrapped = new RequestPausedEventArgs();
wrapped.RequestData = new HttpRequestData()
{
RequestId = e.RequestId,
Method = e.Request.Method,
Url = e.Request.Url,
PostData = e.Request.PostData,
Headers = new Dictionary<string, string>(e.Request.Headers)
};
this.OnRequestPaused(wrapped);
}
else
{
ResponsePausedEventArgs wrappedResponse = new ResponsePausedEventArgs();
wrappedResponse.ResponseData = new HttpResponseData()
{
RequestId = e.RequestId,
Url = e.Request.Url,
ResourceType = e.ResourceType.ToString()
};
if (e.ResponseStatusCode.HasValue)
{
wrappedResponse.ResponseData.StatusCode = e.ResponseStatusCode.Value;
}
if (e.ResponseHeaders != null)
{
foreach (var header in e.ResponseHeaders)
{
if (header.Name.ToLowerInvariant() == "set-cookie")
{
wrappedResponse.ResponseData.CookieHeaders.Add(header.Value);
}
else
{
if (wrappedResponse.ResponseData.Headers.ContainsKey(header.Name))
{
string currentHeaderValue = wrappedResponse.ResponseData.Headers[header.Name];
wrappedResponse.ResponseData.Headers[header.Name] = currentHeaderValue + ", " + header.Value;
}
else
{
wrappedResponse.ResponseData.Headers.Add(header.Name, header.Value);
}
}
}
}
this.OnResponsePaused(wrappedResponse);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Collections.Tests
{
public class Hashtable_RemoveTests
{
[Fact]
public void TestRemove()
{
Hashtable hash = null;
int ii;
HashConfuse hshcnf1;
string strValue;
ArrayList alst;
Boolean fRetValue;
int iCount;
Random rnd1;
int iElement;
#region "TestData"
string[] strSuperHeroes =
{
"Captain Marvel" , //0
"Batgirl" , //1
"Nightwing" , //2
"Green Lantern" , //3
"Robin" , //4
"Superman" , //5
"Black Canary" , //6
"Spiderman" , //7
"Iron Man" , //8
"Wonder Girl" , //9
"Batman" , //10
"Flash" , //11
"Green Arrow" , //12
"Atom" , //13
"Steel" , //14
"Powerman" , //15
};
string[] strSecretIdentities =
{
"Batson, Billy" , //0
"Gordan, Barbara" , //1
"Grayson, Dick" , //2
"Jordan, Hal" , //3
"Drake, Tim" , //4
"Kent, Clark" , //5
"Lance, Dinah" , //6
"Parker, Peter" , //7
"Stark, Tony" , //8
"Troy, Donna" , //9
"Wayne, Bruce" , //10
"West, Wally" , //11
"Queen, Oliver" , //12
"Palmer, Ray" , //13
"Irons, John Henry" , //14
"Cage, Luke" , //15
};
#endregion
// Allocate the hash table.
hash = new Hashtable();
Assert.NotNull(hash);
// Construct the hash table by adding items to the table.
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Add(strSuperHeroes[ii], strSecretIdentities[ii]);
}
// Validate additions to Hashtable.
Assert.Equal(strSuperHeroes.Length, hash.Count);
//
// [] Remove: Attempt to remove a bogus key entry from table.
//
hash.Remove("THIS IS A BOGUS KEY");
Assert.Equal(strSuperHeroes.Length, hash.Count);
//
// [] Remove: Attempt to remove a null key entry from table.
//
Assert.Throws<ArgumentNullException>(() =>
{
hash.Remove(null);
}
);
//
// [] Remove: Add key/value pair to Hashtable and remove items.
//
// Remove items from Hashtable.
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Remove(strSuperHeroes[ii]);
Assert.Equal(strSuperHeroes.Length - ii - 1, hash.Count);
}
//[]We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable
//does not expand but have to tread through collision bit set positions to insert the new elements. We do this
//by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that
//the hashtable does not expand as long as we have at most 7 elements at any given time?
hash = new Hashtable();
alst = new ArrayList();
for (int i = 0; i < 7; i++)
{
strValue = "Test_" + i;
hshcnf1 = new HashConfuse(strValue);
alst.Add(hshcnf1);
hash.Add(hshcnf1, strValue);
}
//we will delete and add 3 new ones here and then compare
fRetValue = true;
iCount = 7;
rnd1 = new Random(-55);
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 7; j++)
{
if (!((string)hash[alst[j]]).Equals(((HashConfuse)alst[j]).Word))
{
fRetValue = false;
}
}
//we delete 3 elements from the hashtable
for (int j = 0; j < 3; j++)
{
iElement = rnd1.Next(6);
hash.Remove(alst[iElement]);
alst.RemoveAt(iElement);
strValue = "Test_" + iCount++;
hshcnf1 = new HashConfuse(strValue);
alst.Add(hshcnf1);
hash.Add(hshcnf1, strValue);
}
}
Assert.True(fRetValue);
}
[Fact]
public void TestRemove02()
{
Hashtable hash = null;
int ii;
#region "Test Data"
string[] strSuperHeroes = new string[]
{
"Captain Marvel" , //0
"Batgirl" , //1
"Nightwing" , //2
"Green Lantern" , //3
"Robin" , //4
"Superman" , //5
"Black Canary" , //6
"Spiderman" , //7
"Iron Man" , //8
"Wonder Girl" , //9
"Batman" , //10
"Flash" , //11
"Green Arrow" , //12
"Atom" , //13
"Steel" , //14
"Powerman" , //15
};
string[] strSecretIdentities = new string[]
{
"Batson, Billy" , //0
"Gordan, Barbara" , //1
"Grayson, Dick" , //2
"Jordan, Hal" , //3
"Drake, Tim" , //4
"Kent, Clark" , //5
"Lance, Dinah" , //6
"Parker, Peter" , //7
"Stark, Tony" , //8
"Troy, Donna" , //9
"Wayne, Bruce" , //10
"West, Wally" , //11
"Queen, Oliver" , //12
"Palmer, Ray" , //13
"Irons, John Henry" , //14
"Cage, Luke" , //15
};
#endregion
// Allocate the hash table.
hash = new Hashtable();
// Construct the hash table by adding items to the table.
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Add(strSuperHeroes[ii], strSecretIdentities[ii]);
}
// Validate additions to Hashtable.
Assert.Equal(strSuperHeroes.Length, hash.Count);
//
// []Remove: Attempt to remove a bogus key entry from table.
//
hash.Remove("THIS IS A BOGUS KEY");
Assert.Equal(hash.Count, strSuperHeroes.Length);
//
// [] Remove: Attempt to remove a null key entry from table.
//
Assert.Throws<ArgumentNullException>(() =>
{
hash.Remove(null);
}
);
//
// [] Remove: Add key/value pair to Hashtable and remove items.
//
// Remove items from Hashtable.
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Remove(strSuperHeroes[ii]);
Assert.Equal(strSuperHeroes.Length - ii - 1, hash.Count);
}
// now ADD ALL THE Entries the second time and remove them again
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Add(strSuperHeroes[ii], strSecretIdentities[ii]);
}
// remove elements
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Remove(strSuperHeroes[ii]);
Assert.Equal(hash.Count, strSuperHeroes.Length - ii - 1);
}
//[]Repeated removed
hash.Clear();
for (int iAnnoying = 0; iAnnoying < 10; iAnnoying++)
{
for (ii = 0; ii < strSuperHeroes.Length; ++ii)
{
hash.Remove(strSuperHeroes[ii]);
Assert.Equal(0, hash.Count);
}
}
}
}
class HashConfuse
{
private string _strValue;
public HashConfuse(string val)
{
_strValue = val;
}
public string Word
{
get { return _strValue; }
set { _strValue = value; }
}
public override int GetHashCode()
{
return 5;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using database.Database;
using JsonFlatFileDataStore;
using learning_gui.DataSources;
using learning_gui.Helpers;
using learning_gui.Types;
using Terminal.Gui;
#pragma warning disable 4014
namespace learning_gui.Views
{
public static class Welcome
{
private static bool Quit()
{
var n = MessageBox.Query(50, 7, "Quit", "Are you sure you want to quit this learning tool?", "Yes", "No");
return n == 0;
}
public static void CreateWelcomeUI(Toplevel top)
{
// Creates the top-level window to show
var win = new Window("Learning")
{
ColorScheme = Colors.Base,
X = 0,
Y = 1,
Width = Dim.Fill(),
Height = Dim.Fill()
};
var menu = new MenuBar(new[]
{
new MenuBarItem("_File", new[]
{
new MenuItem("_Quit", "", () =>
{
if (Quit()) top.Running = false;
})
})
});
top.Add(menu);
// load
var fileData = new FileListDataSource(
$"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}/LatinLearning/filesCache.json");
var list = new ListView(fileData)
{
X = 2,
Y = 2,
Width = Dim.Fill(),
Height = Dim.Height(win) - 10,
AllowsMarking = true
};
var addFileButton = new Button("Add vocab list")
{
Clicked = () =>
{
var dialog = new OpenDialog("Vocab list", "Select a text file containing an appropriately-formatted vocab list")
{
AllowsMultipleSelection = true,
CanChooseFiles = true,
CanChooseDirectories = false,
CanCreateDirectories = false,
DirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Vocab",
AllowedFileTypes = new[] {"txt"}
};
Application.Run(dialog);
if (dialog.FilePaths.Any())
foreach (var path in dialog.FilePaths)
((FileListDataSource) list.Source).AddItem(path);
list.SetNeedsDisplay();
},
X = 2,
Y = 0,
Width = 18,
Height = 1
};
var removeFileButton = new Button("Remove a vocab list")
{
Clicked = () =>
{
var entry = new TextField("")
{
X = 1,
Y = 5,
Width = Dim.Fill(),
Height = 1
};
void OkClicked()
{
if (entry.Text.ToString().Trim().ToLower() == "all")
for (var i = list.Source.Count - 1; i >= 0; i--)
((FileListDataSource) list.Source).RemoveItem(i);
var parts = entry.Text.ToString().Split(",").Select(p => p.Trim()).ToList();
foreach (var part in parts)
{
var worked = !int.TryParse(part, out var index);
if (worked || index <= 0 || index > list.Source.Count) continue;
((FileListDataSource) list.Source).RemoveItem(index - 1);
}
list.SetNeedsDisplay();
Application.RequestStop();
}
var ok = new Button("Ok")
{
Clicked = OkClicked
};
var cancel = new Button("Cancel")
{
Clicked = Application.RequestStop
};
var desc = new Label(
"Please enter the index(es) (1-based) of the file you \nwould like to remove, 'all' to remove all of them, \nor click Cancel to cancel this action")
{
X = 1,
Y = 1,
Height = 4
};
var dialog = new Dialog("Remove vocab list", 60, 14, ok, cancel) {desc, entry};
dialog.SetFocus(entry);
Application.Run(dialog);
},
X = Pos.Right(addFileButton) + 2,
Y = 0,
Width = 21,
Height = 1
};
win.Add(addFileButton);
win.Add(removeFileButton);
win.Add(list);
var checkBoxDataStore =
new DataStore($"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}/LatinLearning/checkboxData.json");
var toLatinCheckBox = new CheckBox("to Latin?")
{
X = 2,
Y = Pos.Bottom(win) - 6,
Width = 10,
Height = 1,
Disabled = false,
Checked = checkBoxDataStore.GetItem<bool>("toLatin")
};
toLatinCheckBox.Toggled += (sender, args) =>
{
checkBoxDataStore.ReplaceItemAsync("toLatin", ((CheckBox) sender).Checked, true);
Debug.WriteLine("Done");
};
win.Add(toLatinCheckBox);
var skipUnknownWordsCheckBox = new CheckBox("ignore Unknown words?")
{
X = 16,
Y = Pos.Bottom(win) - 6,
Width = 30,
Height = 1,
Disabled = false,
Checked = checkBoxDataStore.GetItem<bool>("skipUnknown")
};
skipUnknownWordsCheckBox.Toggled += (sender, args) =>
{
checkBoxDataStore.ReplaceItemAsync("skipUnknown", ((CheckBox) sender).Checked, true);
Debug.WriteLine("Done");
};
win.Add(skipUnknownWordsCheckBox);
var goButton = new Button("Go!")
{
X = 2,
Y = Pos.Bottom(win) - 5,
Width = 7,
Height = 1,
Clicked = () =>
{
var selectedFiles = ((FileListDataSource) list.Source).Items.Where(i => i.Marked).Select(i => WordList.Load(i.FileName)).ToList();
if (!selectedFiles.Any())
return;
var learning = new Learning(new LatinContext(), selectedFiles);
//var learnWindow = learning.DisplayUI(top.Frame);
var newWindow = learning.DisplayUI(toLatinCheckBox.Checked, skipUnknownWordsCheckBox.Checked);
Application.Run(newWindow);
}
};
win.Add(goButton);
var progressButton = new Button("check Progress")
{
X = 10,
Y = Pos.Bottom(win) - 5,
Width = 18,
Height = 1,
Clicked = () =>
{
var selectedFiles = ((FileListDataSource) list.Source).Items.Where(i => i.Marked).Select(i => WordList.Load(i.FileName)).ToList();
if (!selectedFiles.Any())
return;
var progress = new Progress(new LatinContext(), selectedFiles, skipUnknownWordsCheckBox.Checked);
var newWindow = progress.CreateUI();
Application.Run(newWindow);
}
};
win.Add(progressButton);
var checkDataButton = new Button("check Data")
{
X = 29,
Y = Pos.Bottom(win) - 5,
Width = 12,
Height = 1,
Clicked = () =>
{
var selectedFiles = ((FileListDataSource) list.Source).Items.Where(i => i.Marked).Select(i => WordList.Load(i.FileName)).ToList();
if (!selectedFiles.Any())
return;
var listEditor = new ListEditor(new LatinContext(), selectedFiles, skipUnknownWordsCheckBox.Checked);
var newWindow = listEditor.CreateUI();
Application.Run(newWindow);
}
};
win.Add(checkDataButton);
var addDefinitionsButton = new Button("Import definitions")
{
X = 45,
Y = Pos.Bottom(win) - 5,
Width = 12,
Height = 1,
Clicked = () =>
{
var selectedFiles = ((FileListDataSource) list.Source).Items.Where(i => i.Marked).Select(i => i.FileName).ToList();
if (!selectedFiles.Any())
return;
selectedFiles.ForEach(sf => FileHelpers.AddDefinitions(sf, skipUnknownWordsCheckBox.Checked));
MessageBox.Query(60, 10, "Definitions", "The definitions have been successfully imported.", "Close");
top.Add(win);
}
};
win.Add(addDefinitionsButton);
var closeButton = new Button("X")
{
Clicked = () => top.Running = false,
X = Pos.Right(win) - 8,
Y = 0,
Width = 5,
Height = 1
};
win.Add(closeButton);
top.Add(win);
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using ASC.Common.Data;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.Core.Users;
using ASC.CRM.Core;
using ASC.CRM.Core.Entities;
using ASC.Web.Studio.Utility;
namespace ASC.Feed.Aggregator.Modules.CRM
{
internal class CrmTasksModule : FeedModule
{
private const string item = "crmTask";
protected override string Table
{
get { return "crm_task"; }
}
protected override string LastUpdatedColumn
{
get { return "create_on"; }
}
protected override string TenantColumn
{
get { return "tenant_id"; }
}
protected override string DbId
{
get { return Constants.CrmDbId; }
}
public override string Name
{
get { return Constants.CrmTasksModule; }
}
public override string Product
{
get { return ModulesHelper.CRMProductName; }
}
public override Guid ProductID
{
get { return ModulesHelper.CRMProductID; }
}
public override bool VisibleFor(Feed feed, object data, Guid userId)
{
return base.VisibleFor(feed, data, userId) && CRMSecurity.CanGoToFeed((Task)data);
}
public override IEnumerable<Tuple<Feed, object>> GetFeeds(FeedFilter filter)
{
var query =
new SqlQuery("crm_task t")
.Select(TaskColumns().Select(t => "t." + t).ToArray())
.Where("t.tenant_id", filter.Tenant)
.Where(Exp.Between("t.create_on", filter.Time.From, filter.Time.To))
.LeftOuterJoin("crm_contact c",
Exp.EqColumns("c.id", "t.contact_id")
& Exp.Eq("c.tenant_id", filter.Tenant)
)
.Select(ContactColumns().Select(c => "c." + c).ToArray());
using (var db = DbManager.FromHttpContext(DbId))
{
var tasks = db.ExecuteList(query).ConvertAll(ToTask);
return tasks.Select(t => new Tuple<Feed, object>(ToFeed(t), t));
}
}
private static IEnumerable<string> TaskColumns()
{
return new[]
{
"id",
"title",
"description",
"deadline",
"responsible_id",
"contact_id",
"is_closed",
"entity_type",
"entity_id",
"category_id",
"create_by",
"create_on",
"last_modifed_by",
"last_modifed_on" // 13
};
}
private static IEnumerable<string> ContactColumns()
{
return new[]
{
"is_company", // 14
"id",
"notes",
"first_name",
"last_name",
"company_name",
"company_id",
"display_name",
"create_by",
"create_on",
"last_modifed_by",
"last_modifed_on" // 25
};
}
private static Task ToTask(object[] r)
{
var task = new Task
{
ID = Convert.ToInt32(r[0]),
Title = Convert.ToString(r[1]),
Description = Convert.ToString(r[2]),
DeadLine = Convert.ToDateTime(r[3]),
ResponsibleID = new Guid(Convert.ToString(r[4])),
ContactID = Convert.ToInt32(r[5]),
IsClosed = Convert.ToBoolean(r[6]),
EntityType = (EntityType)Convert.ToInt32(r[7]),
EntityID = Convert.ToInt32(r[8]),
CategoryID = Convert.ToInt32(r[9]),
CreateBy = new Guid(Convert.ToString(r[10])),
CreateOn = Convert.ToDateTime(r[11]),
LastModifedBy = new Guid(Convert.ToString(r[12])),
LastModifedOn = Convert.ToDateTime(r[13])
};
if (string.IsNullOrEmpty(Convert.ToString(r[14]))) return task;
var isCompany = Convert.ToBoolean(r[14]);
if (isCompany)
{
task.Contact = new Company
{
ID = Convert.ToInt32(r[15]),
About = Convert.ToString(r[16]),
CompanyName = Convert.ToString(r[19]),
CreateBy = new Guid(Convert.ToString(r[22])),
CreateOn = Convert.ToDateTime(r[23]),
LastModifedBy = new Guid(Convert.ToString(r[24])),
LastModifedOn = Convert.ToDateTime(r[25])
};
}
else
{
task.Contact = new Person
{
ID = Convert.ToInt32(r[15]),
About = Convert.ToString(r[16]),
FirstName = Convert.ToString(r[17]),
LastName = Convert.ToString(r[18]),
CompanyID = Convert.ToInt32(r[20]),
JobTitle = Convert.ToString(r[21]),
CreateBy = new Guid(Convert.ToString(r[22])),
CreateOn = Convert.ToDateTime(r[23]),
LastModifedBy = new Guid(Convert.ToString(r[24])),
LastModifedOn = Convert.ToDateTime(r[25])
};
}
return task;
}
private Feed ToFeed(Task task)
{
const string itemUrl = "/Products/CRM/Tasks.aspx";
return new Feed(task.CreateBy, task.CreateOn)
{
Item = item,
ItemId = task.ID.ToString(CultureInfo.InvariantCulture),
ItemUrl = CommonLinkUtility.ToAbsolute(itemUrl),
Product = Product,
Module = Name,
Title = task.Title,
Description = Helper.GetHtmlDescription(HttpUtility.HtmlEncode(task.Description)),
AdditionalInfo = Helper.GetUser(task.ResponsibleID).DisplayUserName(),
AdditionalInfo2 = task.Contact.GetTitle(),
Keywords = string.Format("{0} {1}", task.Title, task.Description),
HasPreview = false,
CanComment = false,
GroupId = GetGroupId(item, task.CreateBy)
};
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.BatchAI.Fluent.Models;
using Microsoft.Azure.Management.BatchAI.Fluent.Models.HasMountVolumes.Definition;
namespace Microsoft.Azure.Management.BatchAI.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.BatchAI.Fluent.AzureBlobFileSystem.Definition;
using Microsoft.Azure.Management.BatchAI.Fluent.AzureFileShare.Definition;
using Microsoft.Azure.Management.BatchAI.Fluent.BatchAICluster.Definition;
using Microsoft.Azure.Management.BatchAI.Fluent.BatchAICluster.Update;
using Microsoft.Azure.Management.BatchAI.Fluent.FileServer.Definition;
using Microsoft.Azure.Management.BatchAI.Fluent.NodeSetupTask.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System.Collections.Generic;
using System;
public partial class BatchAIClusterImpl
{
/// <summary>
/// Gets Begins the definition of setup task.
/// </summary>
/// <summary>
/// Gets the first stage of the setup task definition.
/// </summary>
NodeSetupTask.Definition.IBlank<BatchAICluster.Definition.IWithCreate> BatchAICluster.Definition.IWithSetupTask.DefineSetupTask()
{
return this.DefineSetupTask();
}
/// <param name="password">Admin user password (linux only).</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithScaleSettings BatchAICluster.Definition.IWithUserCredentials.WithPassword(string password)
{
return this.WithPassword(password);
}
/// <param name="sshPublicKey">SSH public keys used to authenticate with linux based VMs.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithScaleSettings BatchAICluster.Definition.IWithUserCredentials.WithSshPublicKey(string sshPublicKey)
{
return this.WithSshPublicKey(sshPublicKey);
}
/// <param name="userName">The name of the administrator account.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithUserCredentials BatchAICluster.Definition.IWithUserName.WithUserName(string userName)
{
return this.WithUserName(userName);
}
/// <param name="vmSize">Virtual machine size.</param>
/// <return>Next stage of the definition.</return>
BatchAICluster.Definition.IWithUserName BatchAICluster.Definition.IWithVMSize.WithVMSize(string vmSize)
{
return this.WithVMSize(vmSize);
}
/// <param name="resoureId">Azure Application Insights component resource id.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithAppInsightsKey BatchAICluster.Definition.IWithAppInsightsResourceId.WithAppInsightsComponentId(string resoureId)
{
return this.WithAppInsightsComponentId(resoureId);
}
/// <param name="instrumentationKey">Value of the Azure Application Insights instrumentation key.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithAppInsightsKey.WithInstrumentationKey(string instrumentationKey)
{
return this.WithInstrumentationKey(instrumentationKey);
}
/// <summary>
/// Specifies KeyVault Store and Secret which contains the value for the instrumentation key.
/// </summary>
/// <param name="keyVaultId">Fully qualified resource Id for the Key Vault.</param>
/// <param name="secretUrl">The URL referencing a secret in a Key Vault.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithAppInsightsKey.WithInstrumentationKeySecretReference(string keyVaultId, string secretUrl)
{
return this.WithInstrumentationKeySecretReference(keyVaultId, secretUrl);
}
/// <summary>
/// If autoScale settings are specified, the system automatically scales the cluster up and down (within
/// the supplied limits) based on the pending jobs on the cluster.
/// </summary>
/// <param name="minimumNodeCount">The minimum number of compute nodes the cluster can have.</param>
/// <param name="maximumNodeCount">The maximum number of compute nodes the cluster can have.</param>
/// <return>The next stage of the update.</return>
BatchAICluster.Update.IUpdate BatchAICluster.Update.IWithScaleSettings.WithAutoScale(int minimumNodeCount, int maximumNodeCount)
{
return this.WithAutoScale(minimumNodeCount, maximumNodeCount);
}
/// <summary>
/// If autoScale settings are specified, the system automatically scales the cluster up and down (within
/// the supplied limits) based on the pending jobs on the cluster.
/// </summary>
/// <param name="minimumNodeCount">The minimum number of compute nodes the cluster can have.</param>
/// <param name="maximumNodeCount">The maximum number of compute nodes the cluster can have.</param>
/// <param name="initialNodeCount">
/// The number of compute nodes to allocate on cluster creation.
/// Note that this value is used only during cluster creation.
/// </param>
/// <return>The next stage of the update.</return>
BatchAICluster.Update.IUpdate BatchAICluster.Update.IWithScaleSettings.WithAutoScale(int minimumNodeCount, int maximumNodeCount, int initialNodeCount)
{
return this.WithAutoScale(minimumNodeCount, maximumNodeCount, initialNodeCount);
}
/// <summary>
/// Specifies that cluster should be scaled by manual settings.
/// </summary>
/// <param name="targetNodeCount">The desired number of compute nodes in the Cluster.</param>
/// <return>The next stage of the update.</return>
BatchAICluster.Update.IUpdate BatchAICluster.Update.IWithScaleSettings.WithManualScale(int targetNodeCount)
{
return this.WithManualScale(targetNodeCount);
}
/// <summary>
/// Specifies that cluster should be scaled by manual settings.
/// </summary>
/// <param name="targetNodeCount">The desired number of compute nodes in the Cluster.</param>
/// <param name="deallocationOption">Determines what to do with the job(s) running on compute node if the cluster size is decreasing. The default value is requeue.</param>
/// <return>The next stage of the update.</return>
BatchAICluster.Update.IUpdate BatchAICluster.Update.IWithScaleSettings.WithManualScale(int targetNodeCount, DeallocationOption deallocationOption)
{
return this.WithManualScale(targetNodeCount, deallocationOption);
}
/// <summary>
/// If autoScale settings are specified, the system automatically scales the cluster up and down (within
/// the supplied limits) based on the pending jobs on the cluster.
/// </summary>
/// <param name="minimumNodeCount">The minimum number of compute nodes the cluster can have.</param>
/// <param name="maximumNodeCount">The maximum number of compute nodes the cluster can have.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithScaleSettings.WithAutoScale(int minimumNodeCount, int maximumNodeCount)
{
return this.WithAutoScale(minimumNodeCount, maximumNodeCount);
}
/// <summary>
/// If autoScale settings are specified, the system automatically scales the cluster up and down (within
/// the supplied limits) based on the pending jobs on the cluster.
/// </summary>
/// <param name="minimumNodeCount">The minimum number of compute nodes the cluster can have.</param>
/// <param name="maximumNodeCount">The maximum number of compute nodes the cluster can have.</param>
/// <param name="initialNodeCount">
/// The number of compute nodes to allocate on cluster creation.
/// Note that this value is used only during cluster creation.
/// </param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithScaleSettings.WithAutoScale(int minimumNodeCount, int maximumNodeCount, int initialNodeCount)
{
return this.WithAutoScale(minimumNodeCount, maximumNodeCount, initialNodeCount);
}
/// <summary>
/// Specifies that cluster should be scaled by manual settings.
/// </summary>
/// <param name="targetNodeCount">The desired number of compute nodes in the Cluster.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithScaleSettings.WithManualScale(int targetNodeCount)
{
return this.WithManualScale(targetNodeCount);
}
/// <summary>
/// Specifies that cluster should be scaled by manual settings.
/// </summary>
/// <param name="targetNodeCount">The desired number of compute nodes in the Cluster.</param>
/// <param name="deallocationOption">Determines what to do with the job(s) running on compute node if the cluster size is decreasing. The default value is requeue.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithScaleSettings.WithManualScale(int targetNodeCount, DeallocationOption deallocationOption)
{
return this.WithManualScale(targetNodeCount, deallocationOption);
}
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithVMPriority.WithLowPriority()
{
return this.WithLowPriority();
}
/// <summary>
/// Gets Begins the definition of Azure blob file system reference to be mounted on each cluster node.
/// </summary>
/// <summary>
/// Gets the first stage of Azure blob file system reference definition.
/// </summary>
AzureBlobFileSystem.Definition.IBlank<BatchAICluster.Definition.IWithCreate> IWithMountVolumes<IWithCreate>.DefineAzureBlobFileSystem()
{
return this.DefineAzureBlobFileSystem();
}
/// <summary>
/// Specifies the details of the file system to mount on the compute cluster nodes.
/// </summary>
/// <param name="mountCommand">Command used to mount the unmanaged file system.</param>
/// <param name="relativeMountPath">The relative path on the compute cluster node where the file system will be mounted.</param>
/// <return>The next stage of Batch AI cluster definition.</return>
BatchAICluster.Definition.IWithCreate IWithMountVolumes<IWithCreate>.WithUnmanagedFileSystem(string mountCommand, string relativeMountPath)
{
return this.WithUnmanagedFileSystem(mountCommand, relativeMountPath);
}
/// <summary>
/// Gets Begins the definition of Azure file server reference.
/// </summary>
/// <summary>
/// Gets the first stage of file server reference definition.
/// </summary>
FileServer.Definition.IBlank<BatchAICluster.Definition.IWithCreate> IWithMountVolumes<IWithCreate>.DefineFileServer()
{
return this.DefineFileServer();
}
/// <param name="subnetId">Identifier of the subnet.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithSubnet.WithSubnet(string subnetId)
{
return this.WithSubnet(subnetId);
}
/// <param name="networkId">Identifier of the network.</param>
/// <param name="subnetName">Subnet name.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithSubnet.WithSubnet(string networkId, string subnetName)
{
return this.WithSubnet(networkId, subnetName);
}
/// <summary>
/// Gets Begins the definition of Azure file share reference to be mounted on each cluster node.
/// </summary>
/// <summary>
/// Gets the first stage of file share reference definition.
/// </summary>
AzureFileShare.Definition.IBlank<BatchAICluster.Definition.IWithCreate> IWithMountVolumes<BatchAICluster.Definition.IWithCreate>.DefineAzureFileShare()
{
return this.DefineAzureFileShare();
}
/// <summary>
/// Specifies virtual machine image.
/// </summary>
/// <param name="publisher">Publisher of the image.</param>
/// <param name="offer">Offer of the image.</param>
/// <param name="sku">Sku of the image.</param>
/// <param name="version">Version of the image.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithVirtualMachineImage.
WithVirtualMachineImage(string publisher, string offer, string sku, string version)
{
return this.WithVirtualMachineImage(publisher, offer, sku,
version);
}
/// <summary>
/// Specifies virtual machine image.
/// </summary>
/// <param name="publisher">Publisher of the image.</param>
/// <param name="offer">Offer of the image.</param>
/// <param name="sku">Sku of the image.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithVirtualMachineImage.
WithVirtualMachineImage(string publisher, string offer, string sku)
{
return this.WithVirtualMachineImage(publisher, offer, sku);
}
/// <summary>
/// Computes nodes of the cluster will be created using this custom image. This is of the form
/// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName}.
/// The virtual machine image must be in the same region and subscription as
/// the cluster. For information about the firewall settings for the Batch
/// node agent to communicate with the Batch service see
/// https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration.
/// Note, you need to provide publisher, offer and sku of the base OS image
/// of which the custom image has been derived from.
/// </summary>
/// <param name="virtualMachineImageId">The ARM resource identifier of the virtual machine image.</param>
/// <param name="publisher">Publisher of the image.</param>
/// <param name="offer">Offer of the image.</param>
/// <param name="sku">Sku of the image.</param>
/// <return>The next stage of the definition.</return>
BatchAICluster.Definition.IWithCreate BatchAICluster.Definition.IWithVirtualMachineImage.WithVirtualMachineImageId(string virtualMachineImageId, string publisher, string offer, string sku)
{
return this.WithVirtualMachineImageId(virtualMachineImageId, publisher, offer, sku);
}
/// <summary>
/// Gets settings for OS image and mounted data volumes.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.VirtualMachineConfiguration Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.VirtualMachineConfiguration
{
get
{
return this.VirtualMachineConfiguration();
}
}
/// <summary>
/// Gets the provisioning state transition time of the cluster.
/// </summary>
System.DateTime Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.ProvisioningStateTransitionTime
{
get
{
return this.ProvisioningStateTransitionTime();
}
}
/// <summary>
/// Gets All virtual machines in a cluster are the same size. For information
/// about available VM sizes for clusters using images from the Virtual
/// Machines Marketplace (see Sizes for Virtual Machines (Linux) or Sizes
/// for Virtual Machines (Windows). Batch AI service supports all Azure VM
/// sizes except STANDARD_A0 and those with premium storage (STANDARD_GS,
/// STANDARD_DS, and STANDARD_DSV2 series).
/// </summary>
/// <summary>
/// Gets the size of the virtual machines in the cluster.
/// </summary>
string Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.VMSize
{
get
{
return this.VMSize();
}
}
/// <summary>
/// Gets the number of compute nodes currently assigned to the cluster.
/// </summary>
int Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.CurrentNodeCount
{
get
{
return this.CurrentNodeCount();
}
}
/// <summary>
/// Gets counts of various node states on the cluster.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.NodeStateCounts Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.NodeStateCounts
{
get
{
return this.NodeStateCounts();
}
}
/// <summary>
/// Gets administrator account name for compute nodes.
/// </summary>
string Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.AdminUserName
{
get
{
return this.AdminUserName();
}
}
/// <summary>
/// Gets the time at which the cluster entered its current allocation state.
/// </summary>
System.DateTime Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.AllocationStateTransitionTime
{
get
{
return this.AllocationStateTransitionTime();
}
}
/// <summary>
/// Gets desired scale for the Cluster.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.ScaleSettings Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.ScaleSettings
{
get
{
return this.ScaleSettings();
}
}
/// <summary>
/// Gets Indicates whether the cluster is resizing.
/// </summary>
/// <summary>
/// Gets cluster allocation state.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.AllocationState Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.AllocationState
{
get
{
return this.AllocationState();
}
}
/// <summary>
/// Gets all the errors encountered by various compute nodes during node setup.
/// </summary>
System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.BatchAI.Fluent.Models.BatchAIError> Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.Errors
{
get
{
return this.Errors();
}
}
/// <summary>
/// Gets the provisioning state of the cluster.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.ProvisioningState Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.ProvisioningState
{
get
{
return this.ProvisioningState();
}
}
/// <summary>
/// Gets the creation time of the cluster.
/// </summary>
System.DateTime Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.CreationTime
{
get
{
return this.CreationTime();
}
}
/// <summary>
/// Gets the identifier of the subnet.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.ResourceId Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.Subnet
{
get
{
return this.Subnet();
}
}
/// <summary>
/// Gets The default value is dedicated. The node can get preempted while the
/// task is running if lowpriority is choosen. This is best suited if the
/// workload is checkpointing and can be restarted.
/// </summary>
/// <summary>
/// Gets virtual machine priority status.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.VmPriority Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.VMPriority
{
get
{
return this.VMPriority();
}
}
/// <summary>
/// Gets setup to be done on all compute nodes in the Cluster.
/// </summary>
Microsoft.Azure.Management.BatchAI.Fluent.Models.NodeSetup Microsoft.Azure.Management.BatchAI.Fluent.IBatchAICluster.NodeSetup
{
get
{
return this.NodeSetup();
}
}
}
}
| |
using System;
using System.CodeDom;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
namespace Orleans.Messaging
{
// <summary>
// This class is used on the client only.
// It provides the client counterpart to the Gateway and GatewayAcceptor classes on the silo side.
//
// There is one ProxiedMessageCenter instance per OutsideRuntimeClient. There can be multiple ProxiedMessageCenter instances
// in a single process, but because RuntimeClient keeps a static pointer to a single OutsideRuntimeClient instance, this is not
// generally done in practice.
//
// Each ProxiedMessageCenter keeps a collection of GatewayConnection instances. Each of these represents a bidirectional connection
// to a single gateway endpoint. Requests are assigned to a specific connection based on the target grain ID, so that requests to
// the same grain will go to the same gateway, in sending order. To do this efficiently and scalably, we bucket grains together
// based on their hash code mod a reasonably large number (currently 8192).
//
// When the first message is sent to a bucket, we assign a gateway to that bucket, selecting in round-robin fashion from the known
// gateways. If this is the first message to be sent to the gateway, we will create a new connection for it and assign the bucket to
// the new connection. Either way, all messages to grains in that bucket will be sent to the assigned connection as long as the
// connection is live.
//
// Connections stay live as long as possible. If a socket error or other communications error occurs, then the client will try to
// reconnect twice before giving up on the gateway. If the connection cannot be re-established, then the gateway is deemed (temporarily)
// dead, and any buckets assigned to the connection are unassigned (so that the next message sent will cause a new gateway to be selected).
// There is no assumption that this death is permanent; the system will try to reuse the gateway every 5 minutes.
//
// The list of known gateways is managed by the GatewayManager class. See comments there for details...
// =======================================================================================================================================
// Locking and lock protocol:
// The ProxiedMessageCenter instance itself may be accessed by many client threads simultaneously, and each GatewayConnection instance
// is accessed by its own thread, by the thread for its Receiver, and potentially by client threads from within the ProxiedMessageCenter.
// Thus, we need locks to protect the various data structured from concurrent modifications.
//
// Each GatewayConnection instance has a "lockable" field that is used to lock local information. This lock is used by both the GatewayConnection
// thread and the Receiver thread.
//
// The ProxiedMessageCenter instance also has a "lockable" field. This lock is used by any client thread running methods within the instance.
//
// Note that we take care to ensure that client threads never need locked access to GatewayConnection state and GatewayConnection threads never need
// locked access to ProxiedMessageCenter state. Thus, we don't need to worry about lock ordering across these objects.
//
// Finally, the GatewayManager instance within the ProxiedMessageCenter has two collections, knownGateways and knownDead, that it needs to
// protect with locks. Rather than using a "lockable" field, each collection is lcoked to protect the collection.
// All sorts of threads can run within the GatewayManager, including client threads and GatewayConnection threads, so we need to
// be careful about locks here. The protocol we use is to always take GatewayManager locks last, to only take them within GatewayManager methods,
// and to always release them before returning from the method. In addition, we never simultaneously hold the knownGateways and knownDead locks,
// so there's no need to worry about the order in which we take and release those locks.
// </summary>
internal class ProxiedMessageCenter : IMessageCenter
{
#region Constants
internal static readonly TimeSpan MINIMUM_INTERCONNECT_DELAY = TimeSpan.FromMilliseconds(100); // wait one tenth of a second between connect attempts
internal const int CONNECT_RETRY_COUNT = 2; // Retry twice before giving up on a gateway server
#endregion
internal GrainId ClientId { get; private set; }
internal bool Running { get; private set; }
internal readonly GatewayManager GatewayManager;
internal readonly BlockingCollection<Message> PendingInboundMessages;
private readonly Dictionary<Uri, GatewayConnection> gatewayConnections;
private int numMessages;
// The grainBuckets array is used to select the connection to use when sending an ordered message to a grain.
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
private readonly WeakReference[] grainBuckets;
private readonly Logger logger;
private readonly object lockable;
public SiloAddress MyAddress { get; private set; }
public IMessagingConfiguration MessagingConfiguration { get; private set; }
private readonly QueueTrackingStatistic queueTracking;
public ProxiedMessageCenter(ClientConfiguration config, IPAddress localAddress, int gen, GrainId clientId, IGatewayListProvider gatewayListProvider)
{
lockable = new object();
MyAddress = SiloAddress.New(new IPEndPoint(localAddress, 0), gen);
ClientId = clientId;
Running = false;
MessagingConfiguration = config;
GatewayManager = new GatewayManager(config, gatewayListProvider);
PendingInboundMessages = new BlockingCollection<Message>();
gatewayConnections = new Dictionary<Uri, GatewayConnection>();
numMessages = 0;
grainBuckets = new WeakReference[config.ClientSenderBuckets];
logger = LogManager.GetLogger("Messaging.ProxiedMessageCenter", LoggerType.Runtime);
if (logger.IsVerbose) logger.Verbose("Proxy grain client constructed");
IntValueStatistic.FindOrCreate(StatisticNames.CLIENT_CONNECTED_GATEWAY_COUNT, () =>
{
lock (gatewayConnections)
{
return gatewayConnections.Values.Count(conn => conn.IsLive);
}
});
if (StatisticsCollector.CollectQueueStats)
{
queueTracking = new QueueTrackingStatistic("ClientReceiver");
}
}
public void Start()
{
Running = true;
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnStartExecution();
}
if (logger.IsVerbose) logger.Verbose("Proxy grain client started");
}
public void PrepareToStop()
{
// put any pre stop logic here.
}
public void Stop()
{
Running = false;
Utils.SafeExecute(() =>
{
PendingInboundMessages.CompleteAdding();
});
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnStopExecution();
}
GatewayManager.Stop();
foreach (var gateway in gatewayConnections.Values)
{
gateway.Stop();
}
}
public void SendMessage(Message msg)
{
GatewayConnection gatewayConnection = null;
bool startRequired = false;
// If there's a specific gateway specified, use it
if (msg.TargetSilo != null)
{
Uri addr = msg.TargetSilo.ToGatewayUri();
lock (lockable)
{
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose("Creating gateway to {0} for pre-addressed message", addr);
startRequired = true;
}
}
}
// For untargeted messages to system targets, and for unordered messages, pick a next connection in round robin fashion.
else if (msg.TargetGrain.IsSystemTarget || msg.IsUnordered)
{
// Get the cached list of live gateways.
// Pick a next gateway name in a round robin fashion.
// See if we have a live connection to it.
// If Yes, use it.
// If not, create a new GatewayConnection and start it.
// If start fails, we will mark this connection as dead and remove it from the GetCachedLiveGatewayNames.
lock (lockable)
{
int msgNumber = numMessages;
numMessages = unchecked(numMessages + 1);
IList<Uri> gatewayNames = GatewayManager.GetLiveGateways();
int numGateways = gatewayNames.Count;
if (numGateways == 0)
{
RejectMessage(msg, "No gateways available");
logger.Warn(ErrorCode.ProxyClient_CannotSend, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager);
return;
}
Uri addr = gatewayNames[msgNumber % numGateways];
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayUnordered, "Creating gateway to {0} for unordered message to grain {1}", addr, msg.TargetGrain);
startRequired = true;
}
// else - Fast path - we've got a live gatewayConnection to use
}
}
// Otherwise, use the buckets to ensure ordering.
else
{
var index = msg.TargetGrain.GetHashCode_Modulo((uint)grainBuckets.Length);
lock (lockable)
{
// Repeated from above, at the declaration of the grainBuckets array:
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
var weakRef = grainBuckets[index];
if ((weakRef != null) && weakRef.IsAlive)
{
gatewayConnection = weakRef.Target as GatewayConnection;
}
if ((gatewayConnection == null) || !gatewayConnection.IsLive)
{
var addr = GatewayManager.GetLiveGateway();
if (addr == null)
{
RejectMessage(msg, "No gateways available");
logger.Warn(ErrorCode.ProxyClient_CannotSend_NoGateway, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager);
return;
}
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_NewBucketIndex, "Starting new bucket index {0} for ordered messages to grain {1}", index, msg.TargetGrain);
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayToGrain, "Creating gateway to {0} for message to grain {1}, bucket {2}, grain id hash code {3}X", addr, msg.TargetGrain, index,
msg.TargetGrain.GetHashCode().ToString("x"));
startRequired = true;
}
grainBuckets[index] = new WeakReference(gatewayConnection);
}
}
}
if (startRequired)
{
gatewayConnection.Start();
if (!gatewayConnection.IsLive)
{
// if failed to start Gateway connection (failed to connect), try sending this msg to another Gateway.
RejectOrResend(msg);
return;
}
}
try
{
gatewayConnection.QueueRequest(msg);
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", msg, gatewayConnection.Address);
}
catch (InvalidOperationException)
{
// This exception can be thrown if the gateway connection we selected was closed since we checked (i.e., we lost the race)
// If this happens, we reject if the message is targeted to a specific silo, or try again if not
RejectOrResend(msg);
}
}
private void RejectOrResend(Message msg)
{
if (msg.TargetSilo != null)
{
RejectMessage(msg, String.Format("Target silo {0} is unavailable", msg.TargetSilo));
}
else
{
SendMessage(msg);
}
}
public Task<IGrainTypeResolver> GetTypeCodeMap(GrainFactory grainFactory)
{
var silo = GetLiveGatewaySiloAddress();
return GetTypeManager(silo, grainFactory).GetTypeCodeMap(silo);
}
public Task<Streams.ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(GrainFactory grainFactory)
{
var silo = GetLiveGatewaySiloAddress();
return GetTypeManager(silo, grainFactory).GetImplicitStreamSubscriberTable(silo);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public Message WaitMessage(Message.Categories type, CancellationToken ct)
{
try
{
if (ct.IsCancellationRequested)
{
return null;
}
// Don't pass CancellationToken to Take. It causes too much spinning.
Message msg = PendingInboundMessages.Take();
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnDeQueueRequest(msg);
}
#endif
return msg;
}
#if !NETSTANDARD
catch (ThreadAbortException exc)
{
// Silo may be shutting-down, so downgrade to verbose log
logger.Verbose(ErrorCode.ProxyClient_ThreadAbort, "Received thread abort exception -- exiting. {0}", exc);
Thread.ResetAbort();
return null;
}
#endif
catch (OperationCanceledException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received operation cancelled exception -- exiting. {0}", exc);
return null;
}
catch (ObjectDisposedException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Object Disposed exception -- exiting. {0}", exc);
return null;
}
catch (InvalidOperationException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Invalid Operation exception -- exiting. {0}", exc);
return null;
}
catch (Exception ex)
{
logger.Error(ErrorCode.ProxyClient_ReceiveError, "Unexpected error getting an inbound message", ex);
return null;
}
}
internal void QueueIncomingMessage(Message msg)
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnEnQueueRequest(1, PendingInboundMessages.Count, msg);
}
#endif
PendingInboundMessages.Add(msg);
}
private void RejectMessage(Message msg, string reasonFormat, params object[] reasonParams)
{
if (!Running) return;
var reason = String.Format(reasonFormat, reasonParams);
if (msg.Direction != Message.Directions.Request)
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason);
}
else
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable, reason);
QueueIncomingMessage(error);
}
}
/// <summary>
/// For testing use only
/// </summary>
public void Disconnect()
{
throw new NotImplementedException("Disconnect");
}
/// <summary>
/// For testing use only.
/// </summary>
public void Reconnect()
{
throw new NotImplementedException("Reconnect");
}
#region Random IMessageCenter stuff
public int SendQueueLength
{
get { return 0; }
}
public int ReceiveQueueLength
{
get { return 0; }
}
#endregion
private ITypeManager GetTypeManager(SiloAddress destination, GrainFactory grainFactory)
{
return grainFactory.GetSystemTarget<ITypeManager>(Constants.TypeManagerId, destination);
}
private SiloAddress GetLiveGatewaySiloAddress()
{
var gateway = GatewayManager.GetLiveGateway();
if (gateway == null)
{
throw new OrleansException("Not connected to a gateway");
}
return gateway.ToSiloAddress();
}
internal void UpdateClientId(GrainId clientId)
{
if(ClientId.Category != UniqueKey.Category.Client)
throw new InvalidOperationException("Only handshake client ID can be updated with a cluster ID.");
if (clientId.Category != UniqueKey.Category.GeoClient)
throw new ArgumentException("Handshake client ID can only be updated with a geo client.", nameof(clientId));
ClientId = clientId;
}
}
}
| |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
//
// Windows.Kinect.LongExposureInfraredFrameReader
//
public sealed partial class LongExposureInfraredFrameReader : RootSystem.IDisposable, Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal LongExposureInfraredFrameReader(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Windows_Kinect_LongExposureInfraredFrameReader_AddRefObject(ref _pNative);
}
~LongExposureInfraredFrameReader()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Helper.NativeObjectCache.RemoveObject<LongExposureInfraredFrameReader>(_pNative);
if (disposing)
{
Windows_Kinect_LongExposureInfraredFrameReader_Dispose(_pNative);
}
Windows_Kinect_LongExposureInfraredFrameReader_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern bool Windows_Kinect_LongExposureInfraredFrameReader_get_IsPaused(RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_put_IsPaused(RootSystem.IntPtr pNative, bool isPaused);
public bool IsPaused
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReader");
}
return Windows_Kinect_LongExposureInfraredFrameReader_get_IsPaused(_pNative);
}
set
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReader");
}
Windows_Kinect_LongExposureInfraredFrameReader_put_IsPaused(_pNative, value);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Windows_Kinect_LongExposureInfraredFrameReader_get_LongExposureInfraredFrameSource(RootSystem.IntPtr pNative);
public Windows.Kinect.LongExposureInfraredFrameSource LongExposureInfraredFrameSource
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReader");
}
RootSystem.IntPtr objectPointer = Windows_Kinect_LongExposureInfraredFrameReader_get_LongExposureInfraredFrameSource(_pNative);
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.LongExposureInfraredFrameSource>(objectPointer, n => new Windows.Kinect.LongExposureInfraredFrameSource(n));
}
}
// Events
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs>>> Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate))]
private static void Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs>> callbackList = null;
Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<LongExposureInfraredFrameReader>(pNative);
var args = new Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs(result);
foreach(var func in callbackList)
{
#if UNITY_METRO || UNITY_XBOXONE
UnityEngine.WSA.Application.InvokeOnAppThread(() => { try { func(objThis, args); } catch { } }, true);
#else
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
#endif
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_add_FrameArrived(RootSystem.IntPtr pNative, _Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs> FrameArrived
{
add
{
#if !UNITY_METRO && !UNITY_XBOXONE
Helper.EventPump.EnsureInitialized();
#endif
Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate(Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handler);
_Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Windows_Kinect_LongExposureInfraredFrameReader_add_FrameArrived(_pNative, del, false);
}
}
}
remove
{
Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Windows_Kinect_LongExposureInfraredFrameReader_add_FrameArrived(_pNative, Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handler, true);
_Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handle.Free();
}
}
}
}
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))]
private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null;
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<LongExposureInfraredFrameReader>(pNative);
var args = new Windows.Data.PropertyChangedEventArgs(result);
foreach(var func in callbackList)
{
#if UNITY_METRO || UNITY_XBOXONE
UnityEngine.WSA.Application.InvokeOnAppThread(() => { try { func(objThis, args); } catch { } }, true);
#else
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
#endif
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged
{
add
{
#if !UNITY_METRO && !UNITY_XBOXONE
Helper.EventPump.EnsureInitialized();
#endif
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Windows_Kinect_LongExposureInfraredFrameReader_add_PropertyChanged(_pNative, del, false);
}
}
}
remove
{
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Windows_Kinect_LongExposureInfraredFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
// Public Methods
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Windows_Kinect_LongExposureInfraredFrameReader_AcquireLatestFrame(RootSystem.IntPtr pNative);
public Windows.Kinect.LongExposureInfraredFrame AcquireLatestFrame()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReader");
}
RootSystem.IntPtr objectPointer = Windows_Kinect_LongExposureInfraredFrameReader_AcquireLatestFrame(_pNative);
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.LongExposureInfraredFrame>(objectPointer, n => new Windows.Kinect.LongExposureInfraredFrame(n));
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_Dispose(RootSystem.IntPtr pNative);
public void Dispose()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Dispose(true);
RootSystem.GC.SuppressFinalize(this);
}
}
}
| |
/*
* Copyright (c) 2013 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace DeltaDNA.MiniJSON {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WORD_BREAK = "{}[],:\"";
public static bool IsWordBreak(char c) {
return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
}
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new char[4];
for (int i=0; i< 4; i++) {
hex[i] = NextChar;
}
s.Append((char) Convert.ToInt32(new string(hex), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1 && number.IndexOf('E') == -1 && number.IndexOf('e') == -1) {
long parsedInt;
Int64.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (Char.IsWhiteSpace(PeekChar)) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (!IsWordBreak(PeekChar)) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
switch (PeekChar) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
switch (NextWord) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
} else if ((asStr = value as string) != null) {
SerializeString(asStr);
} else if (value is bool) {
builder.Append((bool) value ? "true" : "false");
} else if ((asList = value as IList) != null) {
SerializeArray(asList);
} else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
} else if (value is char) {
SerializeString(new string((char) value, 1));
} else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
for (int i=0; i<anArray.Count; i++) {
object obj = anArray[i];
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
for (int i=0; i<charArray.Length; i++) {
char c = charArray[i];
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u");
builder.Append(codepoint.ToString("x4"));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (value is float) {
builder.Append(((float) value).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
} else if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong) {
builder.Append(value);
} else if (value is double
|| value is decimal) {
builder.Append(Convert.ToDouble(value).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
} else {
SerializeString(value.ToString());
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace EZOper.TechTester.JWTOAuthWebSI3.Areas.Help
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//
// ContentValues.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// 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.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sharpen;
namespace Couchbase.Lite.Store
{
/// <summary>
/// A class for holding arbitrary values for binding to SQL statements and such
/// </summary>
public sealed class ContentValues // TODO: Create Add override and refactor to use initializer syntax.
{
#region Constants
private const string Tag = "ContentValues";
#endregion
#region Variables
//The actual container for storing the values
private readonly Dictionary<string, object> mValues;
#endregion
#region Properties
internal object this[string key] {
get { return mValues[key]; }
set { mValues[key] = value; }
}
#endregion
#region Constructors
/// <summary>
/// Creates an empty set of values using the default initial size
/// </summary>
public ContentValues()
{
// COPY: Copied from android.content.ContentValues
// Choosing a default size of 8 based on analysis of typical
// consumption by applications.
mValues = new Dictionary<string, object>(8);
}
/// <summary>
/// Creates an empty set of values using the given initial size
/// </summary>
/// <param name="size">the initial size of the set of values</param>
public ContentValues(int size)
{
mValues = new Dictionary<String, Object>(size);
}
/// <summary>
/// Creates a set of values copied from the given set
/// </summary>
/// <param name="from">The values to copy</param>
public ContentValues(ContentValues from)
{
mValues = new Dictionary<string, object>(from.mValues);
}
#endregion
#region Public Methods
/// <summary>Adds a value to the set.</summary>
/// <param name="key">the name of the value to put</param>
/// <param name="value">the data for the value to put</param>
public void Put(string key, string value)
{
mValues[key] = value;
}
/// <summary>Adds all values from the passed in ContentValues.</summary>
/// <param name="other">the ContentValues from which to copy</param>
public void PutAll(ContentValues other)
{
mValues.PutAll(other.mValues);
}
/// <summary>Adds a value to the set.</summary>
/// <param name="key">the name of the value to put</param>
/// <param name="value">the data for the value to put</param>
public void Put(string key, byte value)
{
mValues[key] = value;
}
/// <summary>Adds a value to the set.</summary>
/// <param name="key">the name of the value to put</param>
/// <param name="value">the data for the value to put</param>
public void Put(string key, short value)
{
mValues[key] = value;
}
/// <summary>Adds a value to the set.</summary>
/// <param name="key">the name of the value to put</param>
/// <param name="value">the data for the value to put</param>
public void Put(string key, int value)
{
mValues[key] = value;
}
/// <summary>Adds a value to the set.</summary>
/// <param name="key">the name of the value to put</param>
/// <param name="value">the data for the value to put</param>
public void Put(string key, long value)
{
mValues[key] = value;
}
/// <summary>Adds a value to the set.</summary>
/// <param name="key">the name of the value to put</param>
/// <param name="value">the data for the value to put</param>
public void Put(string key, float value)
{
mValues[key] = value;
}
/// <summary>Adds a value to the set.</summary>
/// <param name="key">the name of the value to put</param>
/// <param name="value">the data for the value to put</param>
public void Put(string key, double value)
{
mValues[key] = value;
}
/// <summary>Adds a value to the set.</summary>
/// <param name="key">the name of the value to put</param>
/// <param name="value">the data for the value to put</param>
public void Put(string key, bool value)
{
mValues[key] = value;
}
/// <summary>Adds a value to the set.</summary>
/// <param name="key">the name of the value to put</param>
/// <param name="value">the data for the value to put</param>
public void Put(string key, IEnumerable<Byte> value)
{
mValues[key] = value;
}
/// <summary>Adds a null value to the set.</summary>
/// <param name="key">the name of the value to make null</param>
public void PutNull(string key)
{
mValues[key] = null;
}
/// <summary>Returns the number of values.</summary>
/// <returns>the number of values</returns>
public int Size()
{
return mValues.Count;
}
/// <summary>Remove a single value.</summary>
/// <param name="key">the name of the value to remove</param>
public void Remove(string key)
{
mValues.Remove(key);
}
/// <summary>Removes all values.</summary>
public void Clear()
{
mValues.Clear();
}
/// <summary>Returns true if this object has the named value.</summary>
/// <param name="key">the value to check for</param>
/// <returns>
///
/// <code>true</code>
/// if the value is present,
/// <code>false</code>
/// otherwise
/// </returns>
public bool ContainsKey(string key)
{
return mValues.ContainsKey(key);
}
/// <summary>
/// Returns the value of the specified key, or null if not present
/// </summary>
/// <param name="key">The key to check</param>
public object Get(string key)
{
return mValues.Get(key);
}
/// <summary>
/// Gets a value and converts it to a String.
/// </summary>
/// <param name="key">the value to get</param>
/// <returns>the String for the value</returns>
public string GetAsString(string key)
{
object value = mValues.Get(key);
return value != null ? value.ToString() : null;
}
/// <summary>
/// Gets a value and converts it to a Long.
/// </summary>
/// <param name="key">the value to get</param>
/// <returns>the Long value, or null if the value is missing or cannot be converted</returns>
public long? GetAsLong(string key)
{
return mValues.GetNullable<long>(key);
}
/// <summary>
/// Gets a value and converts it to an Integer.
/// </summary>
/// <param name="key">the value to get</param>
/// <returns>the Integer value, or null if the value is missing or cannot be converted</returns>
public int? GetAsInteger(string key)
{
return mValues.GetNullable<int>(key);
}
/// <summary>
/// Gets a value and converts it to a Short.
/// </summary>
/// <param name="key">the value to get</param>
/// <returns>the Short value, or null if the value is missing or cannot be converted</returns>
public short? GetAsShort(string key)
{
return mValues.GetNullable<short>(key);
}
/// <summary>
/// Gets a value and converts it to a Byte.
/// </summary>
/// <param name="key">the value to get</param>
/// <returns>the Byte value, or null if the value is missing or cannot be converted</returns>
public byte? GetAsByte(string key)
{
return mValues.GetNullable<byte>(key);
}
/// <summary>
/// Gets a value and converts it to a Double.
/// </summary>
/// <param name="key">the value to get</param>
/// <returns>the Double value, or null if the value is missing or cannot be converted</returns>
public double? GetAsDouble(string key)
{
return mValues.GetNullable<double>(key);
}
/// <summary>
/// Gets a value and converts it to a Float.
/// </summary>
/// <param name="key">the value to get</param>
/// <returns>the Float value, or null if the value is missing or cannot be converted</returns>
public float? GetAsFloat(string key)
{
return mValues.GetNullable<float>(key);
}
/// <summary>
/// Gets a value and converts it to a Boolean.
/// </summary>
/// <param name="key">the value to get</param>
/// <returns>the Boolean value, or null if the value is missing or cannot be converted</returns>
public bool? GetAsBoolean(string key)
{
return mValues.GetNullable<bool>(key);
}
/// <summary>
/// Gets a value that is a byte array.
/// </summary>
/// <remarks>
/// Gets a value that is a byte array. Note that this method will not convert
/// any other types to byte arrays.
/// </remarks>
/// <param name="key">the value to get</param>
/// <returns>the byte[] value, or null is the value is missing or not a byte[]</returns>
public byte[] GetAsByteArray(string key)
{
return mValues.GetCast<byte[]>(key);
}
/// <summary>
/// Returns a set of all of the keys and values
/// </summary>
/// <returns>a set of all of the keys and values</returns>
public ICollection<KeyValuePair<string, object>> ValueSet()
{
return mValues.AsSafeEnumerable().ToArray();
}
/// <summary>Returns a set of all of the keys</summary>
/// <returns>a set of all of the keys</returns>
public ICollection<string> KeySet()
{
return mValues.Keys;
}
#endregion
#region Overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="Couchbase.Lite.Store.ContentValues"/>.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="Couchbase.Lite.Store.ContentValues"/>.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current
/// <see cref="Couchbase.Lite.Store.ContentValues"/>; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (!(obj is ContentValues))
{
return false;
}
return mValues.Equals(((ContentValues)obj).mValues);
}
/// <summary>
/// Serves as a hash function for a <see cref="Couchbase.Lite.Store.ContentValues"/> object.
/// </summary>
/// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a
/// hash table.</returns>
public override int GetHashCode()
{
return mValues.GetHashCode();
}
/// <summary>
/// Returns a string containing a concise, human-readable description of this object.
/// </summary>
/// <returns>a printable representation of this object.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (string name in mValues.Keys)
{
string value = GetAsString(name);
if (sb.Length > 0)
{
sb.Append(" ");
}
sb.Append(name + "=" + value);
}
return sb.ToString();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization
{
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Threading;
using System.Diagnostics.Contracts;
//
// Data table for encoding classes. Used by System.Text.Encoding.
// This class contains two hashtables to allow System.Text.Encoding
// to retrieve the data item either by codepage value or by webName.
//
// Only statics, does not need to be marked with the serializable attribute
internal static class EncodingTable
{
//This number is the size of the table in native. The value is retrieved by
//calling the native GetNumEncodingItems().
private static int lastEncodingItem = GetNumEncodingItems() - 1;
//This number is the size of the code page table. Its generated when we walk the table the first time.
private static volatile int lastCodePageItem;
//
// This points to a native data table which maps an encoding name to the correct code page.
//
unsafe internal static InternalEncodingDataItem *encodingDataPtr = GetEncodingData();
//
// This points to a native data table which stores the properties for the code page, and
// the table is indexed by code page.
//
unsafe internal static InternalCodePageDataItem *codePageDataPtr = GetCodePageData();
//
// This caches the mapping of an encoding name to a code page.
//
private static Hashtable hashByName = Hashtable.Synchronized(new Hashtable(StringComparer.OrdinalIgnoreCase));
//
// THe caches the data item which is indexed by the code page value.
//
private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable());
static EncodingTable()
{
}
// Find the data item by binary searching the table that we have in native.
// nativeCompareOrdinalWC is an internal-only function.
unsafe private static int internalGetCodePageFromName(String name) {
int left = 0;
int right = lastEncodingItem;
int index;
int result;
//Binary search the array until we have only a couple of elements left and then
//just walk those elements.
while ((right - left)>3) {
index = ((right - left)/2) + left;
result = String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[index].webName);
if (result == 0) {
//We found the item, return the associated codepage.
return (encodingDataPtr[index].codePage);
} else if (result<0) {
//The name that we're looking for is less than our current index.
right = index;
} else {
//The name that we're looking for is greater than our current index
left = index;
}
}
//Walk the remaining elements (it'll be 3 or fewer).
for (; left<=right; left++) {
if (String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[left].webName) == 0) {
return (encodingDataPtr[left].codePage);
}
}
// The encoding name is not valid.
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Argument_EncodingNotSupported"), name), nameof(name));
}
// Return a list of all EncodingInfo objects describing all of our encodings
internal static unsafe EncodingInfo[] GetEncodings()
{
if (lastCodePageItem == 0)
{
int count;
for (count = 0; codePageDataPtr[count].codePage != 0; count++)
{
// Count them
}
lastCodePageItem = count;
}
EncodingInfo[] arrayEncodingInfo = new EncodingInfo[lastCodePageItem];
int i;
for (i = 0; i < lastCodePageItem; i++)
{
arrayEncodingInfo[i] = new EncodingInfo(codePageDataPtr[i].codePage, CodePageDataItem.CreateString(codePageDataPtr[i].Names, 0),
Environment.GetResourceString("Globalization.cp_" + codePageDataPtr[i].codePage));
}
return arrayEncodingInfo;
}
/*=================================GetCodePageFromName==========================
**Action: Given a encoding name, return the correct code page number for this encoding.
**Returns: The code page for the encoding.
**Arguments:
** name the name of the encoding
**Exceptions:
** ArgumentNullException if name is null.
** internalGetCodePageFromName will throw ArgumentException if name is not a valid encoding name.
============================================================================*/
internal static int GetCodePageFromName(String name)
{
if (name==null) {
throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
Object codePageObj;
//
// The name is case-insensitive, but ToLower isn't free. Check for
// the code page in the given capitalization first.
//
codePageObj = hashByName[name];
if (codePageObj!=null) {
return ((int)codePageObj);
}
//Okay, we didn't find it in the hash table, try looking it up in the
//unmanaged data.
int codePage = internalGetCodePageFromName(name);
hashByName[name] = codePage;
return codePage;
}
unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage) {
CodePageDataItem dataItem;
// We synchronize around dictionary gets/sets. There's still a possibility that two threads
// will create a CodePageDataItem and the second will clobber the first in the dictionary.
// However, that's acceptable because the contents are correct and we make no guarantees
// other than that.
//Look up the item in the hashtable.
dataItem = (CodePageDataItem)hashByCodePage[codepage];
//If we found it, return it.
if (dataItem!=null) {
return dataItem;
}
//If we didn't find it, try looking it up now.
//If we find it, add it to the hashtable.
//This is a linear search, but we probably won't be doing it very often.
//
int i = 0;
int data;
while ((data = codePageDataPtr[i].codePage) != 0) {
if (data == codepage) {
dataItem = new CodePageDataItem(i);
hashByCodePage[codepage] = dataItem;
return (dataItem);
}
i++;
}
//Nope, we didn't find it.
return null;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalEncodingDataItem *GetEncodingData();
//
// Return the number of encoding data items.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetNumEncodingItems();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalCodePageDataItem* GetCodePageData();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe static extern byte* nativeCreateOpenFileMapping(
String inSectionName, int inBytesToAllocate, out IntPtr mappedFileHandle);
}
/*=================================InternalEncodingDataItem==========================
**Action: This is used to map a encoding name to a correct code page number. By doing this,
** we can get the properties of this encoding via the InternalCodePageDataItem.
**
** We use this structure to access native data exposed by the native side.
============================================================================*/
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
internal unsafe struct InternalEncodingDataItem {
internal sbyte * webName;
internal UInt16 codePage;
}
/*=================================InternalCodePageDataItem==========================
**Action: This is used to access the properties related to a code page.
** We use this structure to access native data exposed by the native side.
============================================================================*/
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
internal unsafe struct InternalCodePageDataItem {
internal UInt16 codePage;
internal UInt16 uiFamilyCodePage;
internal uint flags;
internal sbyte * Names;
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using System.IO;
using DockSample.Customization;
using Lextm.SharpSnmpLib;
using WeifenLuo.WinFormsUI.Docking;
namespace DockSample
{
public partial class MainForm : Form
{
private bool m_bSaveLayout = true;
private DeserializeDockContent m_deserializeDockContent;
private DummySolutionExplorer m_solutionExplorer;
private DummyPropertyWindow m_propertyWindow;
private DummyToolbox m_toolbox;
private DummyOutputWindow m_outputWindow;
private DummyTaskList m_taskList;
public MainForm()
{
InitializeComponent();
CreateStandardControls();
dockPanel.Theme = new VS2012LightTheme();
showRightToLeft.Checked = (RightToLeft == RightToLeft.Yes);
RightToLeftLayout = showRightToLeft.Checked;
m_solutionExplorer.RightToLeftLayout = RightToLeftLayout;
m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
}
#region Methods
private IDockContent FindDocument(string text)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
if (form.Text == text)
return form as IDockContent;
return null;
}
else
{
foreach (IDockContent content in dockPanel.Documents)
if (content.DockHandler.TabText == text)
return content;
return null;
}
}
private DummyDoc CreateNewDocument()
{
DummyDoc dummyDoc = new DummyDoc();
int count = 1;
//string text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
string text = "Document" + count.ToString();
while (FindDocument(text) != null)
{
count++;
//text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
text = "Document" + count.ToString();
}
dummyDoc.Text = text;
return dummyDoc;
}
private DummyDoc CreateNewDocument(string text)
{
DummyDoc dummyDoc = new DummyDoc();
dummyDoc.Text = text;
return dummyDoc;
}
private void CloseAllDocuments()
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
form.Close();
}
else
{
for (int index = dockPanel.Contents.Count - 1; index >= 0; index--)
{
if (dockPanel.Contents[index] is IDockContent)
{
IDockContent content = (IDockContent)dockPanel.Contents[index];
content.DockHandler.Close();
}
}
}
}
private IDockContent GetContentFromPersistString(string persistString)
{
if (persistString == typeof(DummySolutionExplorer).ToString())
return m_solutionExplorer;
else if (persistString == typeof(DummyPropertyWindow).ToString())
return m_propertyWindow;
else if (persistString == typeof(DummyToolbox).ToString())
return m_toolbox;
else if (persistString == typeof(DummyOutputWindow).ToString())
return m_outputWindow;
else if (persistString == typeof(DummyTaskList).ToString())
return m_taskList;
else
{
// DummyDoc overrides GetPersistString to add extra information into persistString.
// Any DockContent may override this value to add any needed information for deserialization.
string[] parsedStrings = persistString.Split(new char[] { ',' });
if (parsedStrings.Length != 3)
return null;
if (parsedStrings[0] != typeof(DummyDoc).ToString())
return null;
DummyDoc dummyDoc = new DummyDoc();
if (parsedStrings[1] != string.Empty)
dummyDoc.FileName = parsedStrings[1];
if (parsedStrings[2] != string.Empty)
dummyDoc.Text = parsedStrings[2];
return dummyDoc;
}
}
private void CloseAllContents()
{
// we don't want to create another instance of tool window, set DockPanel to null
m_solutionExplorer.DockPanel = null;
m_propertyWindow.DockPanel = null;
m_toolbox.DockPanel = null;
m_outputWindow.DockPanel = null;
m_taskList.DockPanel = null;
// Close all other document windows
CloseAllDocuments();
}
private readonly ToolStripRenderer _system = new ToolStripProfessionalRenderer();
private readonly ToolStripRenderer _custom = new VS2012ToolStripRenderer();
private void SetSchema(object sender, System.EventArgs e)
{
CloseAllContents();
if (sender == menuItemSchemaVS2005)
{
dockPanel.Theme = vS2005Theme1;
ToolStripManager.Renderer = _system;
}
else if (sender == menuItemSchemaVS2003)
{
dockPanel.Theme = vS2003Theme1;
ToolStripManager.Renderer = _system;
}
else if (sender == menuItemSchemaVS2012Light)
{
dockPanel.Theme = vS2012LightTheme1;
ToolStripManager.Renderer = _custom;
}
menuItemSchemaVS2005.Checked = (sender == menuItemSchemaVS2005);
menuItemSchemaVS2003.Checked = (sender == menuItemSchemaVS2003);
menuItemSchemaVS2012Light.Checked = (sender == menuItemSchemaVS2012Light);
}
private void SetDocumentStyle(object sender, System.EventArgs e)
{
DocumentStyle oldStyle = dockPanel.DocumentStyle;
DocumentStyle newStyle;
if (sender == menuItemDockingMdi)
newStyle = DocumentStyle.DockingMdi;
else if (sender == menuItemDockingWindow)
newStyle = DocumentStyle.DockingWindow;
else if (sender == menuItemDockingSdi)
newStyle = DocumentStyle.DockingSdi;
else
newStyle = DocumentStyle.SystemMdi;
if (oldStyle == newStyle)
return;
if (oldStyle == DocumentStyle.SystemMdi || newStyle == DocumentStyle.SystemMdi)
CloseAllDocuments();
dockPanel.DocumentStyle = newStyle;
menuItemDockingMdi.Checked = (newStyle == DocumentStyle.DockingMdi);
menuItemDockingWindow.Checked = (newStyle == DocumentStyle.DockingWindow);
menuItemDockingSdi.Checked = (newStyle == DocumentStyle.DockingSdi);
menuItemSystemMdi.Checked = (newStyle == DocumentStyle.SystemMdi);
menuItemLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
menuItemLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
}
private void SetDockPanelSkinOptions(bool isChecked)
{
if (isChecked)
{
// All of these options may be set in the designer.
// This is not a complete list of possible options available in the skin.
AutoHideStripSkin autoHideSkin = new AutoHideStripSkin();
autoHideSkin.DockStripGradient.StartColor = Color.AliceBlue;
autoHideSkin.DockStripGradient.EndColor = Color.Blue;
autoHideSkin.DockStripGradient.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
autoHideSkin.TabGradient.StartColor = SystemColors.Control;
autoHideSkin.TabGradient.EndColor = SystemColors.ControlDark;
autoHideSkin.TabGradient.TextColor = SystemColors.ControlText;
autoHideSkin.TextFont = new Font("Showcard Gothic", 10);
dockPanel.Skin.AutoHideStripSkin = autoHideSkin;
DockPaneStripSkin dockPaneSkin = new DockPaneStripSkin();
dockPaneSkin.DocumentGradient.DockStripGradient.StartColor = Color.Red;
dockPaneSkin.DocumentGradient.DockStripGradient.EndColor = Color.Pink;
dockPaneSkin.DocumentGradient.ActiveTabGradient.StartColor = Color.Green;
dockPaneSkin.DocumentGradient.ActiveTabGradient.EndColor = Color.Green;
dockPaneSkin.DocumentGradient.ActiveTabGradient.TextColor = Color.White;
dockPaneSkin.DocumentGradient.InactiveTabGradient.StartColor = Color.Gray;
dockPaneSkin.DocumentGradient.InactiveTabGradient.EndColor = Color.Gray;
dockPaneSkin.DocumentGradient.InactiveTabGradient.TextColor = Color.Black;
dockPaneSkin.TextFont = new Font("SketchFlow Print", 10);
dockPanel.Skin.DockPaneStripSkin = dockPaneSkin;
}
else
{
dockPanel.Skin = new DockPanelSkin();
}
menuItemLayoutByXml_Click(menuItemLayoutByXml, EventArgs.Empty);
}
#endregion
#region Event Handlers
private void menuItemExit_Click(object sender, System.EventArgs e)
{
Close();
}
private void menuItemSolutionExplorer_Click(object sender, System.EventArgs e)
{
m_solutionExplorer.Show(dockPanel);
}
private void menuItemPropertyWindow_Click(object sender, System.EventArgs e)
{
m_propertyWindow.Show(dockPanel);
}
private void menuItemToolbox_Click(object sender, System.EventArgs e)
{
m_toolbox.Show(dockPanel);
}
private void menuItemOutputWindow_Click(object sender, System.EventArgs e)
{
m_outputWindow.Show(dockPanel);
}
private void menuItemTaskList_Click(object sender, System.EventArgs e)
{
m_taskList.Show(dockPanel);
}
private void menuItemAbout_Click(object sender, System.EventArgs e)
{
AboutDialog aboutDialog = new AboutDialog();
aboutDialog.ShowDialog(this);
}
private void menuItemNew_Click(object sender, System.EventArgs e)
{
DummyDoc dummyDoc = CreateNewDocument();
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
dummyDoc.MdiParent = this;
dummyDoc.Show();
}
else
dummyDoc.Show(dockPanel);
}
private void menuItemOpen_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = Application.ExecutablePath;
openFile.Filter = "rtf files (*.rtf)|*.rtf|txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFile.FilterIndex = 1;
openFile.RestoreDirectory = true;
if (openFile.ShowDialog() == DialogResult.OK)
{
string fullName = openFile.FileName;
string fileName = Path.GetFileName(fullName);
if (FindDocument(fileName) != null)
{
MessageBox.Show("The document: " + fileName + " has already opened!");
return;
}
DummyDoc dummyDoc = new DummyDoc();
dummyDoc.Text = fileName;
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
dummyDoc.MdiParent = this;
dummyDoc.Show();
}
else
dummyDoc.Show(dockPanel);
try
{
dummyDoc.FileName = fullName;
}
catch (Exception exception)
{
dummyDoc.Close();
MessageBox.Show(exception.Message);
}
}
}
private void menuItemFile_Popup(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
menuItemClose.Enabled = menuItemCloseAll.Enabled = (ActiveMdiChild != null);
}
else
{
menuItemClose.Enabled = (dockPanel.ActiveDocument != null);
menuItemCloseAll.Enabled = (dockPanel.DocumentsCount > 0);
}
}
private void menuItemClose_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
ActiveMdiChild.Close();
else if (dockPanel.ActiveDocument != null)
dockPanel.ActiveDocument.DockHandler.Close();
}
private void menuItemCloseAll_Click(object sender, System.EventArgs e)
{
CloseAllDocuments();
}
private void MainForm_Load(object sender, System.EventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (File.Exists(configFile))
dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (m_bSaveLayout)
dockPanel.SaveAsXml(configFile);
else if (File.Exists(configFile))
File.Delete(configFile);
}
private void menuItemToolBar_Click(object sender, System.EventArgs e)
{
toolBar.Visible = menuItemToolBar.Checked = !menuItemToolBar.Checked;
}
private void menuItemStatusBar_Click(object sender, System.EventArgs e)
{
statusBar.Visible = menuItemStatusBar.Checked = !menuItemStatusBar.Checked;
}
private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem == toolBarButtonNew)
menuItemNew_Click(null, null);
else if (e.ClickedItem == toolBarButtonOpen)
menuItemOpen_Click(null, null);
else if (e.ClickedItem == toolBarButtonSolutionExplorer)
menuItemSolutionExplorer_Click(null, null);
else if (e.ClickedItem == toolBarButtonPropertyWindow)
menuItemPropertyWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonToolbox)
menuItemToolbox_Click(null, null);
else if (e.ClickedItem == toolBarButtonOutputWindow)
menuItemOutputWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonTaskList)
menuItemTaskList_Click(null, null);
else if (e.ClickedItem == toolBarButtonLayoutByCode)
menuItemLayoutByCode_Click(null, null);
else if (e.ClickedItem == toolBarButtonLayoutByXml)
menuItemLayoutByXml_Click(null, null);
else if (e.ClickedItem == toolBarButtonDockPanelSkinDemo)
SetDockPanelSkinOptions(!toolBarButtonDockPanelSkinDemo.Checked);
}
private void menuItemNewWindow_Click(object sender, System.EventArgs e)
{
MainForm newWindow = new MainForm();
newWindow.Text = newWindow.Text + " - New";
newWindow.Show();
}
private void menuItemTools_Popup(object sender, System.EventArgs e)
{
menuItemLockLayout.Checked = !this.dockPanel.AllowEndUserDocking;
}
private void menuItemLockLayout_Click(object sender, System.EventArgs e)
{
dockPanel.AllowEndUserDocking = !dockPanel.AllowEndUserDocking;
}
private void menuItemLayoutByCode_Click(object sender, System.EventArgs e)
{
dockPanel.SuspendLayout(true);
CloseAllDocuments();
CreateStandardControls();
m_solutionExplorer.Show(dockPanel, DockState.DockRight);
m_propertyWindow.Show(m_solutionExplorer.Pane, m_solutionExplorer);
m_toolbox.Show(dockPanel, new Rectangle(98, 133, 200, 383));
m_outputWindow.Show(m_solutionExplorer.Pane, DockAlignment.Bottom, 0.35);
m_taskList.Show(m_toolbox.Pane, DockAlignment.Left, 0.4);
DummyDoc doc1 = CreateNewDocument("Document1");
DummyDoc doc2 = CreateNewDocument("Document2");
DummyDoc doc3 = CreateNewDocument("Document3");
DummyDoc doc4 = CreateNewDocument("Document4");
doc1.Show(dockPanel, DockState.Document);
doc2.Show(doc1.Pane, null);
doc3.Show(doc1.Pane, DockAlignment.Bottom, 0.5);
doc4.Show(doc3.Pane, DockAlignment.Right, 0.5);
dockPanel.ResumeLayout(true, true);
}
private void CreateStandardControls()
{
m_solutionExplorer = new DummySolutionExplorer();
m_propertyWindow = new DummyPropertyWindow();
m_toolbox = new DummyToolbox();
m_outputWindow = new DummyOutputWindow();
m_taskList = new DummyTaskList();
}
private void menuItemLayoutByXml_Click(object sender, System.EventArgs e)
{
dockPanel.SuspendLayout(true);
// In order to load layout from XML, we need to close all the DockContents
CloseAllContents();
CreateStandardControls();
Assembly assembly = Assembly.GetAssembly(typeof(MainForm));
Stream xmlStream = assembly.GetManifestResourceStream("DockSample.Resources.DockPanel.xml");
dockPanel.LoadFromXml(xmlStream, m_deserializeDockContent);
xmlStream.Close();
dockPanel.ResumeLayout(true, true);
}
private void menuItemCloseAllButThisOne_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
Form activeMdi = ActiveMdiChild;
foreach (Form form in MdiChildren)
{
if (form != activeMdi)
form.Close();
}
}
else
{
foreach (IDockContent document in dockPanel.DocumentsToArray())
{
if (!document.DockHandler.IsActivated)
document.DockHandler.Close();
}
}
}
private void menuItemShowDocumentIcon_Click(object sender, System.EventArgs e)
{
dockPanel.ShowDocumentIcon = menuItemShowDocumentIcon.Checked = !menuItemShowDocumentIcon.Checked;
}
private void showRightToLeft_Click(object sender, EventArgs e)
{
CloseAllContents();
if (showRightToLeft.Checked)
{
this.RightToLeft = RightToLeft.No;
this.RightToLeftLayout = false;
}
else
{
this.RightToLeft = RightToLeft.Yes;
this.RightToLeftLayout = true;
}
m_solutionExplorer.RightToLeftLayout = this.RightToLeftLayout;
showRightToLeft.Checked = !showRightToLeft.Checked;
}
private void exitWithoutSavingLayout_Click(object sender, EventArgs e)
{
m_bSaveLayout = false;
Close();
m_bSaveLayout = true;
}
#endregion
}
}
| |
/*
ChatObject_publisher.cs
A publication of data of type ChatObject
This file is derived from code automatically generated by the rtiddsgen
command:
rtiddsgen -language C# -example <arch> Chat.idl
Example publication of type ChatObject automatically generated by
'rtiddsgen'. To test them follow these steps:
(1) Compile this file and the example subscription.
(2) Start the subscription with the command
objs\<arch>${constructMap.nativeFQNameInModule}_subscriber <domain_id> <sample_count>
(3) Start the publication with the command
objs\<arch>${constructMap.nativeFQNameInModule}_publisher <domain_id> <sample_count>
(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.
You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.
Example:
To run the example application on domain <domain_id>:
bin\<Debug|Release>\ChatObject_publisher <domain_id> <sample_count>
bin\<Debug|Release>\ChatObject_subscriber <domain_id> <sample_count>
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace My{
public class ChatObjectPublisher {
public static void Main(string[] args) {
// --- Get domain ID --- //
int domain_id = 0;
if (args.Length >= 1) {
domain_id = Int32.Parse(args[0]);
}
// --- Get max loop count; 0 means infinite loop --- //
int sample_count = 0;
if (args.Length >= 2) {
sample_count = Int32.Parse(args[1]);
}
/* Uncomment this to turn on additional logging
NDDS.ConfigLogger.get_instance().set_verbosity_by_category(
NDDS.LogCategory.NDDS_CONFIG_LOG_CATEGORY_API,
NDDS.LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
*/
// --- Run --- //
try {
ChatObjectPublisher.publish(
domain_id, sample_count);
}
catch(DDS.Exception)
{
Console.WriteLine("error in publisher");
}
}
static void publish(int domain_id, int sample_count) {
// --- Create participant --- //
/* To customize participant QoS, use
the configuration file USER_QOS_PROFILES.xml */
DDS.DomainParticipant participant =
DDS.DomainParticipantFactory.get_instance().create_participant(
domain_id,
DDS.DomainParticipantFactory.PARTICIPANT_QOS_DEFAULT,
null /* listener */,
DDS.StatusMask.STATUS_MASK_NONE);
if (participant == null) {
shutdown(participant);
throw new ApplicationException("create_participant error");
}
// --- Create publisher --- //
/* To customize publisher QoS, use
the configuration file USER_QOS_PROFILES.xml */
DDS.Publisher publisher = participant.create_publisher(
DDS.DomainParticipant.PUBLISHER_QOS_DEFAULT,
null /* listener */,
DDS.StatusMask.STATUS_MASK_NONE);
if (publisher == null) {
shutdown(participant);
throw new ApplicationException("create_publisher error");
}
// --- Create topic --- //
/* Register type before creating topic */
System.String type_name = ChatObjectTypeSupport.get_type_name();
try {
ChatObjectTypeSupport.register_type(
participant, type_name);
}
catch(DDS.Exception e) {
Console.WriteLine("register_type error {0}", e);
shutdown(participant);
throw e;
}
/* To customize topic QoS, use
the configuration file USER_QOS_PROFILES.xml */
DDS.Topic topic = participant.create_topic(
My.CHAT_TOPIC_NAME.VALUE, /*>>><<<*/
type_name,
DDS.DomainParticipant.TOPIC_QOS_DEFAULT,
null /* listener */,
DDS.StatusMask.STATUS_MASK_NONE);
if (topic == null) {
shutdown(participant);
throw new ApplicationException("create_topic error");
}
// --- Create writer --- //
/* To customize data writer QoS, use
the configuration file USER_QOS_PROFILES.xml */
DDS.DataWriter writer = publisher.create_datawriter(
topic,
DDS.Publisher.DATAWRITER_QOS_DEFAULT,
null /* listener */,
DDS.StatusMask.STATUS_MASK_NONE);
if (writer == null) {
shutdown(participant);
throw new ApplicationException("create_datawriter error");
}
ChatObjectDataWriter ChatObject_writer =
(ChatObjectDataWriter)writer;
// --- Write --- //
/* Create data sample for writing */
ChatObject instance = ChatObjectTypeSupport.create_data();
if (instance == null) {
shutdown(participant);
throw new ApplicationException(
"ChatObjectTypeSupport.create_data error");
}
/* For a data type that has a key, if the same instance is going to be
written multiple times, initialize the key here
and register the keyed instance prior to writing */
/* >>> */
DDS.InstanceHandle_t instance_handle = DDS.InstanceHandle_t.HANDLE_NIL;
instance.user = "Rajive";
// instance_handle = ChatObject_writer.register_instance(instance);
/* <<< */
/* Main loop */
const System.Int32 send_period = 4000; // milliseconds
for (int count=0;
(sample_count == 0) || (count < sample_count);
++count) {
Console.WriteLine("Writing ChatObject, count {0}", count);
/* Modify the data to be sent here */
/* >>> */
instance.msg = "Hello " + count;
/* <<< */
try {
ChatObject_writer.write(instance, ref instance_handle);
}
catch(DDS.Exception e) {
Console.WriteLine("write error {0}", e);
}
System.Threading.Thread.Sleep(send_period);
}
/*
try {
ChatObject_writer.unregister_instance(
instance, ref instance_handle);
} catch(DDS.Exception e) {
Console.WriteLine("unregister instance error: {0}", e);
}
*/
// --- Shutdown --- //
/* Delete data sample */
try {
ChatObjectTypeSupport.delete_data(instance);
} catch(DDS.Exception e) {
Console.WriteLine(
"ChatObjectTypeSupport.delete_data error: {0}", e);
}
/* Delete all entities */
shutdown(participant);
}
static void shutdown(
DDS.DomainParticipant participant) {
/* Delete all entities */
if (participant != null) {
participant.delete_contained_entities();
DDS.DomainParticipantFactory.get_instance().delete_participant(
ref participant);
}
/* RTI Connext provides finalize_instance() method on
domain participant factory for people who want to release memory
used by the participant factory. Uncomment the following block of
code for clean destruction of the singleton. */
/*
try {
DDS.DomainParticipantFactory.finalize_instance();
} catch (DDS.Exception e) {
Console.WriteLine("finalize_instance error: {0}", e);
throw e;
}
*/
}
}
} /* namespace My */
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Cli.Compiler.Common;
using Microsoft.Dnx.Runtime.Common.CommandLine;
using Microsoft.Dotnet.Cli.Compiler.Common;
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.ProjectModel.Graph;
using NuGet.Frameworks;
using Microsoft.Extensions.PlatformAbstractions;
namespace Microsoft.DotNet.Tools.Restore
{
public partial class RestoreCommand
{
private static readonly string DefaultRid = PlatformServices.Default.Runtime.GetLegacyRestoreRuntimeIdentifier();
public static int Run(string[] args)
{
DebugHelper.HandleDebugSwitch(ref args);
var app = new CommandLineApplication(false)
{
Name = "dotnet restore",
FullName = ".NET project dependency restorer",
Description = "Restores dependencies listed in project.json"
};
// Parse --quiet, because we have to handle that specially since NuGet3 has a different
// "--verbosity" switch that goes BEFORE the command
var quiet = args.Any(s => s.Equals("--quiet", StringComparison.OrdinalIgnoreCase));
args = args.Where(s => !s.Equals("--quiet", StringComparison.OrdinalIgnoreCase)).ToArray();
// Until NuGet/Home#1941 is fixed, if no RIDs are specified, add our own.
if (!args.Any(s => s.Equals("--runtime", StringComparison.OrdinalIgnoreCase)))
{
args = Enumerable.Concat(
args,
PlatformServices.Default.Runtime.GetOverrideRestoreRuntimeIdentifiers().SelectMany(r => new [] { "--runtime", r })
).ToArray();
}
app.OnExecute(() =>
{
try
{
var projectRestoreResult = NuGet3.Restore(args, quiet);
var restoreTasks = GetRestoreTasks(args);
foreach (var restoreTask in restoreTasks)
{
var project = ProjectReader.GetProject(restoreTask.ProjectPath);
RestoreTools(project, restoreTask, quiet);
}
return projectRestoreResult;
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
return -1;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return -2;
}
});
return app.Execute(args);
}
private static IEnumerable<RestoreTask> GetRestoreTasks(IEnumerable<string> args)
{
var directory = Directory.GetCurrentDirectory();
if (args.Any())
{
var firstArg = args.First();
if (IsProjectFile(firstArg))
{
return new [] {new RestoreTask { ProjectPath = firstArg, Arguments = args.Skip(1)} };
}
if (Directory.Exists(firstArg))
{
directory = firstArg;
args = args.Skip(1);
}
}
return GetAllProjectFiles(directory)
.Select(p => new RestoreTask {ProjectPath = p, Arguments = args});
}
private static string[] GetAllProjectFiles(string directory)
{
return Directory.GetFiles(directory, Project.FileName, SearchOption.AllDirectories);
}
private static bool IsProjectFile(string firstArg)
{
return firstArg.EndsWith(Project.FileName) && File.Exists(firstArg);
}
private static void RestoreTools(Project project, RestoreTask restoreTask, bool quiet)
{
foreach (var tooldep in project.Tools)
{
RestoreTool(tooldep, restoreTask, quiet);
}
}
private static void RestoreTool(LibraryRange tooldep, RestoreTask restoreTask, bool quiet)
{
var tempRoot = Path.Combine(restoreTask.ProjectDirectory, "obj");
try
{
var tempPath = Path.Combine(tempRoot, Guid.NewGuid().ToString(), "bin");
var restoreSucceded = RestoreToolToPath(tooldep, restoreTask.Arguments, tempPath, quiet);
if (restoreSucceded)
{
CreateDepsInPackageCache(tooldep, tempPath);
PersistLockFile(tooldep, tempPath, restoreTask.ProjectDirectory);
}
}
finally
{
Directory.Delete(tempRoot, true);
}
}
private static void PersistLockFile(LibraryRange tooldep, string tempPath, string projectPath)
{
var sourcePath = Path.Combine(tempPath, "project.lock.json");
var targetDir = Path.Combine(projectPath, "artifacts", "Tools", tooldep.Name);
var targetPath = Path.Combine(targetDir, "project.lock.json");
if (Directory.Exists(targetDir)) Directory.Delete(targetDir, true);
Directory.CreateDirectory(targetDir);
Console.WriteLine($"Writing '{sourcePath}' to '{targetPath}'");
File.Move(sourcePath, targetPath);
}
private static void CreateDepsInPackageCache(LibraryRange toolLibrary, string projectPath)
{
var context = ProjectContext.Create(projectPath,
FrameworkConstants.CommonFrameworks.DnxCore50, new[] { DefaultRid });
var toolDescription = context.LibraryManager.GetLibraries()
.Select(l => l as PackageDescription)
.Where(l => l != null)
.FirstOrDefault(l => l.Identity.Name == toolLibrary.Name);
var depsPath = Path.Combine(
toolDescription.Path,
Path.GetDirectoryName(toolDescription.Target.RuntimeAssemblies.First().Path),
toolDescription.Identity.Name + FileNameSuffixes.Deps);
var calculator = context.GetOutputPaths(Constants.DefaultConfiguration, buidBasePath: null, outputPath: context.ProjectDirectory);
var executable = new Executable(context, calculator, context.CreateExporter(Constants.DefaultConfiguration));
executable.MakeCompilationOutputRunnable();
if (File.Exists(depsPath)) File.Delete(depsPath);
File.Move(Path.Combine(calculator.RuntimeOutputPath, "bin" + FileNameSuffixes.Deps), depsPath);
}
private static bool RestoreToolToPath(LibraryRange tooldep, IEnumerable<string> args, string tempPath, bool quiet)
{
Directory.CreateDirectory(tempPath);
var projectPath = Path.Combine(tempPath, Project.FileName);
Console.WriteLine($"Restoring Tool '{tooldep.Name}' for '{projectPath}' in '{tempPath}'");
File.WriteAllText(projectPath, GenerateProjectJsonContents(new[] {"dnxcore50"}, tooldep));
return NuGet3.Restore(new [] { $"{projectPath}", "--runtime", $"{DefaultRid}"}.Concat(args), quiet) == 0;
}
private static string GenerateProjectJsonContents(IEnumerable<string> frameworks, LibraryRange tooldep)
{
var sb = new StringBuilder();
sb.AppendLine("{");
sb.AppendLine(" \"dependencies\": {");
sb.AppendLine($" \"{tooldep.Name}\": \"{tooldep.VersionRange.OriginalString}\"");
sb.AppendLine(" },");
sb.AppendLine(" \"frameworks\": {");
foreach (var framework in frameworks)
{
var importsStatement = "\"imports\": \"portable-net452+win81\"";
sb.AppendLine($" \"{framework}\": {{ {importsStatement} }}");
}
sb.AppendLine(" }");
sb.AppendLine("}");
var pjContents = sb.ToString();
return pjContents;
}
}
}
| |
// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using SmugMug.v2.Authentication;
namespace SmugMug.v2.Types
{
public partial class UserEntity : SmugMugEntity
{
private AccountStatusEnum _accountStatus;
private string _domain;
private string _domainOnly;
private string _firstName;
private bool _friendsView;
private long _imageCount;
private bool _isTrial;
private string _lastName;
private string _name;
private string _nickName;
private string _plan;
private bool _quickShare;
private string _refTag;
private string _responseLevel;
private SortByEnum _sortBy;
private string _totalAccountSize;
private string _totalUploadedSize;
private string _viewPassHint;
private string _viewPassword;
private string _webUri;
public AccountStatusEnum AccountStatus {
get {
return _accountStatus;
}
set {
if (_accountStatus != value)
{
NotifyPropertyValueChanged("AccountStatus", oldValue:_accountStatus, newValue: value);
_accountStatus = value;
}
}
}
public string Domain {
get {
return _domain;
}
set {
if (_domain != value)
{
NotifyPropertyValueChanged("Domain", oldValue:_domain, newValue: value);
_domain = value;
}
}
}
public string DomainOnly {
get {
return _domainOnly;
}
set {
if (_domainOnly != value)
{
NotifyPropertyValueChanged("DomainOnly", oldValue:_domainOnly, newValue: value);
_domainOnly = value;
}
}
}
public string FirstName {
get {
return _firstName;
}
set {
if (_firstName != value)
{
NotifyPropertyValueChanged("FirstName", oldValue:_firstName, newValue: value);
_firstName = value;
}
}
}
public bool FriendsView {
get {
return _friendsView;
}
set {
if (_friendsView != value)
{
NotifyPropertyValueChanged("FriendsView", oldValue:_friendsView, newValue: value);
_friendsView = value;
}
}
}
public long ImageCount {
get {
return _imageCount;
}
set {
if (_imageCount != value)
{
NotifyPropertyValueChanged("ImageCount", oldValue:_imageCount, newValue: value);
_imageCount = value;
}
}
}
public bool IsTrial {
get {
return _isTrial;
}
set {
if (_isTrial != value)
{
NotifyPropertyValueChanged("IsTrial", oldValue:_isTrial, newValue: value);
_isTrial = value;
}
}
}
public string LastName {
get {
return _lastName;
}
set {
if (_lastName != value)
{
NotifyPropertyValueChanged("LastName", oldValue:_lastName, newValue: value);
_lastName = value;
}
}
}
public string Name {
get {
return _name;
}
set {
if (_name != value)
{
NotifyPropertyValueChanged("Name", oldValue:_name, newValue: value);
_name = value;
}
}
}
public string NickName {
get {
return _nickName;
}
set {
if (_nickName != value)
{
NotifyPropertyValueChanged("NickName", oldValue:_nickName, newValue: value);
_nickName = value;
}
}
}
public string Plan {
get {
return _plan;
}
set {
if (_plan != value)
{
NotifyPropertyValueChanged("Plan", oldValue:_plan, newValue: value);
_plan = value;
}
}
}
public bool QuickShare {
get {
return _quickShare;
}
set {
if (_quickShare != value)
{
NotifyPropertyValueChanged("QuickShare", oldValue:_quickShare, newValue: value);
_quickShare = value;
}
}
}
internal string RefTag {
get {
return _refTag;
}
set {
if (_refTag != value)
{
NotifyPropertyValueChanged("RefTag", oldValue:_refTag, newValue: value);
_refTag = value;
}
}
}
public string ResponseLevel {
get {
return _responseLevel;
}
set {
if (_responseLevel != value)
{
NotifyPropertyValueChanged("ResponseLevel", oldValue:_responseLevel, newValue: value);
_responseLevel = value;
}
}
}
public SortByEnum SortBy {
get {
return _sortBy;
}
set {
if (_sortBy != value)
{
NotifyPropertyValueChanged("SortBy", oldValue:_sortBy, newValue: value);
_sortBy = value;
}
}
}
public string TotalAccountSize {
get {
return _totalAccountSize;
}
set {
if (_totalAccountSize != value)
{
NotifyPropertyValueChanged("TotalAccountSize", oldValue:_totalAccountSize, newValue: value);
_totalAccountSize = value;
}
}
}
public string TotalUploadedSize {
get {
return _totalUploadedSize;
}
set {
if (_totalUploadedSize != value)
{
NotifyPropertyValueChanged("TotalUploadedSize", oldValue:_totalUploadedSize, newValue: value);
_totalUploadedSize = value;
}
}
}
public string ViewPassHint {
get {
return _viewPassHint;
}
set {
if (_viewPassHint != value)
{
NotifyPropertyValueChanged("ViewPassHint", oldValue:_viewPassHint, newValue: value);
_viewPassHint = value;
}
}
}
public string ViewPassword {
get {
return _viewPassword;
}
set {
if (_viewPassword != value)
{
NotifyPropertyValueChanged("ViewPassword", oldValue:_viewPassword, newValue: value);
_viewPassword = value;
}
}
}
public string WebUri {
get {
return _webUri;
}
set {
if (_webUri != value)
{
NotifyPropertyValueChanged("WebUri", oldValue:_webUri, newValue: value);
_webUri = value;
}
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is1 distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.Record
{
using System;
using System.Web;
using System.IO;
using NPOI.Util;
using NPOI.HSSF.Record;
using NPOI.HSSF.Util;
using NUnit.Framework;
/**
* Test HyperlinkRecord
*
* @author Nick Burch
* @author Yegor Kozlov
*/
[TestFixture]
public class TestHyperlinkRecord
{
/// <summary>
/// Some of the tests are depending on the american culture.
/// </summary>
[SetUp]
public void InitializeCultere()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
}
//link to http://www.lakings.com/
byte[] data1 = { 0x02, 0x00, //First row of the hyperlink
0x02, 0x00, //Last row of the hyperlink
0x00, 0x00, //First column of the hyperlink
0x00, 0x00, //Last column of the hyperlink
//16-byte GUID. Seems to be always the same. Does not depend on the hyperlink type
(byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
0x02, 0x00, 0x00, 0x00, //integer, always 2
// flags. Define the type of the hyperlink:
// HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL
0x17, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, //length of the label including the trailing '\0'
//label:
0x4D, 0x00, 0x79, 0x00, 0x20, 0x00, 0x4C, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x6B, 0x00, 0x00, 0x00,
//16-byte link moniker: HyperlinkRecord.URL_MONIKER
(byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
//count of bytes in the address including the tail
0x48, 0x00, 0x00, 0x00, //integer
//the actual link, terminated by '\u0000'
0x68, 0x00, 0x74, 0x00, 0x74, 0x00, 0x70, 0x00, 0x3A, 0x00, 0x2F, 0x00,
0x2F, 0x00, 0x77, 0x00, 0x77, 0x00, 0x77, 0x00, 0x2E, 0x00, 0x6C, 0x00,
0x61, 0x00, 0x6B, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x73, 0x00,
0x2E, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x2F, 0x00, 0x00, 0x00,
//standard 24-byte tail of a URL link. Seems to always be the same for all URL HLINKs
0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, 0x2C,
(byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00,
0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00};
//link to a file in the current directory: link1.xls
byte[] data2 = {0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
//16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type
(byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
0x02, 0x00, 0x00, 0x00, //integer, always 2
0x15, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL
0x05, 0x00, 0x00, 0x00, //length of the label
//label
0x66, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x65, 0x00, 0x00, 0x00,
//16-byte link moniker: HyperlinkRecord.FILE_MONIKER
0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
0x00, 0x00, //level
0x0A, 0x00, 0x00, 0x00, //length of the path )
//path to the file (plain ISO-8859 bytes, NOT UTF-16LE!)
0x6C, 0x69, 0x6E, 0x6B, 0x31, 0x2E, 0x78, 0x6C, 0x73, 0x00,
//standard 28-byte tail of a file link
(byte)0xFF, (byte)0xFF, (byte)0xAD, (byte)0xDE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
// mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!
byte[] data3 = {0x01, 0x00,
0x01, 0x00,
0x00, 0x00,
0x00, 0x00,
//16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type
(byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
0x02, 0x00, 0x00, 0x00, //integer, always 2
0x17, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL
0x06, 0x00, 0x00, 0x00, //length of the label
0x65, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x00, 0x00, //label
//16-byte link moniker: HyperlinkRecord.URL_MONIKER
(byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
//length of the address including the tail.
0x76, 0x00, 0x00, 0x00,
//the address is terminated by '\u0000'
0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x74, 0x00, 0x6F, 0x00,
0x3A, 0x00, 0x65, 0x00, 0x62, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6E, 0x00,
0x73, 0x00, 0x40, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00,
0x2E, 0x00, 0x72, 0x00, 0x75, 0x00, 0x3F, 0x00, 0x73, 0x00, 0x75, 0x00,
0x62, 0x00, 0x6A, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x3D, 0x00,
0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x2C, 0x00,
0x25, 0x00, 0x32, 0x00, 0x30, 0x00, 0x45, 0x00, 0x62, 0x00, 0x67, 0x00,
0x61, 0x00, 0x6E, 0x00, 0x73, 0x00, 0x21, 0x00, 0x00, 0x00,
//standard 24-byte tail of a URL link
0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, (byte)0x2C,
(byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00,
0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00
};
//link to a place in worksheet: Sheet1!A1
byte[] data4 = {0x03, 0x00,
0x03, 0x00,
0x00, 0x00,
0x00, 0x00,
//16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type
(byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
0x02, 0x00, 0x00, 0x00, //integer, always 2
0x1C, 0x00, 0x00, 0x00, //flags: HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE
0x06, 0x00, 0x00, 0x00, //length of the label
0x70, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x63, 0x00, 0x65, 0x00, 0x00, 0x00, //label
0x0A, 0x00, 0x00, 0x00, //length of the document link including trailing zero
//link: Sheet1!A1
0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x65, 0x00, 0x74, 0x00, 0x31, 0x00, 0x21,
0x00, 0x41, 0x00, 0x31, 0x00, 0x00, 0x00};
private static byte[] dataLinkToWorkbook = HexRead.ReadFromString("01 00 01 00 01 00 01 00 " +
"D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
"02 00 00 00 " +
"1D 00 00 00 " + // options: LABEL | PLACE | FILE_OR_URL
// label: "My Label"
"09 00 00 00 " +
"4D 00 79 00 20 00 4C 00 61 00 62 00 65 00 6C 00 00 00 " +
"03 03 00 00 00 00 00 00 C0 00 00 00 00 00 00 46 " + // file GUID
"00 00 " + // file options
// shortFileName: "YEARFR~1.XLS"
"0D 00 00 00 " +
"59 45 41 52 46 52 7E 31 2E 58 4C 53 00 " +
// FILE_TAIL - unknown byte sequence
"FF FF AD DE 00 00 00 00 " +
"00 00 00 00 00 00 00 00 " +
"00 00 00 00 00 00 00 00 " +
// field len, char data len
"2E 00 00 00 " +
"28 00 00 00 " +
"03 00 " + // unknown ushort
// _address: "yearfracExamples.xls"
"79 00 65 00 61 00 72 00 66 00 72 00 61 00 63 00 " +
"45 00 78 00 61 00 6D 00 70 00 6C 00 65 00 73 00 " +
"2E 00 78 00 6C 00 73 00 " +
// textMark: "Sheet1!B6"
"0A 00 00 00 " +
"53 00 68 00 65 00 65 00 74 00 31 00 21 00 42 00 " +
"36 00 00 00");
private static byte[] dataTargetFrame = HexRead.ReadFromString("0E 00 0E 00 00 00 00 00 " +
"D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
"02 00 00 00 " +
"83 00 00 00 " + // options: TARGET_FRAME | ABS | FILE_OR_URL
// targetFrame: "_blank"
"07 00 00 00 " +
"5F 00 62 00 6C 00 61 00 6E 00 6B 00 00 00 " +
// url GUID
"E0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
// address: "http://www.regnow.com/softsell/nph-softsell.cgi?currency=USD&item=7924-37"
"94 00 00 00 " +
"68 00 74 00 74 00 70 00 3A 00 2F 00 2F 00 77 00 " +
"77 00 77 00 2E 00 72 00 65 00 67 00 6E 00 6F 00 " +
"77 00 2E 00 63 00 6F 00 6D 00 2F 00 73 00 6F 00 " +
"66 00 74 00 73 00 65 00 6C 00 6C 00 2F 00 6E 00 " +
"70 00 68 00 2D 00 73 00 6F 00 66 00 74 00 73 00 " +
"65 00 6C 00 6C 00 2E 00 63 00 67 00 69 00 3F 00 " +
"63 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 " +
"3D 00 55 00 53 00 44 00 26 00 69 00 74 00 65 00 " +
"6D 00 3D 00 37 00 39 00 32 00 34 00 2D 00 33 00 " +
"37 00 00 00");
private static byte[] dataUNC = HexRead.ReadFromString("01 00 01 00 01 00 01 00 " +
"D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
"02 00 00 00 " +
"1F 01 00 00 " + // options: UNC_PATH | LABEL | TEXT_MARK | ABS | FILE_OR_URL
"09 00 00 00 " + // label: "My Label"
"4D 00 79 00 20 00 6C 00 61 00 62 00 65 00 6C 00 00 00 " +
// note - no moniker GUID
"27 00 00 00 " + // "\\\\MyServer\\my-share\\myDir\\PRODNAME.xls"
"5C 00 5C 00 4D 00 79 00 53 00 65 00 72 00 76 00 " +
"65 00 72 00 5C 00 6D 00 79 00 2D 00 73 00 68 00 " +
"61 00 72 00 65 00 5C 00 6D 00 79 00 44 00 69 00 " +
"72 00 5C 00 50 00 52 00 4F 00 44 00 4E 00 41 00 " +
"4D 00 45 00 2E 00 78 00 6C 00 73 00 00 00 " +
"0C 00 00 00 " + // textMark: PRODNAME!C2
"50 00 52 00 4F 00 44 00 4E 00 41 00 4D 00 45 00 21 00 " +
"43 00 32 00 00 00");
/**
* From Bugzilla 47498
*/
private static byte[] data_47498 = {
0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xD0, (byte)0xC9,
(byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C,
(byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00,
0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x50, 0x00,
0x44, 0x00, 0x46, 0x00, 0x00, 0x00, (byte)0xE0, (byte)0xC9, (byte)0xEA,
0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, (byte)0x11, (byte)0x8C, (byte)0x82,
0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x28, 0x00, 0x00, 0x00,
0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x66, 0x00, 0x6F, 0x00,
0x6C, 0x00, 0x64, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2F, 0x00, 0x74, 0x00,
0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x2E, 0x00, 0x50, 0x00, 0x44, 0x00,
0x46, 0x00, 0x00, 0x00};
private void ConfirmGUID(GUID expectedGuid, GUID actualGuid)
{
Assert.AreEqual(expectedGuid, actualGuid);
}
[Test]
public void TestReadURLLink()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data1);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(2, link.FirstRow);
Assert.AreEqual(2, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
ConfirmGUID(HyperlinkRecord.URL_MONIKER, link.Moniker);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL;
Assert.AreEqual(0x17, opts);
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual(0, link.FileOptions);
Assert.AreEqual("My Link", link.Label);
Assert.AreEqual("http://www.lakings.com/", link.Address);
}
[Test]
public void TestReadFileLink()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create((short)HyperlinkRecord.sid, data2);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(0, link.FirstRow);
Assert.AreEqual(0, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
ConfirmGUID(HyperlinkRecord.FILE_MONIKER, link.Moniker);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL;
Assert.AreEqual(0x15, opts);
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual("file", link.Label);
Assert.AreEqual("link1.xls", link.ShortFilename);
}
[Test]
public void TestReadEmailLink()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create((short)HyperlinkRecord.sid, data3);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(1, link.FirstRow);
Assert.AreEqual(1, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
ConfirmGUID(HyperlinkRecord.URL_MONIKER, link.Moniker);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL;
Assert.AreEqual(0x17, opts);
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual("email", link.Label);
Assert.AreEqual("mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!", link.Address);
}
[Test]
public void TestReadDocumentLink()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data4);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(3, link.FirstRow);
Assert.AreEqual(3, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE;
Assert.AreEqual(0x1C, opts);
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual("place", link.Label);
Assert.AreEqual("Sheet1!A1", link.TextMark);
Assert.AreEqual("Sheet1!A1", link.Address);
}
private void Serialize(byte[] data)
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data);
HyperlinkRecord link = new HyperlinkRecord(is1);
byte[] bytes1 = link.Serialize();
is1 = TestcaseRecordInputStream.Create(bytes1);
link = new HyperlinkRecord(is1);
byte[] bytes2 = link.Serialize();
Assert.AreEqual(bytes1.Length, bytes2.Length);
Assert.IsTrue(Arrays.Equals(bytes1, bytes2));
}
[Test]
public void TestSerialize()
{
Serialize(data1);
Serialize(data2);
Serialize(data3);
Serialize(data4);
}
[Test]
public void TestCreateURLRecord()
{
HyperlinkRecord link = new HyperlinkRecord();
link.CreateUrlLink();
link.FirstRow = 2;
link.LastRow = 2;
link.Label = "My Link";
link.Address = "http://www.lakings.com/";
byte[] tmp = link.Serialize();
byte[] ser = new byte[tmp.Length - 4];
Array.Copy(tmp, 4, ser, 0, ser.Length);
Assert.AreEqual(data1.Length, ser.Length);
Assert.IsTrue(Arrays.Equals(data1, ser));
}
[Test]
public void TestCreateFileRecord()
{
HyperlinkRecord link = new HyperlinkRecord();
link.CreateFileLink();
link.FirstRow = 0;
link.LastRow = 0;
link.Label = "file";
link.ShortFilename = "link1.xls";
byte[] tmp = link.Serialize();
byte[] ser = new byte[tmp.Length - 4];
Array.Copy(tmp, 4, ser, 0, ser.Length);
Assert.AreEqual(data2.Length, ser.Length);
Assert.IsTrue(Arrays.Equals(data2, ser));
}
[Test]
public void TestCreateDocumentRecord()
{
HyperlinkRecord link = new HyperlinkRecord();
link.CreateDocumentLink();
link.FirstRow = 3;
link.LastRow = 3;
link.Label = "place";
link.TextMark = "Sheet1!A1";
byte[] tmp = link.Serialize();
byte[] ser = new byte[tmp.Length - 4];
Array.Copy(tmp, 4, ser, 0, ser.Length);
//Assert.AreEqual(data4.Length, ser.Length);
Assert.IsTrue(Arrays.Equals(data4, ser));
}
[Test]
public void TestCreateEmailtRecord()
{
HyperlinkRecord link = new HyperlinkRecord();
link.CreateUrlLink();
link.FirstRow = 1;
link.LastRow = 1;
link.Label = "email";
link.Address = "mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!";
byte[] tmp = link.Serialize();
byte[] ser = new byte[tmp.Length - 4];
Array.Copy(tmp, 4, ser, 0, ser.Length);
Assert.AreEqual(data3.Length, ser.Length);
Assert.IsTrue(Arrays.Equals(data3, ser));
}
[Test]
public void TestClone()
{
byte[][] data = { data1, data2, data3, data4 };
for (int i = 0; i < data.Length; i++)
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data[i]);
HyperlinkRecord link = new HyperlinkRecord(is1);
HyperlinkRecord clone = (HyperlinkRecord)link.Clone();
Assert.IsTrue(Arrays.Equals(link.Serialize(), clone.Serialize()));
}
}
[Test]
public void TestReserializeTargetFrame()
{
RecordInputStream in1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, dataTargetFrame);
HyperlinkRecord hr = new HyperlinkRecord(in1);
byte[] ser = hr.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, dataTargetFrame, ser);
}
[Test]
public void TestReserializeLinkToWorkbook()
{
RecordInputStream in1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, dataLinkToWorkbook);
HyperlinkRecord hr = new HyperlinkRecord(in1);
byte[] ser = hr.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, dataLinkToWorkbook, ser);
if ("YEARFR~1.XLS".Equals(hr.Address))
{
throw new AssertionException("Identified bug in reading workbook link");
}
Assert.AreNotEqual("YEARFR~1.XLS", hr.Address, "Identified bug in reading workbook link");
Assert.AreEqual("yearfracExamples.xls", hr.Address);
}
[Test]
public void TestReserializeUNC()
{
RecordInputStream in1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, dataUNC);
HyperlinkRecord hr = new HyperlinkRecord(in1);
byte[] ser = hr.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, dataUNC, ser);
try
{
hr.ToString();
}
catch (NullReferenceException)
{
Assert.Fail("Identified bug with option URL and UNC set at same time");
}
}
[Test]
public void TestGUID()
{
GUID g;
g = GUID.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301");
ConfirmGUID(g, 0x3F2504E0, 0x4F89, 0x11D3, unchecked((long)0x9A0C0305E82C3301L));
Assert.AreEqual("3F2504E0-4F89-11D3-9A0C-0305E82C3301", g.FormatAsString());
g = GUID.Parse("13579BDF-0246-8ACE-0123-456789ABCDEF");
ConfirmGUID(g, 0x13579BDF, 0x0246, 0x8ACE, unchecked((long)0x0123456789ABCDEFL));
Assert.AreEqual("13579BDF-0246-8ACE-0123-456789ABCDEF", g.FormatAsString());
byte[] buf = new byte[16];
g.Serialize(new LittleEndianByteArrayOutputStream(buf, 0));
String expectedDump = "[DF, 9B, 57, 13, 46, 02, CE, 8A, 01, 23, 45, 67, 89, AB, CD, EF]";
Assert.AreEqual(expectedDump, HexDump.ToHex(buf));
// STD Moniker
g = CreateFromStreamDump("[D0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]");
Assert.AreEqual("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B", g.FormatAsString());
// URL Moniker
g = CreateFromStreamDump("[E0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]");
Assert.AreEqual("79EAC9E0-BAF9-11CE-8C82-00AA004BA90B", g.FormatAsString());
// File Moniker
g = CreateFromStreamDump("[03, 03, 00, 00, 00, 00, 00, 00, C0, 00, 00, 00, 00, 00, 00, 46]");
Assert.AreEqual("00000303-0000-0000-C000-000000000046", g.FormatAsString());
}
private static GUID CreateFromStreamDump(String s)
{
return new GUID(new LittleEndianByteArrayInputStream(HexRead.ReadFromString(s)));
}
private void ConfirmGUID(GUID g, int d1, int d2, int d3, long d4)
{
Assert.AreEqual(new String(HexDump.IntToHex(d1)), new String(HexDump.IntToHex(g.D1)));
Assert.AreEqual(new String(HexDump.ShortToHex(d2)), new String(HexDump.ShortToHex(g.D2)));
Assert.AreEqual(new String(HexDump.ShortToHex(d3)), new String(HexDump.ShortToHex(g.D3)));
Assert.AreEqual(new String(HexDump.LongToHex(d4)), new String(HexDump.LongToHex(g.D4)));
}
[Test]
public void Test47498()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data_47498);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(2, link.FirstRow);
Assert.AreEqual(2, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
ConfirmGUID(HyperlinkRecord.URL_MONIKER, link.Moniker);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL;
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual(0, link.FileOptions);
Assert.AreEqual("PDF", link.Label);
Assert.AreEqual("testfolder/test.PDF", link.Address);
byte[] ser = link.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, data_47498, ser);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Specialized;
using System.Linq;
using Humanizer;
using Humanizer.Localisation;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Localisation;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Rooms;
using osu.Game.Overlays;
using osu.Game.Screens.OnlinePlay.Match.Components;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Playlists
{
public class PlaylistsRoomSettingsOverlay : RoomSettingsOverlay
{
public Action EditPlaylist;
private MatchSettings settings;
protected override OsuButton SubmitButton => settings.ApplyButton;
protected override bool IsLoading => settings.IsLoading; // should probably be replaced with an OngoingOperationTracker.
public PlaylistsRoomSettingsOverlay(Room room)
: base(room)
{
}
protected override void SelectBeatmap() => settings.SelectBeatmap();
protected override OnlinePlayComposite CreateSettings(Room room) => settings = new MatchSettings(room)
{
RelativeSizeAxes = Axes.Both,
RelativePositionAxes = Axes.Y,
EditPlaylist = () => EditPlaylist?.Invoke()
};
protected class MatchSettings : OnlinePlayComposite
{
private const float disabled_alpha = 0.2f;
public Action EditPlaylist;
public OsuTextBox NameField, MaxParticipantsField, MaxAttemptsField;
public OsuDropdown<TimeSpan> DurationField;
public RoomAvailabilityPicker AvailabilityPicker;
public TriangleButton ApplyButton;
public bool IsLoading => loadingLayer.State.Value == Visibility.Visible;
public OsuSpriteText ErrorText;
private LoadingLayer loadingLayer;
private DrawableRoomPlaylist playlist;
private OsuSpriteText playlistLength;
private PurpleTriangleButton editPlaylistButton;
[Resolved(CanBeNull = true)]
private IRoomManager manager { get; set; }
[Resolved]
private IAPIProvider api { get; set; }
private readonly Room room;
public MatchSettings(Room room)
{
this.room = room;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider, OsuColour colours)
{
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background4
},
new GridContainer
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
},
Content = new[]
{
new Drawable[]
{
new OsuScrollContainer
{
Padding = new MarginPadding
{
Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING,
Vertical = 10
},
RelativeSizeAxes = Axes.Both,
Children = new[]
{
new Container
{
Padding = new MarginPadding { Horizontal = WaveOverlayContainer.WIDTH_PADDING },
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new SectionContainer
{
Padding = new MarginPadding { Right = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Room name")
{
Child = NameField = new OsuTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
LengthLimit = 100
},
},
new Section("Duration")
{
Child = DurationField = new DurationDropdown
{
RelativeSizeAxes = Axes.X,
}
},
new Section("Allowed attempts (across all playlist items)")
{
Child = MaxAttemptsField = new OsuNumberBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
PlaceholderText = "Unlimited",
},
},
new Section("Room visibility")
{
Alpha = disabled_alpha,
Child = AvailabilityPicker = new RoomAvailabilityPicker
{
Enabled = { Value = false }
},
},
new Section("Max participants")
{
Alpha = disabled_alpha,
Child = MaxParticipantsField = new OsuNumberBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
ReadOnly = true,
},
},
new Section("Password (optional)")
{
Alpha = disabled_alpha,
Child = new OsuPasswordTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
ReadOnly = true,
},
},
},
},
new SectionContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Padding = new MarginPadding { Left = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Playlist")
{
Child = new GridContainer
{
RelativeSizeAxes = Axes.X,
Height = 448,
Content = new[]
{
new Drawable[]
{
playlist = new PlaylistsRoomSettingsPlaylist
{
RelativeSizeAxes = Axes.Both,
}
},
new Drawable[]
{
playlistLength = new OsuSpriteText
{
Margin = new MarginPadding { Vertical = 5 },
Colour = colours.Yellow,
Font = OsuFont.GetFont(size: 12),
}
},
new Drawable[]
{
editPlaylistButton = new PurpleTriangleButton
{
RelativeSizeAxes = Axes.X,
Height = 40,
Text = "Edit playlist",
Action = () => EditPlaylist?.Invoke()
}
}
},
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.AutoSize),
}
}
},
},
},
},
}
},
},
},
new Drawable[]
{
new Container
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Y = 2,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background5
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 20),
Margin = new MarginPadding { Vertical = 20 },
Padding = new MarginPadding { Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING },
Children = new Drawable[]
{
ApplyButton = new CreateRoomButton
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Size = new Vector2(230, 55),
Enabled = { Value = false },
Action = apply,
},
ErrorText = new OsuSpriteText
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Alpha = 0,
Depth = 1,
Colour = colours.RedDark
}
}
}
}
}
}
}
},
loadingLayer = new LoadingLayer(true)
};
RoomName.BindValueChanged(name => NameField.Text = name.NewValue, true);
Availability.BindValueChanged(availability => AvailabilityPicker.Current.Value = availability.NewValue, true);
MaxParticipants.BindValueChanged(count => MaxParticipantsField.Text = count.NewValue?.ToString(), true);
MaxAttempts.BindValueChanged(count => MaxAttemptsField.Text = count.NewValue?.ToString(), true);
Duration.BindValueChanged(duration => DurationField.Current.Value = duration.NewValue ?? TimeSpan.FromMinutes(30), true);
api.LocalUser.BindValueChanged(populateDurations, true);
playlist.Items.BindTo(Playlist);
Playlist.BindCollectionChanged(onPlaylistChanged, true);
}
private void populateDurations(ValueChangedEvent<APIUser> user)
{
DurationField.Items = new[]
{
TimeSpan.FromMinutes(30),
TimeSpan.FromHours(1),
TimeSpan.FromHours(2),
TimeSpan.FromHours(4),
TimeSpan.FromHours(8),
TimeSpan.FromHours(12),
TimeSpan.FromHours(24),
TimeSpan.FromDays(3),
TimeSpan.FromDays(7),
TimeSpan.FromDays(14),
};
// TODO: show these in the interface at all times.
if (user.NewValue.IsSupporter)
{
// roughly correct (see https://github.com/Humanizr/Humanizer/blob/18167e56c082449cc4fe805b8429e3127a7b7f93/readme.md?plain=1#L427)
// if we want this to be more accurate we might consider sending an actual end time, not a time span. probably not required though.
const int days_in_month = 31;
DurationField.AddDropdownItem(TimeSpan.FromDays(days_in_month));
DurationField.AddDropdownItem(TimeSpan.FromDays(days_in_month * 3));
}
}
protected override void Update()
{
base.Update();
ApplyButton.Enabled.Value = hasValidSettings;
}
public void SelectBeatmap() => editPlaylistButton.TriggerClick();
private void onPlaylistChanged(object sender, NotifyCollectionChangedEventArgs e) =>
playlistLength.Text = $"Length: {Playlist.GetTotalDuration()}";
private bool hasValidSettings => RoomID.Value == null && NameField.Text.Length > 0 && Playlist.Count > 0;
private void apply()
{
if (!ApplyButton.Enabled.Value)
return;
hideError();
RoomName.Value = NameField.Text;
Availability.Value = AvailabilityPicker.Current.Value;
if (int.TryParse(MaxParticipantsField.Text, out int max))
MaxParticipants.Value = max;
else
MaxParticipants.Value = null;
if (int.TryParse(MaxAttemptsField.Text, out max))
MaxAttempts.Value = max;
else
MaxAttempts.Value = null;
Duration.Value = DurationField.Current.Value;
loadingLayer.Show();
manager?.CreateRoom(room, onSuccess, onError);
}
private void hideError() => ErrorText.FadeOut(50);
private void onSuccess(Room room) => loadingLayer.Hide();
private void onError(string text)
{
// see https://github.com/ppy/osu-web/blob/2c97aaeb64fb4ed97c747d8383a35b30f57428c7/app/Models/Multiplayer/PlaylistItem.php#L48.
const string not_found_prefix = "beatmaps not found:";
if (text.StartsWith(not_found_prefix, StringComparison.Ordinal))
{
ErrorText.Text = "One or more beatmaps were not available online. Please remove or replace the highlighted items.";
int[] invalidBeatmapIDs = text
.Substring(not_found_prefix.Length + 1)
.Split(", ")
.Select(int.Parse)
.ToArray();
foreach (var item in Playlist)
{
if (invalidBeatmapIDs.Contains(item.Beatmap.OnlineID))
item.MarkInvalid();
}
}
else
{
ErrorText.Text = text;
}
ErrorText.FadeIn(50);
loadingLayer.Hide();
}
}
public class CreateRoomButton : TriangleButton
{
public CreateRoomButton()
{
Text = "Create";
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.Yellow;
Triangles.ColourLight = colours.YellowLight;
Triangles.ColourDark = colours.YellowDark;
}
}
private class DurationDropdown : OsuDropdown<TimeSpan>
{
public DurationDropdown()
{
Menu.MaxHeight = 100;
}
protected override LocalisableString GenerateItemText(TimeSpan item) => item.Humanize(maxUnit: TimeUnit.Month);
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Discovery
{
using System;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Discovery.Version11;
using System.ServiceModel.Discovery.VersionApril2005;
using System.ServiceModel.Discovery.VersionCD1;
using System.Xml;
[Fx.Tag.XamlVisible(false)]
public abstract class DiscoveryProxy :
IAnnouncementContractApril2005,
IAnnouncementContract11,
IAnnouncementContractCD1,
IDiscoveryContractAdhocApril2005,
IDiscoveryContractManagedApril2005,
IDiscoveryContractAdhoc11,
IDiscoveryContractManaged11,
IDiscoveryContractAdhocCD1,
IDiscoveryContractManagedCD1,
IAnnouncementServiceImplementation,
IDiscoveryServiceImplementation,
IMulticastSuppressionImplementation
{
DiscoveryMessageSequenceGenerator messageSequenceGenerator;
DuplicateDetector<UniqueId> duplicateDetector;
protected DiscoveryProxy()
: this(new DiscoveryMessageSequenceGenerator())
{
}
protected DiscoveryProxy(DiscoveryMessageSequenceGenerator messageSequenceGenerator)
: this(messageSequenceGenerator, DiscoveryDefaults.DuplicateMessageHistoryLength)
{
}
protected DiscoveryProxy(
DiscoveryMessageSequenceGenerator messageSequenceGenerator,
int duplicateMessageHistoryLength)
{
if (messageSequenceGenerator == null)
{
throw FxTrace.Exception.ArgumentNull("messageSequenceGenerator");
}
if (duplicateMessageHistoryLength < 0)
{
throw FxTrace.Exception.ArgumentOutOfRange(
"duplicateMessageHistoryLength",
duplicateMessageHistoryLength,
SR.DiscoveryNegativeDuplicateMessageHistoryLength);
}
if (duplicateMessageHistoryLength > 0)
{
this.duplicateDetector = new DuplicateDetector<UniqueId>(duplicateMessageHistoryLength);
}
this.messageSequenceGenerator = messageSequenceGenerator;
}
void IAnnouncementContractApril2005.HelloOperation(HelloMessageApril2005 message)
{
Fx.Assert("The [....] method IAnnouncementContractApril2005.HelloOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IAnnouncementContractApril2005.BeginHelloOperation(HelloMessageApril2005 message, AsyncCallback callback, object state)
{
return new HelloOperationApril2005AsyncResult(this, message, callback, state);
}
void IAnnouncementContractApril2005.EndHelloOperation(IAsyncResult result)
{
HelloOperationApril2005AsyncResult.End(result);
}
void IAnnouncementContractApril2005.ByeOperation(ByeMessageApril2005 message)
{
Fx.Assert("The [....] method IAnnouncementContractApril2005.ByeOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IAnnouncementContractApril2005.BeginByeOperation(ByeMessageApril2005 message, AsyncCallback callback, object state)
{
return new ByeOperationApril2005AsyncResult(this, message, callback, state);
}
void IAnnouncementContractApril2005.EndByeOperation(IAsyncResult result)
{
ByeOperationApril2005AsyncResult.End(result);
}
void IAnnouncementContract11.HelloOperation(HelloMessage11 message)
{
Fx.Assert("The [....] method IAnnouncementContract11.HelloOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IAnnouncementContract11.BeginHelloOperation(HelloMessage11 message, AsyncCallback callback, object state)
{
return new HelloOperation11AsyncResult(this, message, callback, state);
}
void IAnnouncementContract11.EndHelloOperation(IAsyncResult result)
{
HelloOperation11AsyncResult.End(result);
}
void IAnnouncementContract11.ByeOperation(ByeMessage11 message)
{
Fx.Assert("The [....] method IAnnouncementContract11.ByeOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IAnnouncementContract11.BeginByeOperation(ByeMessage11 message, AsyncCallback callback, object state)
{
return new ByeOperation11AsyncResult(this, message, callback, state);
}
void IAnnouncementContract11.EndByeOperation(IAsyncResult result)
{
ByeOperation11AsyncResult.End(result);
}
void IAnnouncementContractCD1.HelloOperation(HelloMessageCD1 message)
{
Fx.Assert("The [....] method IAnnouncementContractCD1.HelloOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IAnnouncementContractCD1.BeginHelloOperation(HelloMessageCD1 message, AsyncCallback callback, object state)
{
return new HelloOperationCD1AsyncResult(this, message, callback, state);
}
void IAnnouncementContractCD1.EndHelloOperation(IAsyncResult result)
{
HelloOperationCD1AsyncResult.End(result);
}
void IAnnouncementContractCD1.ByeOperation(ByeMessageCD1 message)
{
Fx.Assert("The [....] method IAnnouncementContractCD1.ByeOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IAnnouncementContractCD1.BeginByeOperation(ByeMessageCD1 message, AsyncCallback callback, object state)
{
return new ByeOperationCD1AsyncResult(this, message, callback, state);
}
void IAnnouncementContractCD1.EndByeOperation(IAsyncResult result)
{
ByeOperationCD1AsyncResult.End(result);
}
void IDiscoveryContractApril2005.ProbeOperation(ProbeMessageApril2005 request)
{
Fx.Assert("The [....] method IDiscoveryContractApril2005.ProbeOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IDiscoveryContractApril2005.BeginProbeOperation(ProbeMessageApril2005 request, AsyncCallback callback, object state)
{
return new ProbeDuplexApril2005AsyncResult(request, this, this, callback, state);
}
void IDiscoveryContractApril2005.EndProbeOperation(IAsyncResult result)
{
ProbeDuplexApril2005AsyncResult.End(result);
}
void IDiscoveryContractApril2005.ResolveOperation(ResolveMessageApril2005 request)
{
Fx.Assert("The [....] method IDiscoveryContractApril2005.ResolveOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IDiscoveryContractApril2005.BeginResolveOperation(ResolveMessageApril2005 request, AsyncCallback callback, object state)
{
return new ResolveDuplexApril2005AsyncResult(request, this, this, callback, state);
}
void IDiscoveryContractApril2005.EndResolveOperation(IAsyncResult result)
{
ResolveDuplexApril2005AsyncResult.End(result);
}
void IDiscoveryContractAdhoc11.ProbeOperation(ProbeMessage11 request)
{
Fx.Assert("The [....] method IDiscoveryContractAdhoc11.ProbeOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IDiscoveryContractAdhoc11.BeginProbeOperation(ProbeMessage11 request, AsyncCallback callback, object state)
{
return new ProbeDuplex11AsyncResult(request, this, this, callback, state);
}
void IDiscoveryContractAdhoc11.EndProbeOperation(IAsyncResult result)
{
ProbeDuplex11AsyncResult.End(result);
}
void IDiscoveryContractAdhoc11.ResolveOperation(ResolveMessage11 request)
{
Fx.Assert("The [....] method IDiscoveryContractAdhoc11.ResolveOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IDiscoveryContractAdhoc11.BeginResolveOperation(ResolveMessage11 request, AsyncCallback callback, object state)
{
return new ResolveDuplex11AsyncResult(request, this, this, callback, state);
}
void IDiscoveryContractAdhoc11.EndResolveOperation(IAsyncResult result)
{
ResolveDuplex11AsyncResult.End(result);
}
ProbeMatchesMessage11 IDiscoveryContractManaged11.ProbeOperation(ProbeMessage11 request)
{
Fx.Assert("The [....] method IDiscoveryContractManaged11.ProbeOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
return null;
}
IAsyncResult IDiscoveryContractManaged11.BeginProbeOperation(ProbeMessage11 request, AsyncCallback callback, object state)
{
return new ProbeRequestResponse11AsyncResult(request, this, callback, state);
}
ProbeMatchesMessage11 IDiscoveryContractManaged11.EndProbeOperation(IAsyncResult result)
{
return ProbeRequestResponse11AsyncResult.End(result);
}
ResolveMatchesMessage11 IDiscoveryContractManaged11.ResolveOperation(ResolveMessage11 request)
{
Fx.Assert("The [....] method IDiscoveryContractManaged11.ResolveOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
return null;
}
IAsyncResult IDiscoveryContractManaged11.BeginResolveOperation(ResolveMessage11 request, AsyncCallback callback, object state)
{
return new ResolveRequestResponse11AsyncResult(request, this, callback, state);
}
ResolveMatchesMessage11 IDiscoveryContractManaged11.EndResolveOperation(IAsyncResult result)
{
return ResolveRequestResponse11AsyncResult.End(result);
}
void IDiscoveryContractAdhocCD1.ProbeOperation(ProbeMessageCD1 request)
{
Fx.Assert("The [....] method IDiscoveryContractAdhocCD1.ProbeOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IDiscoveryContractAdhocCD1.BeginProbeOperation(ProbeMessageCD1 request, AsyncCallback callback, object state)
{
return new ProbeDuplexCD1AsyncResult(request, this, this, callback, state);
}
void IDiscoveryContractAdhocCD1.EndProbeOperation(IAsyncResult result)
{
ProbeDuplexCD1AsyncResult.End(result);
}
void IDiscoveryContractAdhocCD1.ResolveOperation(ResolveMessageCD1 request)
{
Fx.Assert("The [....] method IDiscoveryContractAdhocCD1.ResolveOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
}
IAsyncResult IDiscoveryContractAdhocCD1.BeginResolveOperation(ResolveMessageCD1 request, AsyncCallback callback, object state)
{
return new ResolveDuplexCD1AsyncResult(request, this, this, callback, state);
}
void IDiscoveryContractAdhocCD1.EndResolveOperation(IAsyncResult result)
{
ResolveDuplexCD1AsyncResult.End(result);
}
ProbeMatchesMessageCD1 IDiscoveryContractManagedCD1.ProbeOperation(ProbeMessageCD1 request)
{
Fx.Assert("The [....] method IDiscoveryContractManagedCD1.ProbeOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
return null;
}
IAsyncResult IDiscoveryContractManagedCD1.BeginProbeOperation(ProbeMessageCD1 request, AsyncCallback callback, object state)
{
return new ProbeRequestResponseCD1AsyncResult(request, this, callback, state);
}
ProbeMatchesMessageCD1 IDiscoveryContractManagedCD1.EndProbeOperation(IAsyncResult result)
{
return ProbeRequestResponseCD1AsyncResult.End(result);
}
ResolveMatchesMessageCD1 IDiscoveryContractManagedCD1.ResolveOperation(ResolveMessageCD1 request)
{
Fx.Assert("The [....] method IDiscoveryContractManagedCD1.ResolveOperation must not get invoked. It is marked with PreferAsyncInvocation flag.");
return null;
}
IAsyncResult IDiscoveryContractManagedCD1.BeginResolveOperation(ResolveMessageCD1 request, AsyncCallback callback, object state)
{
return new ResolveRequestResponseCD1AsyncResult(request, this, callback, state);
}
ResolveMatchesMessageCD1 IDiscoveryContractManagedCD1.EndResolveOperation(IAsyncResult result)
{
return ResolveRequestResponseCD1AsyncResult.End(result);
}
bool IAnnouncementServiceImplementation.IsDuplicate(UniqueId messageId)
{
return (this.duplicateDetector != null) && (!this.duplicateDetector.AddIfNotDuplicate(messageId));
}
IAsyncResult IAnnouncementServiceImplementation.OnBeginOnlineAnnouncement(
DiscoveryMessageSequence messageSequence,
EndpointDiscoveryMetadata endpointDiscoveryMetadata,
AsyncCallback callback,
object state)
{
return this.OnBeginOnlineAnnouncement(messageSequence, endpointDiscoveryMetadata, callback, state);
}
void IAnnouncementServiceImplementation.OnEndOnlineAnnouncement(IAsyncResult result)
{
this.OnEndOnlineAnnouncement(result);
}
IAsyncResult IAnnouncementServiceImplementation.OnBeginOfflineAnnouncement(
DiscoveryMessageSequence messageSequence,
EndpointDiscoveryMetadata endpointDiscoveryMetadata,
AsyncCallback callback,
object state)
{
return this.OnBeginOfflineAnnouncement(messageSequence, endpointDiscoveryMetadata, callback, state);
}
void IAnnouncementServiceImplementation.OnEndOfflineAnnouncement(IAsyncResult result)
{
this.OnEndOfflineAnnouncement(result);
}
bool IDiscoveryServiceImplementation.IsDuplicate(UniqueId messageId)
{
return (this.duplicateDetector != null) && (!this.duplicateDetector.AddIfNotDuplicate(messageId));
}
DiscoveryMessageSequence IDiscoveryServiceImplementation.GetNextMessageSequence()
{
return this.messageSequenceGenerator.Next();
}
IAsyncResult IDiscoveryServiceImplementation.BeginFind(FindRequestContext findRequestContext, AsyncCallback callback, object state)
{
return this.OnBeginFind(findRequestContext, callback, state);
}
void IDiscoveryServiceImplementation.EndFind(IAsyncResult result)
{
this.OnEndFind(result);
}
IAsyncResult IDiscoveryServiceImplementation.BeginResolve(ResolveCriteria resolveCriteria, AsyncCallback callback, object state)
{
return this.OnBeginResolve(resolveCriteria, callback, state);
}
EndpointDiscoveryMetadata IDiscoveryServiceImplementation.EndResolve(IAsyncResult result)
{
return this.OnEndResolve(result);
}
IAsyncResult IMulticastSuppressionImplementation.BeginShouldRedirectFind(FindCriteria findCriteria, AsyncCallback callback, object state)
{
return this.BeginShouldRedirectFind(findCriteria, callback, state);
}
bool IMulticastSuppressionImplementation.EndShouldRedirectFind(IAsyncResult result, out Collection<EndpointDiscoveryMetadata> redirectionEndpoints)
{
return this.EndShouldRedirectFind(result, out redirectionEndpoints);
}
IAsyncResult IMulticastSuppressionImplementation.BeginShouldRedirectResolve(ResolveCriteria resolveCriteria, AsyncCallback callback, object state)
{
return this.BeginShouldRedirectResolve(resolveCriteria, callback, state);
}
bool IMulticastSuppressionImplementation.EndShouldRedirectResolve(IAsyncResult result, out Collection<EndpointDiscoveryMetadata> redirectionEndpoints)
{
return this.EndShouldRedirectResolve(result, out redirectionEndpoints);
}
protected virtual IAsyncResult BeginShouldRedirectFind(FindCriteria resolveCriteria, AsyncCallback callback, object state)
{
return new CompletedAsyncResult<bool>(false, callback, state);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.AvoidOutParameters, Justification = "This is a Try pattern that requires out parameter.")]
protected virtual bool EndShouldRedirectFind(IAsyncResult result, out Collection<EndpointDiscoveryMetadata> redirectionEndpoints)
{
redirectionEndpoints = null;
return CompletedAsyncResult<bool>.End(result);
}
protected virtual IAsyncResult BeginShouldRedirectResolve(ResolveCriteria findCriteria, AsyncCallback callback, object state)
{
return new CompletedAsyncResult<bool>(false, callback, state);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.AvoidOutParameters, Justification = "This is a Try pattern that requires out parameter.")]
protected virtual bool EndShouldRedirectResolve(IAsyncResult result, out Collection<EndpointDiscoveryMetadata> redirectionEndpoints)
{
redirectionEndpoints = null;
return CompletedAsyncResult<bool>.End(result);
}
protected abstract IAsyncResult OnBeginOnlineAnnouncement(
DiscoveryMessageSequence messageSequence,
EndpointDiscoveryMetadata endpointDiscoveryMetadata,
AsyncCallback callback,
object state);
protected abstract void OnEndOnlineAnnouncement(IAsyncResult result);
protected abstract IAsyncResult OnBeginOfflineAnnouncement(
DiscoveryMessageSequence messageSequence,
EndpointDiscoveryMetadata endpointDiscoveryMetadata,
AsyncCallback callback,
object state);
protected abstract void OnEndOfflineAnnouncement(IAsyncResult result);
protected abstract IAsyncResult OnBeginFind(FindRequestContext findRequestContext, AsyncCallback callback, object state);
protected abstract void OnEndFind(IAsyncResult result);
protected abstract IAsyncResult OnBeginResolve(ResolveCriteria resolveCriteria, AsyncCallback callback, object state);
protected abstract EndpointDiscoveryMetadata OnEndResolve(IAsyncResult result);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Security.Principal;
using System.Threading;
using System.ComponentModel;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
namespace System.Net.Security
{
//
// The class does the real work in authentication and
// user data encryption with NEGO SSPI package.
//
// This is part of the NegotiateStream PAL.
//
internal static class NegotiateStreamPal
{
internal static IIdentity GetIdentity(NTAuthentication context)
{
IIdentity result = null;
string name = context.IsServer ? context.AssociatedName : context.Spn;
string protocol = context.ProtocolName;
if (context.IsServer)
{
SecurityContextTokenHandle token = null;
try
{
SecurityStatusPal status;
SafeDeleteContext securityContext = context.GetContext(out status);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
throw new Win32Exception((int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status));
}
// This will return a client token when conducted authentication on server side.
// This token can be used for impersonation. We use it to create a WindowsIdentity and hand it out to the server app.
Interop.SecurityStatus winStatus = (Interop.SecurityStatus)SSPIWrapper.QuerySecurityContextToken(
GlobalSSPI.SSPIAuth,
securityContext,
out token);
if (winStatus != Interop.SecurityStatus.OK)
{
throw new Win32Exception((int)winStatus);
}
string authtype = context.ProtocolName;
// TODO #5241:
// The following call was also specifying WindowsAccountType.Normal, true.
// WindowsIdentity.IsAuthenticated is no longer supported in CoreFX.
result = new WindowsIdentity(token.DangerousGetHandle(), authtype);
return result;
}
catch (SecurityException)
{
// Ignore and construct generic Identity if failed due to security problem.
}
finally
{
if (token != null)
{
token.Dispose();
}
}
}
// On the client we don't have access to the remote side identity.
result = new GenericIdentity(name, protocol);
return result;
}
internal static string QueryContextAssociatedName(SafeDeleteContext securityContext)
{
return SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.Names) as string;
}
internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext)
{
var negotiationInfoClass = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.NegotiationInfo) as NegotiationInfoClass;
return negotiationInfoClass?.AuthenticationPackage;
}
internal static int QueryMaxTokenSize(string package)
{
return SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken;
}
internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext)
{
return SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.ClientSpecifiedSpn) as string;
}
internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer)
{
return SSPIWrapper.AcquireDefaultCredential(
GlobalSSPI.SSPIAuth,
package,
(isServer ? Interop.SspiCli.CredentialUse.Inbound : Interop.SspiCli.CredentialUse.Outbound));
}
internal unsafe static SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential)
{
SafeSspiAuthDataHandle authData = null;
try
{
Interop.SecurityStatus result = Interop.SspiCli.SspiEncodeStringsAsAuthIdentity(
credential.UserName, credential.Domain,
credential.Password, out authData);
if (result != Interop.SecurityStatus.OK)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.PrintError(
NetEventSource.ComponentType.Security,
SR.Format(
SR.net_log_operation_failed_with_error,
"SspiEncodeStringsAsAuthIdentity()",
String.Format(CultureInfo.CurrentCulture, "0x{0:X}", (int)result)));
}
throw new Win32Exception((int)result);
}
return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth,
package, (isServer ? Interop.SspiCli.CredentialUse.Inbound : Interop.SspiCli.CredentialUse.Outbound), ref authData);
}
finally
{
if (authData != null)
{
authData.Dispose();
}
}
}
internal static SecurityStatusPal InitializeSecurityContext(
SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext securityContext,
string spn,
ContextFlagsPal requestedContextFlags,
SecurityBuffer[] inSecurityBufferArray,
SecurityBuffer outSecurityBuffer,
ref ContextFlagsPal contextFlags)
{
Interop.SspiCli.ContextFlags outContextFlags = Interop.SspiCli.ContextFlags.Zero;
Interop.SecurityStatus winStatus = (Interop.SecurityStatus)SSPIWrapper.InitializeSecurityContext(
GlobalSSPI.SSPIAuth,
credentialsHandle,
ref securityContext,
spn,
ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(requestedContextFlags),
Interop.SspiCli.Endianness.Network,
inSecurityBufferArray,
outSecurityBuffer,
ref outContextFlags);
contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(outContextFlags);
return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(winStatus);
}
internal static SecurityStatusPal CompleteAuthToken(
ref SafeDeleteContext securityContext,
SecurityBuffer[] inSecurityBufferArray)
{
Interop.SecurityStatus winStatus = (Interop.SecurityStatus)SSPIWrapper.CompleteAuthToken(
GlobalSSPI.SSPIAuth,
ref securityContext,
inSecurityBufferArray);
return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(winStatus);
}
internal static SecurityStatusPal AcceptSecurityContext(
SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext securityContext,
ContextFlagsPal requestedContextFlags,
SecurityBuffer[] inSecurityBufferArray,
SecurityBuffer outSecurityBuffer,
ref ContextFlagsPal contextFlags)
{
Interop.SspiCli.ContextFlags outContextFlags = Interop.SspiCli.ContextFlags.Zero;
Interop.SecurityStatus winStatus = (Interop.SecurityStatus)SSPIWrapper.AcceptSecurityContext(
GlobalSSPI.SSPIAuth,
credentialsHandle,
ref securityContext,
ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(requestedContextFlags),
Interop.SspiCli.Endianness.Network,
inSecurityBufferArray,
outSecurityBuffer,
ref outContextFlags);
contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(outContextFlags);
return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(winStatus);
}
internal static void ValidateImpersonationLevel(TokenImpersonationLevel impersonationLevel)
{
if (impersonationLevel != TokenImpersonationLevel.Identification &&
impersonationLevel != TokenImpersonationLevel.Impersonation &&
impersonationLevel != TokenImpersonationLevel.Delegation)
{
throw new ArgumentOutOfRangeException(nameof(impersonationLevel), impersonationLevel.ToString(), SR.net_auth_supported_impl_levels);
}
}
internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode)
{
return new Win32Exception((int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(statusCode));
}
internal static int Encrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
ref byte[] output,
uint sequenceNumber)
{
SecSizes sizes = SSPIWrapper.QueryContextAttributes(
GlobalSSPI.SSPIAuth,
securityContext,
Interop.SspiCli.ContextAttribute.Sizes
) as SecSizes;
try
{
int maxCount = checked(Int32.MaxValue - 4 - sizes.BlockSize - sizes.SecurityTrailer);
if (count > maxCount || count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.net_io_out_range, maxCount));
}
}
catch (Exception e)
{
if (!ExceptionCheck.IsFatal(e))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Encrypt", "Arguments out of range.");
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Encrypt", "Arguments out of range.");
}
throw;
}
int resultSize = count + sizes.SecurityTrailer + sizes.BlockSize;
if (output == null || output.Length < resultSize + 4)
{
output = new byte[resultSize + 4];
}
// Make a copy of user data for in-place encryption.
Buffer.BlockCopy(buffer, offset, output, 4 + sizes.SecurityTrailer, count);
// Prepare buffers TOKEN(signature), DATA and Padding.
var securityBuffer = new SecurityBuffer[3];
securityBuffer[0] = new SecurityBuffer(output, 4, sizes.SecurityTrailer, SecurityBufferType.Token);
securityBuffer[1] = new SecurityBuffer(output, 4 + sizes.SecurityTrailer, count, SecurityBufferType.Data);
securityBuffer[2] = new SecurityBuffer(output, 4 + sizes.SecurityTrailer + count, sizes.BlockSize, SecurityBufferType.Padding);
int errorCode;
if (isConfidential)
{
errorCode = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
else
{
if (isNtlm)
{
securityBuffer[1].type |= SecurityBufferType.ReadOnlyFlag;
}
errorCode = SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, 0);
}
if (errorCode != 0)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Encrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo));
}
throw new Win32Exception(errorCode);
}
// Compacting the result.
resultSize = securityBuffer[0].size;
bool forceCopy = false;
if (resultSize != sizes.SecurityTrailer)
{
forceCopy = true;
Buffer.BlockCopy(output, securityBuffer[1].offset, output, 4 + resultSize, securityBuffer[1].size);
}
resultSize += securityBuffer[1].size;
if (securityBuffer[2].size != 0 && (forceCopy || resultSize != (count + sizes.SecurityTrailer)))
{
Buffer.BlockCopy(output, securityBuffer[2].offset, output, 4 + resultSize, securityBuffer[2].size);
}
resultSize += securityBuffer[2].size;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
internal static int Decrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
out int newOffset,
uint sequenceNumber)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'offset' out of range.");
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'count' out of range.");
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt", "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
if (isNtlm)
{
return DecryptNtlm(securityContext, buffer, offset, count, isConfidential, out newOffset, sequenceNumber);
}
//
// Kerberos and up
//
var securityBuffer = new SecurityBuffer[2];
securityBuffer[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.Stream);
securityBuffer[1] = new SecurityBuffer(0, SecurityBufferType.Data);
int errorCode;
if (isConfidential)
{
errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
else
{
errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
if (errorCode != 0)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#"+ "::Decrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo));
}
throw new Win32Exception(errorCode);
}
if (securityBuffer[1].type != SecurityBufferType.Data)
{
throw new InternalException();
}
newOffset = securityBuffer[1].offset;
return securityBuffer[1].size;
}
private static int DecryptNtlm(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
out int newOffset,
uint sequenceNumber)
{
const int ntlmSignatureLength = 16;
// For the most part the arguments are verified in Decrypt().
if (count < ntlmSignatureLength)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::DecryptNtlm", "Argument 'count' out of range.");
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::DecryptNtlm", "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
var securityBuffer = new SecurityBuffer[2];
securityBuffer[0] = new SecurityBuffer(buffer, offset, ntlmSignatureLength, SecurityBufferType.Token);
securityBuffer[1] = new SecurityBuffer(buffer, offset + ntlmSignatureLength, count - ntlmSignatureLength, SecurityBufferType.Data);
int errorCode;
SecurityBufferType realDataType = SecurityBufferType.Data;
if (isConfidential)
{
errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
else
{
realDataType |= SecurityBufferType.ReadOnlyFlag;
securityBuffer[1].type = realDataType;
errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
if (errorCode != 0)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(securityContext) + "::Decrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo));
}
throw new Win32Exception(errorCode);
}
if (securityBuffer[1].type != realDataType)
{
throw new InternalException();
}
newOffset = securityBuffer[1].offset;
return securityBuffer[1].size;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Test.Common
{
public class LoopbackServer
{
public static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> AllowAllCertificates = (_, __, ___, ____) => true;
public class Options
{
public IPAddress Address { get; set; } = IPAddress.Loopback;
public int ListenBacklog { get; set; } = 1;
public bool UseSsl { get; set; } = false;
public SslProtocols SslProtocols { get; set; } = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
public bool WebSocketEndpoint { get; set; } = false;
public Func<Stream, Stream> ResponseStreamWrapper { get; set; }
}
public static Task CreateServerAsync(Func<Socket, Uri, Task> funcAsync, Options options = null)
{
IPEndPoint ignored;
return CreateServerAsync(funcAsync, out ignored, options);
}
public static Task CreateServerAsync(Func<Socket, Uri, Task> funcAsync, out IPEndPoint localEndPoint, Options options = null)
{
options = options ?? new Options();
try
{
var server = new Socket(options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(options.Address, 0));
server.Listen(options.ListenBacklog);
localEndPoint = (IPEndPoint)server.LocalEndPoint;
string host = options.Address.AddressFamily == AddressFamily.InterNetworkV6 ?
$"[{localEndPoint.Address}]" :
localEndPoint.Address.ToString();
string scheme = options.UseSsl ? "https" : "http";
if (options.WebSocketEndpoint)
{
scheme = options.UseSsl ? "wss" : "ws";
}
var url = new Uri($"{scheme}://{host}:{localEndPoint.Port}/");
return funcAsync(server, url).ContinueWith(t =>
{
server.Dispose();
t.GetAwaiter().GetResult();
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}
catch (Exception e)
{
localEndPoint = null;
return Task.FromException(e);
}
}
public static string DefaultHttpResponse => $"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 0\r\n\r\n";
public static IPAddress GetIPv6LinkLocalAddress() =>
NetworkInterface
.GetAllNetworkInterfaces()
.SelectMany(i => i.GetIPProperties().UnicastAddresses)
.Select(a => a.Address)
.Where(a => a.IsIPv6LinkLocal)
.FirstOrDefault();
public static Task<List<string>> ReadRequestAndSendResponseAsync(Socket server, string response = null, Options options = null)
{
return AcceptSocketAsync(server, (s, stream, reader, writer) => ReadWriteAcceptedAsync(s, reader, writer, response), options);
}
public static async Task<List<string>> ReadWriteAcceptedAsync(Socket s, StreamReader reader, StreamWriter writer, string response = null)
{
// Read request line and headers. Skip any request body.
var lines = new List<string>();
string line;
while (!string.IsNullOrEmpty(line = await reader.ReadLineAsync().ConfigureAwait(false)))
{
lines.Add(line);
}
await writer.WriteAsync(response ?? DefaultHttpResponse).ConfigureAwait(false);
return lines;
}
public static async Task<bool> WebSocketHandshakeAsync(Socket s, StreamReader reader, StreamWriter writer)
{
string serverResponse = null;
string currentRequestLine;
while (!string.IsNullOrEmpty(currentRequestLine = await reader.ReadLineAsync().ConfigureAwait(false)))
{
string[] tokens = currentRequestLine.Split(new char[] { ':' }, 2);
if (tokens.Length == 2)
{
string headerName = tokens[0];
if (headerName == "Sec-WebSocket-Key")
{
string headerValue = tokens[1].Trim();
string responseSecurityAcceptValue = ComputeWebSocketHandshakeSecurityAcceptValue(headerValue);
serverResponse =
"HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
"Sec-WebSocket-Accept: " + responseSecurityAcceptValue + "\r\n\r\n";
}
}
}
if (serverResponse != null)
{
// We received a valid WebSocket opening handshake. Send the appropriate response.
await writer.WriteAsync(serverResponse).ConfigureAwait(false);
return true;
}
return false;
}
private static string ComputeWebSocketHandshakeSecurityAcceptValue(string secWebSocketKey)
{
// GUID specified by RFC 6455.
const string Rfc6455Guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
string combinedKey = secWebSocketKey + Rfc6455Guid;
// Use of SHA1 hash is required by RFC 6455.
SHA1 sha1Provider = new SHA1CryptoServiceProvider();
byte[] sha1Hash = sha1Provider.ComputeHash(Encoding.UTF8.GetBytes(combinedKey));
return Convert.ToBase64String(sha1Hash);
}
public static async Task<List<string>> AcceptSocketAsync(Socket server, Func<Socket, Stream, StreamReader, StreamWriter, Task<List<string>>> funcAsync, Options options = null)
{
options = options ?? new Options();
Socket s = await server.AcceptAsync().ConfigureAwait(false);
try
{
Stream stream = new NetworkStream(s, ownsSocket: false);
if (options.UseSsl)
{
var sslStream = new SslStream(stream, false, delegate { return true; });
using (var cert = Configuration.Certificates.GetServerCertificate())
{
await sslStream.AuthenticateAsServerAsync(
cert,
clientCertificateRequired: true, // allowed but not required
enabledSslProtocols: options.SslProtocols,
checkCertificateRevocation: false).ConfigureAwait(false);
}
stream = sslStream;
}
using (var reader = new StreamReader(stream, Encoding.ASCII))
using (var writer = new StreamWriter(options?.ResponseStreamWrapper?.Invoke(stream) ?? stream, Encoding.ASCII) { AutoFlush = true })
{
return await funcAsync(s, stream, reader, writer).ConfigureAwait(false);
}
}
finally
{
try
{
s.Shutdown(SocketShutdown.Send);
s.Dispose();
}
catch (ObjectDisposedException)
{
// In case the test itself disposes of the socket
}
}
}
public enum TransferType
{
None = 0,
ContentLength,
Chunked
}
public enum TransferError
{
None = 0,
ContentLengthTooLarge,
ChunkSizeTooLarge,
MissingChunkTerminator
}
public static Task StartTransferTypeAndErrorServer(
TransferType transferType,
TransferError transferError,
out IPEndPoint localEndPoint)
{
return CreateServerAsync((server, url) => AcceptSocketAsync(server, async (client, stream, reader, writer) =>
{
// Read past request headers.
string line;
while (!string.IsNullOrEmpty(line = reader.ReadLine())) ;
// Determine response transfer headers.
string transferHeader = null;
string content = "This is some response content.";
if (transferType == TransferType.ContentLength)
{
transferHeader = transferError == TransferError.ContentLengthTooLarge ?
$"Content-Length: {content.Length + 42}\r\n" :
$"Content-Length: {content.Length}\r\n";
}
else if (transferType == TransferType.Chunked)
{
transferHeader = "Transfer-Encoding: chunked\r\n";
}
// Write response header
await writer.WriteAsync("HTTP/1.1 200 OK\r\n").ConfigureAwait(false);
await writer.WriteAsync($"Date: {DateTimeOffset.UtcNow:R}\r\n").ConfigureAwait(false);
await writer.WriteAsync("Content-Type: text/plain\r\n").ConfigureAwait(false);
if (!string.IsNullOrEmpty(transferHeader))
{
await writer.WriteAsync(transferHeader).ConfigureAwait(false);
}
await writer.WriteAsync("\r\n").ConfigureAwait(false);
// Write response body
if (transferType == TransferType.Chunked)
{
string chunkSizeInHex = string.Format(
"{0:x}\r\n",
content.Length + (transferError == TransferError.ChunkSizeTooLarge ? 42 : 0));
await writer.WriteAsync(chunkSizeInHex).ConfigureAwait(false);
await writer.WriteAsync($"{content}\r\n").ConfigureAwait(false);
if (transferError != TransferError.MissingChunkTerminator)
{
await writer.WriteAsync("0\r\n\r\n").ConfigureAwait(false);
}
}
else
{
await writer.WriteAsync($"{content}\r\n").ConfigureAwait(false);
}
return null;
}), out localEndPoint);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Fabric;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Data;
using Microsoft.ServiceFabric.Data.Collections;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Remoting.V2.FabricTransport.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
using SoCreate.ServiceFabric.PubSub.Events;
using SoCreate.ServiceFabric.PubSub.Helpers;
using SoCreate.ServiceFabric.PubSub.State;
using SoCreate.ServiceFabric.PubSub.Subscriber;
namespace SoCreate.ServiceFabric.PubSub
{
/// <remarks>
/// Base class for a <see cref="StatefulService"/> that serves as a Broker that accepts messages from Actors &
/// Services and forwards them to <see cref="ISubscriberActor"/> Actors and <see cref="ISubscriberService"/>
/// Services. Every message type is mapped to one of the partitions of this service.
/// </remarks>
public abstract class BrokerService : StatefulService, IBrokerService
{
private readonly ManualResetEventSlim _initializer = new ManualResetEventSlim(false);
private readonly ConcurrentDictionary<string, ISubscription> _subscriptions = new ConcurrentDictionary<string, ISubscription>();
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1);
private readonly IBrokerEventsManager _brokerEventsManager;
private readonly SubscriptionFactory _subscriptionFactory;
private readonly IProxyFactories _proxyFactories;
/// <summary>
/// Gets the state key for all subscriber queues.
/// </summary>
private const string Subscribers = "Queues";
/// <summary>
/// The name that the <see cref="ServiceReplicaListener"/> instance will get.
/// </summary>
public const string ListenerName = BrokerServiceListenerSettings.ListenerName;
/// <summary>
/// When Set, this callback will be used to trace Service messages to.
/// </summary>
protected Action<string> ServiceEventSourceMessageCallback { get; set; }
/// <summary>
/// Gets or sets the interval to wait before starting to publish messages. (Default: 5s after Activation)
/// </summary>
protected TimeSpan DueTime { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>
/// Gets or sets the interval to wait between batches of publishing messages. (Default: 1s)
/// </summary>
protected TimeSpan Period { get; set; } = TimeSpan.FromSeconds(1);
/// <summary>
/// Gets or sets the amount to throttle queue processing when deliveries are failing. Slow down queue processing by a factor of X. (Default 10) (Default: 10)
/// </summary>
protected int ThrottleFactor { get; set; } = 10;
/// <summary>
/// Get or Sets the maximum period to process messages before allowing enqueuing
/// </summary>
protected TimeSpan MaxProcessingPeriod { get; set; } = TimeSpan.FromSeconds(3);
/// <summary>
/// Gets or Sets the maximum number of messages to de-queue in one iteration of process queue
/// </summary>
protected long MaxDequeuesInOneIteration { get; set; } = 100;
/// <summary>
/// Creates a new instance using the provided context and registers this instance for automatic discovery if needed.
/// </summary>
/// <param name="serviceContext"></param>
/// <param name="enableAutoDiscovery"></param>
/// <param name="brokerEventsManager"></param>
protected BrokerService(StatefulServiceContext serviceContext, bool enableAutoDiscovery = true, IBrokerEventsManager brokerEventsManager = null, IProxyFactories proxyFactories = null)
: base(serviceContext)
{
if (enableAutoDiscovery)
{
new BrokerServiceLocator(Context.ServiceName).RegisterAsync()
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
}
_brokerEventsManager = brokerEventsManager ?? new DefaultBrokerEventsManager();
_subscriptionFactory = new SubscriptionFactory(StateManager);
_proxyFactories = proxyFactories ?? new ProxyFactories();
}
/// <summary>
/// Creates a new instance using the provided context and registers this instance for automatic discovery if needed.
/// </summary>
/// <param name="serviceContext"></param>
/// <param name="reliableStateManagerReplica"></param>
/// <param name="enableAutoDiscovery"></param>
/// <param name="brokerEvents"></param>
protected BrokerService(StatefulServiceContext serviceContext,
IReliableStateManagerReplica2 reliableStateManagerReplica, bool enableAutoDiscovery = true, IBrokerEventsManager brokerEvents = null, IProxyFactories proxyFactories = null)
: base(serviceContext, reliableStateManagerReplica)
{
if (enableAutoDiscovery)
{
new BrokerServiceLocator(Context.ServiceName).RegisterAsync()
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
}
_brokerEventsManager = brokerEvents ?? new DefaultBrokerEventsManager();
_subscriptionFactory = new SubscriptionFactory(StateManager);
_proxyFactories = proxyFactories ?? new ProxyFactories();
}
protected virtual void SetupEvents(IBrokerEvents events)
{
}
/// <summary>
/// Registers a Service or Actor <paramref name="reference"/> as subscriber for messages of type <paramref name="messageTypeName"/>
/// </summary>
/// <param name="reference">Reference to the Service or Actor to register.</param>
/// <param name="messageTypeName">Full type name of message object.</param>
/// <param name="isOrdered"></param>
/// <returns></returns>
public async Task SubscribeAsync(ReferenceWrapper reference, string messageTypeName, bool isOrdered = true)
{
await WaitForInitializeAsync(CancellationToken.None);
var brokerState = await TimeoutRetryHelper.Execute((token, state) => StateManager.GetOrAddAsync<IReliableDictionary<string, BrokerServiceState>>(messageTypeName));
var subscriptionDetails = new SubscriptionDetails(reference, messageTypeName, isOrdered);
ISubscription subscription = null;
await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
subscription = await _subscriptionFactory.CreateAsync(tx, subscriptionDetails);
await brokerState.AddOrUpdateSubscription(tx, Subscribers, subscriptionDetails);
ServiceEventSourceMessage($"Registered subscriber: {reference.Name}");
await _brokerEventsManager.OnSubscribedAsync(subscriptionDetails.QueueName, reference, messageTypeName);
}, cancellationToken: CancellationToken.None);
if (subscription != null)
{
_subscriptions.AddOrUpdate(subscriptionDetails.QueueName, subscription, (key, old) => subscription);
}
}
/// <summary>
/// Unregisters a Service or Actor <paramref name="reference"/> as subscriber for messages of type <paramref name="messageTypeName"/>
/// </summary>
/// <param name="reference"></param>
/// <param name="messageTypeName"></param>
/// <returns></returns>
public async Task UnsubscribeAsync(ReferenceWrapper reference, string messageTypeName)
{
await WaitForInitializeAsync(CancellationToken.None);
var brokerState = await TimeoutRetryHelper.Execute((token, state) => StateManager.GetOrAddAsync<IReliableDictionary<string, BrokerServiceState>>(messageTypeName));
await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
var queueName = SubscriptionDetails.CreateQueueName(reference, messageTypeName);
if (_subscriptions.TryGetValue(queueName, out var subscription))
{
await brokerState.RemoveSubscription(tx, Subscribers, subscription.SubscriptionDetails);
}
await StateManager.RemoveAsync(tx, queueName);
ServiceEventSourceMessage($"Unregistered subscriber: {reference.Name}");
_subscriptions.TryRemove(queueName, out _);
await _brokerEventsManager.OnUnsubscribedAsync(queueName, reference, messageTypeName);
});
}
/// <summary>
/// Takes a published message and forwards it (indirectly) to all Subscribers.
/// </summary>
/// <param name="message">The message to publish</param>
/// <returns></returns>
public async Task PublishMessageAsync(MessageWrapper message)
{
await WaitForInitializeAsync(CancellationToken.None);
await _brokerEventsManager.OnMessagePublishedAsync(message);
var myDictionary = await TimeoutRetryHelper.Execute((token, state) => StateManager.GetOrAddAsync<IReliableDictionary<string, BrokerServiceState>>(message.MessageType));
var subscriptions = await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
var result = await myDictionary.TryGetValueAsync(tx, Subscribers);
return result.HasValue ? result.Value.Subscribers.ToArray() : null;
});
if (subscriptions == null || subscriptions.Length == 0) return;
ServiceEventSourceMessage($"Publishing message '{message.MessageType}' to {subscriptions.Length} subscribers.");
await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
foreach (var subscriptionDetails in subscriptions)
{
await _subscriptions[subscriptionDetails.QueueName].EnqueueMessageAsync(tx, message);
await _brokerEventsManager.OnMessageQueuedToSubscriberAsync(subscriptionDetails.QueueName, subscriptionDetails.ServiceOrActorReference, message);
}
ServiceEventSourceMessage($"Published message '{message.MessageType}' to {subscriptions.Length} subscribers.");
});
}
public async Task<QueueStatsWrapper> GetBrokerStatsAsync()
{
return new QueueStatsWrapper
{
Queues = _subscriptions.ToDictionary(subscription => subscription.Key, subscription => subscription.Value.SubscriptionDetails.ServiceOrActorReference),
Stats = await _brokerEventsManager.GetStatsAsync()
};
}
/// <summary>
/// Starts a loop that processes all queued messages.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected override async Task RunAsync(CancellationToken cancellationToken)
{
await WaitForInitializeAsync(cancellationToken);
ServiceEventSourceMessage($"Sleeping for {DueTime.TotalMilliseconds}ms before starting to publish messages.");
await Task.Delay(DueTime, cancellationToken);
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
//process messages for given time, then allow other transactions to enqueue messages
var cts = new CancellationTokenSource(MaxProcessingPeriod);
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
var timeoutCancellationToken = linkedTokenSource.Token;
try
{
await ProcessAllQueuesAsync(timeoutCancellationToken);
}
catch (TaskCanceledException)
{//swallow and move on..
}
catch (OperationCanceledException)
{//swallow and move on..
}
catch (ObjectDisposedException)
{//swallow and move on..
}
catch (Exception ex)
{
ServiceEventSourceMessage($"Exception caught while processing messages:'{ex.Message}'");
//swallow and move on..
}
finally
{
linkedTokenSource.Dispose();
}
await Task.Delay(Period, cancellationToken);
}
// ReSharper disable once FunctionNeverReturns
}
protected async Task ProcessAllQueuesAsync(CancellationToken timeoutCancellationToken)
{
await Task.WhenAll(
from subscription in _subscriptions
where subscription.Value.SubscriptionDetails.ServiceOrActorReference.ShouldProcessMessages()
select ProcessQueues(timeoutCancellationToken, subscription.Value));
}
/// <inheritdoc />
protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
//add the pubsub listener
yield return new ServiceReplicaListener(context => new FabricTransportServiceRemotingListener(context, this), ListenerName);
}
/// <summary>
/// Blocks the calling thread until <see cref="InitializeAsync"/> is complete.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task WaitForInitializeAsync(CancellationToken cancellationToken)
{
if (_initializer.IsSet) return;
await Task.Run(() => InitializeAsync(cancellationToken), cancellationToken);
_initializer.Wait(cancellationToken);
}
/// <summary>
/// Loads all registered message queues from state and keeps them in memory. Avoids some locks in the statemanager.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task InitializeAsync(CancellationToken cancellationToken)
{
if (_initializer.IsSet) return;
try
{
SetupEvents(_brokerEventsManager);
_semaphore.Wait(cancellationToken);
if (_initializer.IsSet) return;
await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
_subscriptions.Clear();
var enumerator = StateManager.GetAsyncEnumerator();
while (await enumerator.MoveNextAsync(cancellationToken))
{
var current = enumerator.Current as IReliableDictionary<string, BrokerServiceState>;
if (current == null) continue;
var result = await current.TryGetValueAsync(tx, Subscribers);
if (!result.HasValue) continue;
var subscriptions = result.Value.Subscribers.ToList();
foreach (var subscriptionDetails in subscriptions)
{
var subscription = await _subscriptionFactory.CreateAsync(tx, subscriptionDetails);
_subscriptions.TryAdd(subscriptionDetails.QueueName, subscription);
}
}
}, cancellationToken: cancellationToken);
_initializer.Set();
}
finally
{
_semaphore.Release();
}
}
/// <summary>
/// Sends out queued messages for the provided queue.
/// </summary>
/// <param name="cancellationToken"></param>
/// <param name="subscription"></param>
/// <returns></returns>
private async Task ProcessQueues(CancellationToken cancellationToken, ISubscription subscription)
{
var details = subscription.SubscriptionDetails;
var messageCount = await subscription.GetQueueCount(cancellationToken);
if (messageCount == 0L) return;
messageCount = Math.Min(messageCount, MaxDequeuesInOneIteration);
ServiceEventSourceMessage($"Processing {messageCount} items from queue {details.QueueName} for subscriber: {details.ServiceOrActorReference.Name}");
for (long i = 0; i < messageCount; i++)
{
cancellationToken.ThrowIfCancellationRequested();
await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
var message = await subscription.DequeueMessageAsync(tx, cancellationToken);
if (message.HasValue)
{
try
{
await subscription.DeliverMessageAsync(message.Value, _proxyFactories);
await _brokerEventsManager.OnMessageDeliveredAsync(details.QueueName, details.ServiceOrActorReference, message.Value);
}
catch (Exception ex)
{
await _brokerEventsManager.OnMessageDeliveryFailedAsync(details.QueueName, details.ServiceOrActorReference, message.Value, ex, ThrottleFactor);
throw;
}
}
}, cancellationToken: cancellationToken);
}
}
/// <summary>
/// Outputs the provided message to the <see cref="ServiceEventSourceMessageCallback"/> if it's configured.
/// </summary>
/// <param name="message"></param>
/// <param name="caller"></param>
protected void ServiceEventSourceMessage(string message, [CallerMemberName] string caller = "unknown")
{
ServiceEventSourceMessageCallback?.Invoke($"{caller} - {message}");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.