context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.Pug
{
/// <summary>
/// Common factory for creating our editor
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public abstract class CommonEditorFactory : IVsEditorFactory
{
private Package _package;
private ServiceProvider _serviceProvider;
private readonly bool _promptEncodingOnLoad;
public CommonEditorFactory(Package package)
{
this._package = package;
}
public CommonEditorFactory(Package package, bool promptEncodingOnLoad)
{
this._package = package;
this._promptEncodingOnLoad = promptEncodingOnLoad;
}
#region IVsEditorFactory Members
public virtual int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
{
this._serviceProvider = new ServiceProvider(psp);
return VSConstants.S_OK;
}
public virtual object GetService(Type serviceType)
{
return this._serviceProvider.GetService(serviceType);
}
// This method is called by the Environment (inside IVsUIShellOpenDocument::
// OpenStandardEditor and OpenSpecificEditor) to map a LOGICAL view to a
// PHYSICAL view. A LOGICAL view identifies the purpose of the view that is
// desired (e.g. a view appropriate for Debugging [LOGVIEWID_Debugging], or a
// view appropriate for text view manipulation as by navigating to a find
// result [LOGVIEWID_TextView]). A PHYSICAL view identifies an actual type
// of view implementation that an IVsEditorFactory can create.
//
// NOTE: Physical views are identified by a string of your choice with the
// one constraint that the default/primary physical view for an editor
// *MUST* use a NULL string as its physical view name (*pbstrPhysicalView = NULL).
//
// NOTE: It is essential that the implementation of MapLogicalView properly
// validates that the LogicalView desired is actually supported by the editor.
// If an unsupported LogicalView is requested then E_NOTIMPL must be returned.
//
// NOTE: The special Logical Views supported by an Editor Factory must also
// be registered in the local registry hive. LOGVIEWID_Primary is implicitly
// supported by all editor types and does not need to be registered.
// For example, an editor that supports a ViewCode/ViewDesigner scenario
// might register something like the following:
// HKLM\Software\Microsoft\VisualStudio\9.0\Editors\
// {...guidEditor...}\
// LogicalViews\
// {...LOGVIEWID_TextView...} = s ''
// {...LOGVIEWID_Code...} = s ''
// {...LOGVIEWID_Debugging...} = s ''
// {...LOGVIEWID_Designer...} = s 'Form'
//
public virtual int MapLogicalView(ref Guid logicalView, out string physicalView)
{
// initialize out parameter
physicalView = null;
var isSupportedView = false;
// Determine the physical view
if (VSConstants.LOGVIEWID_Primary == logicalView ||
VSConstants.LOGVIEWID_Debugging == logicalView ||
VSConstants.LOGVIEWID_Code == logicalView ||
VSConstants.LOGVIEWID_TextView == logicalView)
{
// primary view uses NULL as pbstrPhysicalView
isSupportedView = true;
}
else if (VSConstants.LOGVIEWID_Designer == logicalView)
{
physicalView = "Design";
isSupportedView = true;
}
if (isSupportedView)
{
return VSConstants.S_OK;
}
else
{
// E_NOTIMPL must be returned for any unrecognized rguidLogicalView values
return VSConstants.E_NOTIMPL;
}
}
public virtual int Close()
{
return VSConstants.S_OK;
}
/// <summary>
///
/// </summary>
/// <param name="grfCreateDoc"></param>
/// <param name="pszMkDocument"></param>
/// <param name="pszPhysicalView"></param>
/// <param name="pvHier"></param>
/// <param name="itemid"></param>
/// <param name="punkDocDataExisting"></param>
/// <param name="ppunkDocView"></param>
/// <param name="ppunkDocData"></param>
/// <param name="pbstrEditorCaption"></param>
/// <param name="pguidCmdUI"></param>
/// <param name="pgrfCDW"></param>
/// <returns></returns>
public virtual int CreateEditorInstance(
uint createEditorFlags,
string documentMoniker,
string physicalView,
IVsHierarchy hierarchy,
uint itemid,
System.IntPtr docDataExisting,
out System.IntPtr docView,
out System.IntPtr docData,
out string editorCaption,
out Guid commandUIGuid,
out int createDocumentWindowFlags)
{
// Initialize output parameters
docView = IntPtr.Zero;
docData = IntPtr.Zero;
commandUIGuid = Guid.Empty;
createDocumentWindowFlags = 0;
editorCaption = null;
// Validate inputs
if ((createEditorFlags & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
{
return VSConstants.E_INVALIDARG;
}
if (this._promptEncodingOnLoad && docDataExisting != IntPtr.Zero)
{
return VSConstants.VS_E_INCOMPATIBLEDOCDATA;
}
// Get a text buffer
var textLines = GetTextBuffer(docDataExisting);
// Assign docData IntPtr to either existing docData or the new text buffer
if (docDataExisting != IntPtr.Zero)
{
docData = docDataExisting;
Marshal.AddRef(docData);
}
else
{
docData = Marshal.GetIUnknownForObject(textLines);
}
try
{
docView = CreateDocumentView(documentMoniker, physicalView, hierarchy, itemid, textLines, out editorCaption, out commandUIGuid);
}
finally
{
if (docView == IntPtr.Zero)
{
if (docDataExisting != docData && docData != IntPtr.Zero)
{
// Cleanup the instance of the docData that we have addref'ed
Marshal.Release(docData);
docData = IntPtr.Zero;
}
}
}
return VSConstants.S_OK;
}
#endregion
#region Helper methods
private IVsTextLines GetTextBuffer(System.IntPtr docDataExisting)
{
IVsTextLines textLines;
if (docDataExisting == IntPtr.Zero)
{
// Create a new IVsTextLines buffer.
var textLinesType = typeof(IVsTextLines);
var riid = textLinesType.GUID;
var clsid = typeof(VsTextBufferClass).GUID;
textLines = this._package.CreateInstance(ref clsid, ref riid, textLinesType) as IVsTextLines;
// set the buffer's site
((IObjectWithSite)textLines).SetSite(this._serviceProvider.GetService(typeof(IOleServiceProvider)));
}
else
{
// Use the existing text buffer
var dataObject = Marshal.GetObjectForIUnknown(docDataExisting);
textLines = dataObject as IVsTextLines;
if (textLines == null)
{
// Try get the text buffer from textbuffer provider
var textBufferProvider = dataObject as IVsTextBufferProvider;
if (textBufferProvider != null)
{
textBufferProvider.GetTextBuffer(out textLines);
}
}
if (textLines == null)
{
// Unknown docData type then, so we have to force VS to close the other editor.
ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_INCOMPATIBLEDOCDATA);
}
}
return textLines;
}
private IntPtr CreateDocumentView(string documentMoniker, string physicalView, IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, out string editorCaption, out Guid cmdUI)
{
//Init out params
editorCaption = string.Empty;
cmdUI = Guid.Empty;
if (string.IsNullOrEmpty(physicalView))
{
// create code window as default physical view
return CreateCodeView(documentMoniker, textLines, ref editorCaption, ref cmdUI);
}
//else if (StringComparer.InvariantCultureIgnoreCase.Equals(physicalView, "design"))
//{
// // Create Form view
// return CreateFormView(hierarchy, itemid, textLines, ref editorCaption, ref cmdUI);
//}
// We couldn't create the view
// Return special error code so VS can try another editor factory.
ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_UNSUPPORTEDFORMAT);
return IntPtr.Zero;
}
//private IntPtr CreateFormView(IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI)
//{
// // Request the Designer Service
// var designerService = (IVSMDDesignerService)GetService(typeof(IVSMDDesignerService));
// // Create loader for the designer
// var designerLoader = (IVSMDDesignerLoader)designerService.CreateDesignerLoader("Microsoft.VisualStudio.Designer.Serialization.VSDesignerLoader");
// var loaderInitalized = false;
// try
// {
// var provider = this._serviceProvider.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;
// // Initialize designer loader
// designerLoader.Initialize(provider, hierarchy, (int)itemid, textLines);
// loaderInitalized = true;
// // Create the designer
// var designer = designerService.CreateDesigner(provider, designerLoader);
// // Get editor caption
// editorCaption = designerLoader.GetEditorCaption((int)READONLYSTATUS.ROSTATUS_Unknown);
// // Get view from designer
// object docView = designer.View;
// // Get command guid from designer
// cmdUI = designer.CommandGuid;
// return Marshal.GetIUnknownForObject(docView);
// }
// catch
// {
// // The designer loader may have created a reference to the shell or the text buffer.
// // In case we fail to create the designer we should manually dispose the loader
// // in order to release the references to the shell and the textbuffer
// if (loaderInitalized)
// {
// designerLoader.Dispose();
// }
// throw;
// }
//}
private IntPtr CreateCodeView(string documentMoniker, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI)
{
var codeWindowType = typeof(IVsCodeWindow);
var riid = codeWindowType.GUID;
var clsid = typeof(VsCodeWindowClass).GUID;
var window = (IVsCodeWindow)this._package.CreateInstance(ref clsid, ref riid, codeWindowType);
ErrorHandler.ThrowOnFailure(window.SetBuffer(textLines));
ErrorHandler.ThrowOnFailure(window.SetBaseEditorCaption(null));
ErrorHandler.ThrowOnFailure(window.GetEditorCaption(READONLYSTATUS.ROSTATUS_Unknown, out editorCaption));
var userData = textLines as IVsUserData;
if (userData != null)
{
if (this._promptEncodingOnLoad)
{
var guid = VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingPromptOnLoad_guid;
userData.SetData(ref guid, (uint)1);
}
}
InitializeLanguageService(textLines);
cmdUI = VSConstants.GUID_TextEditorFactory;
return Marshal.GetIUnknownForObject(window);
}
/// <summary>
/// Initializes the language service for the given file. This allows files with different
/// extensions to be opened by the editor type and get correct highlighting and intellisense
/// controllers.
///
/// New in 1.1
/// </summary>
protected virtual void InitializeLanguageService(IVsTextLines textLines)
{
}
#endregion
protected void InitializeLanguageService(IVsTextLines textLines, Guid langSid)
{
var userData = textLines as IVsUserData;
if (userData != null)
{
if (langSid != Guid.Empty)
{
var vsCoreSid = new Guid("{8239bec4-ee87-11d0-8c98-00c04fc2ab22}");
Guid currentSid;
ErrorHandler.ThrowOnFailure(textLines.GetLanguageServiceID(out currentSid));
// If the language service is set to the default SID, then
// set it to our language
if (currentSid == vsCoreSid)
{
ErrorHandler.ThrowOnFailure(textLines.SetLanguageServiceID(ref langSid));
}
else if (currentSid != langSid)
{
// Some other language service has it, so return VS_E_INCOMPATIBLEDOCDATA
throw new COMException("Incompatible doc data", VSConstants.VS_E_INCOMPATIBLEDOCDATA);
}
var bufferDetectLang = VSConstants.VsTextBufferUserDataGuid.VsBufferDetectLangSID_guid;
ErrorHandler.ThrowOnFailure(userData.SetData(ref bufferDetectLang, false));
}
}
}
}
}
| |
/*
* Copyright 2013 Stanislav Muhametsin. 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.Threading;
using CollectionsWithRoles.API;
using CommonUtils;
using CILAssemblyManipulator.Physical;
namespace CILAssemblyManipulator.Logical.Implementation
{
internal abstract class CILMethodBaseImpl : CILCustomAttributeContainerImpl, CILMethodBase, CILMethodBaseInternal
{
private readonly SettableValueForEnums<CallingConventions> callingConvention;
protected internal readonly SettableValueForEnums<MethodAttributes> methodAttributes;
private readonly MethodKind methodKind;
protected internal readonly Lazy<CILType> declaringType;
private readonly ReadOnlyResettableLazy<ListProxy<CILParameter>> parameters;
private readonly WriteableLazy<MethodIL> il;
// Use SettableLazy instead of SettableValue here - we don't want to force this non-portable event to trigger every time.
private readonly WriteableLazy<MethodImplAttributes> methodImplementationAttributes;
private readonly Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> securityInfo;
protected CILMethodBaseImpl(
CILReflectionContextImpl ctx,
Int32 anID,
System.Reflection.MethodBase method
)
: base( ctx, anID, ( method is System.Reflection.ConstructorInfo ) ? CILElementKind.Constructor : CILElementKind.Method, cb => cb.GetCustomAttributesDataForOrThrow( method ) )
{
ArgumentValidator.ValidateNotNull( "Method", method );
if ( method.DeclaringType
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.IsGenericType && !method.DeclaringType
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.IsGenericTypeDefinition )
{
throw new ArgumentException( "This constructor may be used only on methods declared in genericless types or generic type definitions." );
}
if ( method is System.Reflection.MethodInfo && method.GetGenericArguments().Length > 0 && !method.IsGenericMethodDefinition )
{
throw new ArgumentException( "This constructor may be used only on genericless methods or generic method definitions." );
}
InitFields(
ctx,
ref this.callingConvention,
ref this.methodAttributes,
ref this.methodKind,
ref this.declaringType,
ref this.parameters,
ref this.il,
ref this.methodImplementationAttributes,
ref this.securityInfo,
new SettableValueForEnums<CallingConventions>( (CallingConventions) method.CallingConvention ),
new SettableValueForEnums<MethodAttributes>( (MethodAttributes) method.Attributes ),
this.cilKind == CILElementKind.Constructor ? MethodKind.Constructor : MethodKind.Method,
() => (CILType) ctx.Cache.GetOrAdd( method.DeclaringType ),
() => ctx.CollectionsFactory.NewListProxy<CILParameter>( method.GetParameters().Select( param => ctx.Cache.GetOrAdd( param ) ).ToList() ),
() =>
{
MethodIL result;
if ( this.HasILMethodBody() )
{
IEnumerable<Tuple<Boolean, Type>> locals;
Boolean initLocals;
IEnumerable<Tuple<ExceptionBlockType, Int32, Int32, Int32, Int32, Type, Int32>> exceptionBlocks;
Byte[] ilBytes;
ctx.WrapperCallbacks.GetMethodBodyDataOrThrow( method, out locals, out initLocals, out exceptionBlocks, out ilBytes );
result = new MethodILImpl(
this,
initLocals,
ilBytes,
locals.Select( t => Tuple.Create( t.Item1, ctx.NewWrapper( t.Item2 ) ) ).ToArray(),
exceptionBlocks.Select( t => Tuple.Create( t.Item1, t.Item2, t.Item3, t.Item4, t.Item5, ctx.NewWrapperAsType( t.Item6 ), t.Item7 ) ).ToArray(),
CreateNativeTokenResolverCallback( ctx, method )
);
}
else
{
result = null;
}
return result;
},
LazyFactory.NewWriteableLazy( () => ctx.WrapperCallbacks.GetMethodImplementationAttributesOrThrow( method ), ctx.LazyThreadSafetyMode ),
new Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>>( this.SecurityInfoFromAttributes, ctx.LazyThreadSafetyMode ),
true
);
}
private static Func<Int32, ILResolveKind, Object> CreateNativeTokenResolverCallback( CILReflectionContextImpl ctx, System.Reflection.MethodBase method )
{
var dType = method.DeclaringType;
var module = new Lazy<System.Reflection.Module>( () => ctx.WrapperCallbacks.GetModuleOfTypeOrThrow( dType ), ctx.LazyThreadSafetyMode );
var gArgs = dType
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.IsGenericType ? dType.GetGenericTypeDefinition().GetGenericArguments() : null;
var mgArgs = method is System.Reflection.MethodInfo && method.GetGenericArguments().Length > 0 ? ( (System.Reflection.MethodInfo) method ).GetGenericMethodDefinition().GetGenericArguments() : null;
return ( token, rKind ) =>
{
switch ( rKind )
{
case ILResolveKind.String:
return ctx.WrapperCallbacks.ResolveStringOrThrow( module.Value, token );
case ILResolveKind.Signature:
// TODO basically same thing as in ModuleReadingContext, except use this method to resolve tokens.
// Maybe could make static methods to ModuleReadingContext (ReadFieldSignature, ReadMethodSignature, ReadType) that would use callbacks to resolve tokens.
throw new NotImplementedException( "Implement creating method signature + var args from byte array (at this point)." );
default:
var retVal = ctx.WrapperCallbacks.ResolveTypeOrMemberOrThrow( module.Value, token, gArgs, mgArgs );
return retVal is Type ?
ctx.Cache.GetOrAdd( (Type) retVal ) :
( retVal is System.Reflection.FieldInfo ?
ctx.Cache.GetOrAdd( (System.Reflection.FieldInfo) retVal ) :
( retVal is System.Reflection.MethodInfo ?
(Object) ctx.Cache.GetOrAdd( (System.Reflection.MethodInfo) retVal ) :
ctx.Cache.GetOrAdd( (System.Reflection.ConstructorInfo) retVal )
)
);
}
};
}
protected CILMethodBaseImpl(
CILReflectionContextImpl ctx,
Int32 anID,
Boolean isCtor,
Lazy<ListProxy<CILCustomAttribute>> cAttrDataFunc,
SettableValueForEnums<CallingConventions> aCallingConvention,
SettableValueForEnums<MethodAttributes> aMethodAttributes,
Func<CILType> declaringTypeFunc,
Func<ListProxy<CILParameter>> parametersFunc,
Func<MethodIL> methodIL,
WriteableLazy<MethodImplAttributes> aMethodImplementationAttributes,
Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> aSecurityInfo,
Boolean resettablesAreSettable
)
: base( ctx, isCtor ? CILElementKind.Constructor : CILElementKind.Method, anID, cAttrDataFunc )
{
InitFields(
ctx,
ref this.callingConvention,
ref this.methodAttributes,
ref this.methodKind,
ref this.declaringType,
ref this.parameters,
ref this.il,
ref this.methodImplementationAttributes,
ref this.securityInfo,
aCallingConvention,
aMethodAttributes,
isCtor ? MethodKind.Constructor : MethodKind.Method,
declaringTypeFunc,
parametersFunc,
methodIL,
aMethodImplementationAttributes,
aSecurityInfo ?? new Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>>( () => ctx.CollectionsFactory.NewDictionary<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>(), ctx.LazyThreadSafetyMode ),
resettablesAreSettable
);
}
private static void InitFields(
CILReflectionContextImpl ctx,
ref SettableValueForEnums<CallingConventions> callingConvention,
ref SettableValueForEnums<MethodAttributes> methodAttributes,
ref MethodKind methodKind,
ref Lazy<CILType> declaringType,
ref ReadOnlyResettableLazy<ListProxy<CILParameter>> parameters,
ref WriteableLazy<MethodIL> il,
ref WriteableLazy<MethodImplAttributes> methodImplementationAttributes,
ref Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> securityInfo,
SettableValueForEnums<CallingConventions> aCallingConvention,
SettableValueForEnums<MethodAttributes> aMethodAttributes,
MethodKind aMethodKind,
Func<CILType> declaringTypeFunc,
Func<ListProxy<CILParameter>> parametersFunc,
Func<MethodIL> methodIL,
WriteableLazy<MethodImplAttributes> aMethodImplementationAttributes,
Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> securityInfoLazy,
Boolean resettablesAreSettable
)
{
var lazyThreadSafety = ctx.LazyThreadSafetyMode;
callingConvention = aCallingConvention;
methodAttributes = aMethodAttributes;
methodKind = aMethodKind;
declaringType = new Lazy<CILType>( declaringTypeFunc, lazyThreadSafety );
// TODO is ResettableAndSettableLazy really needed?
parameters = LazyFactory.NewReadOnlyResettableLazy( parametersFunc, lazyThreadSafety );
il = LazyFactory.NewWriteableLazy( resettablesAreSettable ? methodIL : () =>
{
throw new NotSupportedException( "Emitting IL is not supported for methods with generic non-definition declaring types or generic non-definition methods." );
}, lazyThreadSafety );
methodImplementationAttributes = aMethodImplementationAttributes;
securityInfo = securityInfoLazy;
}
public override String ToString()
{
return this.GetThisName() + "(" + String.Join( ", ", this.parameters.Value.CQ ) + ")";
}
protected abstract String GetThisName();
#region CILMethodBase Members
public MethodKind MethodKind
{
get
{
return this.methodKind;
}
}
public CallingConventions CallingConvention
{
set
{
this.callingConvention.Value = value;
}
get
{
return this.callingConvention.Value;
}
}
public virtual MethodAttributes Attributes
{
set
{
this.methodAttributes.Value = value;
}
get
{
return this.methodAttributes.Value;
}
}
public CILType DeclaringType
{
get
{
return this.declaringType.Value;
}
}
public MethodIL MethodIL
{
get
{
return this.il.Value;
}
}
public MethodImplAttributes ImplementationAttributes
{
set
{
this.methodImplementationAttributes.Value = value;
}
get
{
return this.methodImplementationAttributes.Value;
}
}
public CILParameter AddParameter( String name, ParameterAttributes attrs, CILTypeBase paramType )
{
this.ThrowIfNotCapableOfChanging();
CILParameter result;
result = this.context.Cache.NewBlankParameter( this, this.parameters.Value.CQ.Count, name, attrs, paramType );
this.parameters.Value.Add( result );
this.context.Cache.ForAllGenericInstancesOf<CILMethodBase, CILMethodBaseInternal>( (CILMethodBase) this, method => method.ResetParameterList() );
return result;
}
public Boolean RemoveParameter( CILParameter parameter )
{
this.ThrowIfNotCapableOfChanging();
var result = this.parameters.Value.Remove( parameter );
if ( result )
{
this.context.Cache.ForAllGenericInstancesOf<CILMethodBase, CILMethodBaseInternal>( this, method => method.ResetParameterList() );
}
return result;
}
public ListQuery<CILParameter> Parameters
{
get
{
return this.parameters.Value.CQ;
}
}
public MethodIL ResetMethodIL()
{
MethodIL retVal = this.il.Value;
if ( retVal != null )
{
this.il.Value = new MethodILImpl( this.DeclaringType.Module );
}
return retVal;
}
/// <summary>
/// Gets or sets the name of the module for platform invoke method.
/// </summary>
/// <value>The name of the module for platform invoke method.</value>
String PlatformInvokeModule { get; set; }
#endregion
#region CILMethodBaseInternal Members
SettableValueForEnums<CallingConventions> CILMethodBaseInternal.CallingConventionInternal
{
get
{
return this.callingConvention;
}
}
SettableValueForEnums<MethodAttributes> CILMethodBaseInternal.MethodAttributesInternal
{
get
{
return this.methodAttributes;
}
}
WriteableLazy<MethodImplAttributes> CILMethodBaseInternal.MethodImplementationAttributesInternal
{
get
{
return this.methodImplementationAttributes;
}
}
void CILMethodBaseInternal.ResetParameterList()
{
this.parameters.Reset();
}
#endregion
#region CILElementOwnedByChangeableTypeUT<CILMethodBase<TMQ,TIQ>> Members
public CILMethodBase ChangeDeclaringTypeUT( params CILTypeBase[] args )
{
// TODO return this if decl type has no gArgs and args is empty.
LogicalUtils.ThrowIfDeclaringTypeNotGeneric( this, args );
var gDef = this.declaringType.Value.GenericDefinition;
var thisMethod = this.ThisOrGDef();
return this.MakeGenericIfNeeded( this.context.Cache.MakeMethodWithGenericDeclaringType(
gDef == null ? this : ( MethodKind.Method == this.methodKind ? (CILMethodBase) gDef.DeclaredMethods[this.declaringType.Value.DeclaredMethods.IndexOf( (CILMethod) thisMethod )] : gDef.Constructors[this.declaringType.Value.Constructors.IndexOf( (CILConstructor) thisMethod )] ),
args
) );
}
#endregion
protected abstract CILMethodBase ThisOrGDef();
protected abstract CILMethodBase MakeGenericIfNeeded( CILMethodBase method );
#region CILElementInstantiable Members
public Boolean IsTrueDefinition
{
get
{
return this.IsCapableOfChanging() == null;
}
}
#endregion
public CILElementWithinILCode ElementTypeKind
{
get
{
return CILElementWithinILCode.Method;
}
}
public DictionaryQuery<SecurityAction, ListQuery<LogicalSecurityInformation>> DeclarativeSecurity
{
get
{
return this.securityInfo.Value.CQ.IQ;
}
}
public LogicalSecurityInformation AddDeclarativeSecurity( SecurityAction action, CILType securityAttributeType )
{
lock ( this.securityInfo.Value )
{
ListProxy<LogicalSecurityInformation> list;
if ( !this.securityInfo.Value.CQ.TryGetValue( action, out list ) )
{
list = this.context.CollectionsFactory.NewListProxy<LogicalSecurityInformation>();
this.securityInfo.Value.Add( action, list );
}
var result = new LogicalSecurityInformation( action, securityAttributeType );
list.Add( result );
return result;
}
}
public Boolean RemoveDeclarativeSecurity( LogicalSecurityInformation information )
{
lock ( this.securityInfo.Value )
{
var result = information != null;
if ( !result )
{
ListProxy<LogicalSecurityInformation> list;
if ( this.securityInfo.Value.CQ.TryGetValue( information.SecurityAction, out list ) )
{
result = list.Remove( information );
}
}
return result;
}
}
internal Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> DeclarativeSecurityInternal
{
get
{
return this.securityInfo;
}
}
}
internal class CILConstructorImpl : CILMethodBaseImpl, CILConstructor
{
internal CILConstructorImpl(
CILReflectionContextImpl ctx,
Int32 anID,
System.Reflection.ConstructorInfo ctor
)
: base( ctx, anID, ctor )
{
}
internal CILConstructorImpl(
CILReflectionContextImpl ctx,
Int32 anID,
CILType declaringType,
MethodAttributes attrs
)
: this(
ctx,
anID,
new Lazy<ListProxy<CILCustomAttribute>>( () => ctx.CollectionsFactory.NewListProxy<CILCustomAttribute>(), ctx.LazyThreadSafetyMode ),
new SettableValueForEnums<CallingConventions>( CallingConventions.Standard ),
new SettableValueForEnums<MethodAttributes>( attrs | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName ),
() => declaringType,
() => ctx.CollectionsFactory.NewListProxy<CILParameter>(),
() => new MethodILImpl( declaringType.Module ),
LazyFactory.NewWriteableLazy( () => MethodImplAttributes.IL, ctx.LazyThreadSafetyMode ),
null,
true
)
{
}
internal CILConstructorImpl(
CILReflectionContextImpl ctx,
Int32 anID,
Lazy<ListProxy<CILCustomAttribute>> cAttrDataFunc,
SettableValueForEnums<CallingConventions> aCallingConvention,
SettableValueForEnums<MethodAttributes> aMethodAttributes,
Func<CILType> declaringTypeFunc,
Func<ListProxy<CILParameter>> parametersFunc,
Func<MethodIL> methodIL,
WriteableLazy<MethodImplAttributes> aMethodImplementationAttributes,
Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> aSecurityInfo,
Boolean resettablesAreSettable
)
: base( ctx, anID, true, cAttrDataFunc, aCallingConvention, aMethodAttributes, declaringTypeFunc, parametersFunc, methodIL, aMethodImplementationAttributes, aSecurityInfo, resettablesAreSettable )
{
}
protected override String GetThisName()
{
return this.methodAttributes.Value.IsStatic() ? Miscellaneous.CLASS_CTOR_NAME : Miscellaneous.INSTANCE_CTOR_NAME;
}
#region CILElementOwnedByChangeableType<CILConstructor> Members
public CILConstructor ChangeDeclaringType( params CILTypeBase[] args )
{
return (CILConstructor) this.ChangeDeclaringTypeUT( args );
}
#endregion
protected override CILMethodBase ThisOrGDef()
{
return this;
}
protected override CILMethodBase MakeGenericIfNeeded( CILMethodBase method )
{
return method;
}
internal override string IsCapableOfChanging()
{
return ( (CommonFunctionality) this.declaringType.Value ).IsCapableOfChanging();
}
}
internal class CILMethodImpl : CILMethodBaseImpl, CILMethod, CILElementWithGenericArgs, CILMethodInternal
{
private readonly SettableValueForClasses<String> name;
private readonly Lazy<CILParameter> returnParameter;
private readonly Lazy<ListProxy<CILTypeBase>> gArgs;
private readonly WriteableLazy<CILMethod> gDef;
private readonly SettableValueForEnums<PInvokeAttributes> pInvokeAttributes;
private readonly SettableValueForClasses<String> pInvokeName;
private readonly SettableValueForClasses<String> pInvokeModule;
internal CILMethodImpl(
CILReflectionContextImpl ctx,
Int32 anID,
System.Reflection.MethodInfo method
)
: base( ctx, anID, method )
{
var nGDef = method.IsGenericMethodDefinition ? method : null;
// TODO SL support (via ctx events?
#if !CAM_LOGICAL_IS_SL
var dllImportAttr = method.GetCustomAttributes( typeof( System.Runtime.InteropServices.DllImportAttribute ), true ).FirstOrDefault() as System.Runtime.InteropServices.DllImportAttribute;
#endif
InitFields(
ctx,
ref this.name,
ref this.returnParameter,
ref this.gArgs,
ref this.gDef,
ref this.pInvokeAttributes,
ref this.pInvokeName,
ref this.pInvokeModule,
new SettableValueForClasses<String>( method.Name ),
() => ctx.Cache.GetOrAdd( method.ReturnParameter ),
() => ctx.CollectionsFactory.NewListProxy<CILTypeBase>( method.GetGenericArguments().Select( gArg => ctx.Cache.GetOrAdd( gArg ) ).ToList() ),
() => ctx.Cache.GetOrAdd( nGDef ),
new SettableValueForEnums<PInvokeAttributes>(
#if CAM_LOGICAL_IS_SL
(PInvokeAttributes) 0
#else
dllImportAttr == null ? (PInvokeAttributes) 0 : dllImportAttr.GetCorrespondingPInvokeAttributes()
#endif
),
new SettableValueForClasses<String>(
#if CAM_LOGICAL_IS_SL
null
#else
dllImportAttr == null ? null : dllImportAttr.EntryPoint
#endif
),
new SettableValueForClasses<String>(
#if CAM_LOGICAL_IS_SL
null
#else
dllImportAttr == null ? null : dllImportAttr.Value
#endif
),
true
);
}
internal CILMethodImpl( CILReflectionContextImpl ctx, Int32 anID, CILType declaringType, String name, MethodAttributes attrs, CallingConventions callingConventions )
: this(
ctx,
anID,
new Lazy<ListProxy<CILCustomAttribute>>( () => ctx.CollectionsFactory.NewListProxy<CILCustomAttribute>(), ctx.LazyThreadSafetyMode ),
new SettableValueForEnums<CallingConventions>( callingConventions ),
new SettableValueForEnums<MethodAttributes>( attrs ),
() => declaringType,
() => ctx.CollectionsFactory.NewListProxy<CILParameter>(),
() => new MethodILImpl( declaringType.Module ),
LazyFactory.NewWriteableLazy( () => MethodImplAttributes.IL, ctx.LazyThreadSafetyMode ),
null,
new SettableValueForClasses<String>( name ),
() => ctx.Cache.NewBlankParameter( ctx.Cache.ResolveMethodBaseID( anID ), E_CILLogical.RETURN_PARAMETER_POSITION, null, ParameterAttributes.None, null ),
() => ctx.CollectionsFactory.NewListProxy<CILTypeBase>(),
() => null,
null,
null,
null,
true )
{
}
internal CILMethodImpl(
CILReflectionContextImpl ctx,
Int32 anID,
Lazy<ListProxy<CILCustomAttribute>> cAttrDataFunc,
SettableValueForEnums<CallingConventions> aCallingConvention,
SettableValueForEnums<MethodAttributes> aMethodAttributes,
Func<CILType> declaringTypeFunc,
Func<ListProxy<CILParameter>> parametersFunc,
WriteableLazy<MethodImplAttributes> aMethodImplementationAttributes,
Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> aLogicalSecurityInformation,
SettableValueForClasses<String> aName,
Func<CILParameter> returnParameterFunc,
Func<ListProxy<CILTypeBase>> gArgsFunc,
Func<CILMethod> gDefFunc,
Boolean resettablesAreSettable = false
)
: this( ctx, anID, cAttrDataFunc, aCallingConvention, aMethodAttributes, declaringTypeFunc, parametersFunc, null, aMethodImplementationAttributes, aLogicalSecurityInformation, aName, returnParameterFunc, gArgsFunc, gDefFunc, null, null, null, resettablesAreSettable )
{
}
internal CILMethodImpl(
CILReflectionContextImpl ctx,
Int32 anID,
Lazy<ListProxy<CILCustomAttribute>> cAttrDataFunc,
SettableValueForEnums<CallingConventions> aCallingConvention,
SettableValueForEnums<MethodAttributes> aMethodAttributes,
Func<CILType> declaringTypeFunc,
Func<ListProxy<CILParameter>> parametersFunc,
Func<MethodIL> methodIL,
WriteableLazy<MethodImplAttributes> aMethodImplementationAttributes,
Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> aLogicalSecurityInformation,
SettableValueForClasses<String> aName,
Func<CILParameter> returnParameterFunc,
Func<ListProxy<CILTypeBase>> gArgsFunc,
Func<CILMethod> gDefFunc,
SettableValueForEnums<PInvokeAttributes> aPInvokeAttributes,
SettableValueForClasses<String> aPInvokeName,
SettableValueForClasses<String> aPInvokeModuleName,
Boolean resettablesAreSettable
)
: base( ctx, anID, false, cAttrDataFunc, aCallingConvention, aMethodAttributes, declaringTypeFunc, parametersFunc, methodIL, aMethodImplementationAttributes, aLogicalSecurityInformation, resettablesAreSettable )
{
InitFields(
ctx,
ref this.name,
ref this.returnParameter,
ref this.gArgs,
ref this.gDef,
ref this.pInvokeAttributes,
ref this.pInvokeName,
ref this.pInvokeModule,
aName,
returnParameterFunc,
gArgsFunc,
gDefFunc,
aPInvokeAttributes,
aPInvokeName,
aPInvokeModuleName,
resettablesAreSettable
);
}
private static void InitFields(
CILReflectionContextImpl ctx,
ref SettableValueForClasses<String> name,
ref Lazy<CILParameter> returnParameter,
ref Lazy<ListProxy<CILTypeBase>> gArgs,
ref WriteableLazy<CILMethod> gDef,
ref SettableValueForEnums<PInvokeAttributes> pInvokeAttributes,
ref SettableValueForClasses<String> pInvokeName,
ref SettableValueForClasses<String> pInvokeModule,
SettableValueForClasses<String> aName,
Func<CILParameter> returnParameterFunc,
Func<ListProxy<CILTypeBase>> gArgsFunc,
Func<CILMethod> gDefFunc,
SettableValueForEnums<PInvokeAttributes> aPInvokeAttributes,
SettableValueForClasses<String> aPInvokeName,
SettableValueForClasses<String> aPInvokeModule,
Boolean resettablesAreSettable
)
{
var lazyThreadSafety = ctx.LazyThreadSafetyMode;
name = aName;
returnParameter = new Lazy<CILParameter>( returnParameterFunc, lazyThreadSafety );
gArgs = new Lazy<ListProxy<CILTypeBase>>( gArgsFunc, lazyThreadSafety );
gDef = LazyFactory.NewWriteableLazy<CILMethod>( gDefFunc, lazyThreadSafety );
pInvokeAttributes = aPInvokeAttributes ?? new SettableValueForEnums<PInvokeAttributes>( (PInvokeAttributes) 0 );
pInvokeName = aPInvokeName ?? new SettableValueForClasses<String>( null );
pInvokeModule = aPInvokeModule ?? new SettableValueForClasses<String>( null );
}
public override String ToString()
{
return this.returnParameter.Value + base.ToString();
}
protected override String GetThisName()
{
var result = this.name.Value;
if ( this.gArgs.Value.CQ.Any() )
{
result += "[" + String.Join( ", ", this.gArgs.Value.CQ ) + "]";
}
return result;
}
#region CILElementWithSimpleName Members
public String Name
{
set
{
this.name.Value = value;
}
get
{
return this.name.Value;
}
}
#endregion
#region CILElementWithGenericArguments<CILMethod> Members
public CILMethod GenericDefinition
{
get
{
return this.gDef.Value;
}
}
#endregion
#region CILElementWithGenericArgs Members
ListProxy<CILTypeBase> CILElementWithGenericArgs.InternalGenericArguments
{
get
{
return this.gArgs.Value;
}
}
#endregion
#region CILElementWithSimpleNameInternal Members
SettableValueForClasses<String> CILElementWithSimpleNameInternal.NameInternal
{
get
{
return this.name;
}
}
#endregion
#region CILMethod Members
public PInvokeAttributes PlatformInvokeAttributes
{
get
{
return this.pInvokeAttributes.Value;
}
set
{
this.pInvokeAttributes.Value = value;
}
}
public String PlatformInvokeName
{
get
{
return this.pInvokeName.Value;
}
set
{
this.pInvokeName.Value = value;
}
}
public String PlatformInvokeModuleName
{
get
{
return this.pInvokeModule.Value;
}
set
{
this.pInvokeModule.Value = value;
}
}
public CILMethod MakeGenericMethod( params CILTypeBase[] args )
{
return this.context.Cache.MakeGenericMethod( this, this.GenericDefinition, args );
}
#endregion
#region CILElementOwnedByChangeableType<CILMethod> Members
public CILMethod ChangeDeclaringType( params CILTypeBase[] args )
{
return (CILMethod) this.ChangeDeclaringTypeUT( args );
}
#endregion
protected override CILMethodBase ThisOrGDef()
{
return this.gArgs.Value.CQ.Any() ? this.gDef.Value : this;
}
protected override CILMethodBase MakeGenericIfNeeded( CILMethodBase method )
{
return this.gArgs.Value.CQ.Any() ? ( (CILMethod) method ).MakeGenericMethod( this.gArgs.Value.CQ.ToArray() ) : method;
}
internal override String IsCapableOfChanging()
{
if ( this.HasGenericArguments() && !this.IsGenericDefinition() )
{
return "This method is generic method instance";
}
else
{
return ( (CommonFunctionality) this.declaringType.Value ).IsCapableOfChanging();
}
}
#region CILElementWithGenericArguments<CILMethod> Members
public CILTypeParameter[] DefineGenericParameters( String[] names )
{
CILTypeParameter[] result;
this.ThrowIfNotCapableOfChanging();
LogicalUtils.CheckWhenDefiningGArgs( this.gArgs.Value, names );
if ( names != null && names.Length > 0 )
{
result = Enumerable.Range( 0, names.Length ).Select( idx => this.context.Cache.NewBlankTypeParameter( this.declaringType.Value, this, names[idx], idx ) ).ToArray();
this.gArgs.Value.AddRange( result );
this.gDef.Value = this;
}
else
{
result = CILTypeImpl.EMPTY_TYPE_PARAMS;
}
return result;
}
#endregion
//public override MethodAttributes Attributes
//{
// set
// {
// base.Attributes = value;
// //LogicalUtils.CheckMethodAttributesForOverriddenMethods( this.methodAttributes, this.overriddenMethods.Value );
// }
//}
#region CILElementWithGenericArguments<CILMethod> Members
public ListQuery<CILTypeBase> GenericArguments
{
get
{
return this.gArgs.Value.CQ;
}
}
#endregion
#region CILMethod Members
public CILParameter ReturnParameter
{
get
{
return this.returnParameter.Value;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml;
using SIL.Lift.Merging;
using SIL.Lift.Validation;
namespace SIL.Lift.Parsing
{
/// <summary>
/// This class takes a file or DOM of lift and makes calls on a supplied "merger" object for what it finds there.
/// This design allows the same parser to be used for WeSay, FLEx, and unit tests, which all have different
/// domain models which they populate based on these calls.
/// </summary>
public class LiftParser<TBase, TEntry, TSense, TExample>
where TBase : class
where TEntry : class, TBase
where TSense : class, TBase
where TExample : class, TBase
{
// Parsing Errors should throw an exception
///<summary></summary>
public event EventHandler<ErrorArgs> ParsingWarning;
///<summary></summary>
public event EventHandler<StepsArgs> SetTotalNumberSteps;
///<summary></summary>
public event EventHandler<ProgressEventArgs> SetStepsCompleted;
///<summary></summary>
public event EventHandler<MessageArgs> SetProgressMessage;
private readonly ILexiconMerger<TBase, TEntry, TSense, TExample> _merger;
// private readonly ILimittedMerger<TBase, TEntry, TSense, TExample> _limitedMerger;
private const string _wsAttributeLabel = "lang";
private string _pathToLift;
private bool _cancelNow;
private DateTime _defaultCreationModificationUTC=default(DateTime);
private ILiftChangeDetector _changeDetector;
private ILiftChangeReport _changeReport;
///<summary>
/// Constructor.
///</summary>
public LiftParser(ILexiconMerger<TBase, TEntry, TSense, TExample> merger)
{
_merger = merger;
// _limitedMerger = _merger as ILimittedMerger<TBase, TEntry, TSense, TExample>;
}
/// <summary>
///
/// </summary>
// public virtual void ReadLiftDom(XmlDocument doc, DateTime defaultCreationModificationUTC)
// {
// DefaultCreationModificationUTC = defaultCreationModificationUTC;
//
// XmlNodeList entryNodes = doc.SelectNodes("/lift/entry");
// int numberOfEntriesRead = 0;
// const int kProgressReportingInterval = 50;
// int nextProgressPoint = numberOfEntriesRead + kProgressReportingInterval;
// ProgressTotalSteps = entryNodes.Count;
// foreach (XmlNode node in entryNodes)
// {
// ReadEntry(node);
// numberOfEntriesRead++;
// if (numberOfEntriesRead >= nextProgressPoint)
// {
// ProgressStepsCompleted = numberOfEntriesRead;
// nextProgressPoint = numberOfEntriesRead + kProgressReportingInterval;
// }
// if (_cancelNow)
// {
// break;
// }
// }
// }
internal void ReadRangeElement(string range, XmlNode node)
{
string id = Utilities.GetStringAttribute(node, "id");
string guid = Utilities.GetOptionalAttributeString(node, "guid");
string parent = Utilities.GetOptionalAttributeString(node, "parent");
LiftMultiText description = LocateAndReadMultiText(node, "description");
LiftMultiText label = LocateAndReadMultiText(node, "label");
LiftMultiText abbrev = LocateAndReadMultiText(node, "abbrev");
_merger.ProcessRangeElement(range, id, guid, parent, description, label, abbrev, node.OuterXml);
}
internal void ReadFieldDefinition(XmlNode node)
{
string tag = Utilities.GetStringAttribute(node, "tag"); //NB: Tag is correct (as of v12). Changed to "type" only on *instances* of <field> element
LiftMultiText description = ReadMultiText(node);
_merger.ProcessFieldDefinition(tag, description);
}
internal TEntry ReadEntry(XmlNode node)
{
if (_changeReport != null)
{
string id = Utilities.GetOptionalAttributeString(node, "id");
if (ChangeReport.GetChangeType(id) == LiftChangeReport.ChangeType.None)
return default(TEntry);
}
Extensible extensible = ReadExtensibleElementBasics(node);
DateTime dateDeleted = GetOptionalDate(node, "dateDeleted", default(DateTime));
if(dateDeleted != default(DateTime))
{
_merger.EntryWasDeleted(extensible, dateDeleted);
return default(TEntry);
}
int homograph = 0;
string order = Utilities.GetOptionalAttributeString(node, "order");
if (!String.IsNullOrEmpty(order))
{
if (!Int32.TryParse(order, out homograph))
homograph = 0;
}
TEntry entry = _merger.GetOrMakeEntry(extensible, homograph);
if (entry == null)// pruned
{
return entry;
}
LiftMultiText lexemeForm = LocateAndReadMultiText(node, "lexical-unit");
if (!lexemeForm.IsEmpty)
{
_merger.MergeInLexemeForm(entry, lexemeForm);
}
LiftMultiText citationForm = LocateAndReadMultiText(node, "citation");
if (!citationForm.IsEmpty)
{
_merger.MergeInCitationForm(entry, citationForm);
}
ReadNotes(node, entry);
var nodes = node.SelectNodes("sense");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadSense(n, entry);
}
nodes = node.SelectNodes("relation");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadRelation(n, entry);
}
nodes = node.SelectNodes("variant");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadVariant(n, entry);
}
nodes = node.SelectNodes("pronunciation");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadPronunciation(n, entry);
}
nodes = node.SelectNodes("etymology");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadEtymology(n, entry);
}
ReadExtensibleElementDetails(entry, node);
_merger.FinishEntry(entry);
return entry;
}
private void ReadNotes(XmlNode node, TBase e)
{
// REVIEW (SRMc): Should we detect multiple occurrences of the same
// type of note? See ReadExtensibleElementDetails() for how field
// elements are handled in this regard.
var nodes = node.SelectNodes("note");
if (nodes != null)
{
foreach (XmlNode noteNode in nodes)
{
string noteType = Utilities.GetOptionalAttributeString(noteNode, "type");
LiftMultiText noteText = ReadMultiText(noteNode);
_merger.MergeInNote(e, noteType, noteText, noteNode.OuterXml);
}
}
}
private void ReadRelation(XmlNode n, TBase parent)
{
string targetId = Utilities.GetStringAttribute(n, "ref");
string relationFieldName = Utilities.GetStringAttribute(n, "type");
_merger.MergeInRelation(parent, relationFieldName, targetId, n.OuterXml);
}
private void ReadPronunciation(XmlNode node, TEntry entry)
{
// if (_limitedMerger != null && _limitedMerger.DoesPreferXmlForPhonetic)
// {
// _limitedMerger.MergeInPronunciation(entry, node.OuterXml);
// return;
// }
LiftMultiText contents = ReadMultiText(node);
TBase pronunciation = _merger.MergeInPronunciation(entry, contents, node.OuterXml);
if (pronunciation != null)
{
var nodes = node.SelectNodes("media");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadMedia(n, pronunciation);
}
ReadExtensibleElementDetails(pronunciation, node);
}
}
private void ReadVariant(XmlNode node, TEntry entry)
{
LiftMultiText contents = ReadMultiText(node);
TBase variant = _merger.MergeInVariant(entry, contents, node.OuterXml);
if (variant != null)
ReadExtensibleElementDetails(variant, node);
}
private void ReadEtymology(XmlNode node, TEntry entry)
{
// if (_limitedMerger != null && _limitedMerger.DoesPreferXmlForEtymology)
// {
// _limitedMerger.MergeInEtymology(entry, node.OuterXml);
// return;
// }
string source = Utilities.GetOptionalAttributeString(node, "source");
string type = Utilities.GetOptionalAttributeString(node, "type");
LiftMultiText form = LocateAndReadMultiText(node, null);
LiftMultiText gloss = LocateAndReadOneElementPerFormData(node, "gloss");
TBase etymology = _merger.MergeInEtymology(entry, source, type, form, gloss, node.OuterXml);
if (etymology != null)
ReadExtensibleElementDetails(etymology, node);
}
private void ReadPicture(XmlNode n, TSense parent)
{
string href = Utilities.GetStringAttribute(n, "href");
LiftMultiText caption = LocateAndReadMultiText(n, "label");
if(caption.IsEmpty)
{
caption = null;
}
_merger.MergeInPicture(parent, href, caption);
}
private void ReadMedia(XmlNode n, TBase parent)
{
string href = Utilities.GetStringAttribute(n, "href");
LiftMultiText caption = LocateAndReadMultiText(n, "label");
if (caption.IsEmpty)
{
caption = null;
}
_merger.MergeInMedia(parent, href, caption);
}
/// <summary>
/// Read the grammatical-info information for either a sense or a reversal.
/// </summary>
private void ReadGrammi(TBase senseOrReversal, XmlNode senseNode)
{
XmlNode grammiNode = senseNode.SelectSingleNode("grammatical-info");
if (grammiNode != null)
{
string val = Utilities.GetStringAttribute(grammiNode, "value");
_merger.MergeInGrammaticalInfo(senseOrReversal, val, GetTraitList(grammiNode));
}
}
/// <summary>
/// Used for elements with traits that are not top level objects (extensibles) or forms.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private List<Trait> GetTraitList(XmlNode node)
{
List<Trait> traits = new List<Trait>();
var nodes = node.SelectNodes("trait");
if (nodes != null)
{
foreach (XmlNode traitNode in nodes)
traits.Add(GetTrait(traitNode));
}
return traits;
}
private void ReadSense(XmlNode node, TEntry entry)
{
TSense sense = _merger.GetOrMakeSense(entry, ReadExtensibleElementBasics(node), node.OuterXml);
FinishReadingSense(node, sense);
}
private void FinishReadingSense(XmlNode node, TSense sense)
{
if (sense != null)//not been pruned
{
ReadGrammi(sense, node);
LiftMultiText gloss = LocateAndReadOneElementPerFormData(node, "gloss");
if (!gloss.IsEmpty)
{
_merger.MergeInGloss(sense, gloss);
}
LiftMultiText def = LocateAndReadMultiText(node, "definition");
if (!def.IsEmpty)
{
_merger.MergeInDefinition(sense, def);
}
ReadNotes(node, sense);
var nodes = node.SelectNodes("example");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadExample(n, sense);
}
nodes = node.SelectNodes("relation");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadRelation(n, sense);
}
nodes = node.SelectNodes("illustration");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadPicture(n, sense);
}
nodes = node.SelectNodes("reversal");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadReversal(n, sense);
}
nodes = node.SelectNodes("subsense");
if (nodes != null)
{
foreach (XmlNode n in nodes)
ReadSubsense(n, sense);
}
ReadExtensibleElementDetails(sense, node);
}
// return sense;
}
private void ReadSubsense(XmlNode node, TSense sense)
{
TSense subsense = _merger.GetOrMakeSubsense(sense, ReadExtensibleElementBasics(node), node.OuterXml);
if (subsense != null)//wesay can't handle these in April 2008
{
FinishReadingSense(node, subsense);
}
}
private void ReadExample(XmlNode node, TSense sense)
{
TExample example = _merger.GetOrMakeExample(sense, ReadExtensibleElementBasics(node));
if (example != null)//not been pruned
{
LiftMultiText exampleSentence = LocateAndReadMultiText(node, null);
if (!exampleSentence.IsEmpty)
{
_merger.MergeInExampleForm(example, exampleSentence);
}
var nodes = node.SelectNodes("translation");
if (nodes != null)
{
foreach (XmlNode translationNode in nodes)
{
LiftMultiText translation = ReadMultiText(translationNode);
string type = Utilities.GetOptionalAttributeString(translationNode, "type");
_merger.MergeInTranslationForm(example, type, translation, translationNode.OuterXml);
}
}
string source = Utilities.GetOptionalAttributeString(node, "source");
if (source != null)
{
_merger.MergeInSource(example, source);
}
// REVIEW(SRMc): If you don't think the note element should be valid
// inside an example, then remove the next line and the corresponding
// chunk from the rng file.
// JH says: LIFT ver 0.13 is going to make notes available to all extensibles
// todo: remove this when that is true
ReadNotes(node, example);
ReadExtensibleElementDetails(example, node);
}
return;
}
private void ReadReversal(XmlNode node, TSense sense)
{
string type = Utilities.GetOptionalAttributeString(node, "type");
XmlNodeList nodelist = node.SelectNodes("main");
if (nodelist != null && nodelist.Count > 1)
{
NotifyFormatError(new LiftFormatException(String.Format("Only one <main> element is allowed inside a <reversal> element:\r\n{0}", node.OuterXml)));
}
TBase parent = null;
if (nodelist != null && nodelist.Count == 1)
parent = ReadParentReversal(type, nodelist[0]);
LiftMultiText text = ReadMultiText(node);
TBase reversal = _merger.MergeInReversal(sense, parent, text, type, node.OuterXml);
if (reversal != null)
ReadGrammi(reversal, node);
}
private TBase ReadParentReversal(string type, XmlNode node)
{
XmlNodeList nodelist = node.SelectNodes("main");
if (nodelist != null && nodelist.Count > 1)
{
NotifyFormatError(new LiftFormatException(String.Format("Only one <main> element is allowed inside a <main> element:\r\n{0}", node.OuterXml)));
}
TBase parent = null;
if (nodelist != null && nodelist.Count == 1)
parent = ReadParentReversal(type, nodelist[0]);
LiftMultiText text = ReadMultiText(node);
TBase reversal = _merger.GetOrMakeParentReversal(parent, text, type);
if (reversal != null)
ReadGrammi(reversal, node);
return reversal;
}
/// <summary>
/// read enough for finding a potential match to merge with
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private Extensible ReadExtensibleElementBasics(XmlNode node)
{
Extensible extensible = new Extensible();
extensible.Id = Utilities.GetOptionalAttributeString(node, "id");//actually not part of extensible (as of 8/1/2007)
//todo: figure out how to actually look it up:
// string flexPrefix = node.OwnerDocument.GetPrefixOfNamespace("http://fieldworks.sil.org");
// string flexPrefix = "flex";
// if (flexPrefix != null && flexPrefix != string.Empty)
{
string guidString = Utilities.GetOptionalAttributeString(node, /*flexPrefix + ":guid"*/"guid");
if (guidString != null)
{
try
{
extensible.Guid = new Guid(guidString);
}
catch (Exception)
{
NotifyFormatError(new LiftFormatException(String.Format("{0} is not a valid GUID", guidString)));
}
}
}
extensible.CreationTime = GetOptionalDate(node, "dateCreated", DefaultCreationModificationUTC);
extensible.ModificationTime = GetOptionalDate(node, "dateModified", DefaultCreationModificationUTC);
return extensible;
}
/// <summary>
/// Once we have the thing we're creating/merging with, we can read in any details,
/// i.e. traits, fields, and annotations
/// </summary>
/// <param name="target"></param>
/// <param name="node"></param>
/// <returns></returns>
private void ReadExtensibleElementDetails(TBase target, XmlNode node)
{
var nodes = node.SelectNodes("field");
if (nodes != null)
{
foreach (XmlNode fieldNode in nodes)
{
string fieldType = Utilities.GetStringAttribute(fieldNode, "type");
//string priorFieldWithSameTag = String.Format("preceding-sibling::field[@type='{0}']", fieldType);
// JH removed this Oct 2010... I can't figure out why this limitation, which is not supported logicall
// or by the schema, was in here. It was preventing, for example, multiple variants.
// if(fieldNode.SelectSingleNode(priorFieldWithSameTag) != null)
// {
// a fatal error
// throw new LiftFormatException(String.Format("Field with same type ({0}) as sibling not allowed. Context:{1}", fieldType, fieldNode.ParentNode.OuterXml));
// }
_merger.MergeInField(target,
fieldType,
GetOptionalDate(fieldNode, "dateCreated", default(DateTime)),
GetOptionalDate(fieldNode, "dateModified", default(DateTime)),
ReadMultiText(fieldNode),
GetTraitList(fieldNode));
}
}
ReadTraits(node, target);
//todo: read annotations
}
private void ReadTraits(XmlNode node, TBase target)
{
var nodes = node.SelectNodes("trait");
if (nodes != null)
{
foreach (XmlNode traitNode in nodes)
_merger.MergeInTrait(target,GetTrait(traitNode));
}
}
/// <summary>
/// careful, can't return null, so give MinValue
/// </summary>
/// <param name="xmlNode"></param>
/// <param name="attributeName"></param>
/// <param name="defaultDateTime">the time to use if this attribute isn't found</param>
/// <returns></returns>
private DateTime GetOptionalDate(XmlNode xmlNode, string attributeName, DateTime defaultDateTime)
{
if (xmlNode.Attributes != null)
{
XmlAttribute attr = xmlNode.Attributes[attributeName];
if (attr == null)
return defaultDateTime;
/* if the incoming data lacks a time, we'll have a kind of 'unspecified', else utc */
try
{
return Extensible.ParseDateTimeCorrectly(attr.Value);
}
catch (Exception e)
{
NotifyFormatError(e); // not a fatal error
}
}
return defaultDateTime;
}
private LiftMultiText LocateAndReadMultiText(XmlNode node, string query)
{
XmlNode element;
if (query == null)
{
element = node;
}
else
{
element = node.SelectSingleNode(query);
XmlNodeList nodes = node.SelectNodes(query);
if (nodes != null && nodes.Count > 1)
{
throw new LiftFormatException(
String.Format("Duplicated element of type {0} unexpected. Context:{1}",
query,
nodes[0].ParentNode == null ? "??" : nodes[0].ParentNode.OuterXml));
}
}
if (element != null)
{
return ReadMultiText(element);
}
return new LiftMultiText();
}
//
// private List<LiftMultiText> LocateAndReadOneOrMoreMultiText(XmlNode node, string query)
// {
// List<LiftMultiText> results = new List<LiftMultiText>();
// foreach (XmlNode n in node.SelectNodes(query))
// {
// results.Add(ReadMultiText(n));
// }
// return results;
// }
private LiftMultiText LocateAndReadOneElementPerFormData(XmlNode node, string query)
{
Debug.Assert(query != null);
LiftMultiText text = new LiftMultiText();
ReadFormNodes(node.SelectNodes(query), text);
return text;
}
internal LiftMultiText ReadMultiText(XmlNode node)
{
LiftMultiText text = new LiftMultiText();
ReadFormNodes(node.SelectNodes("form"), text);
return text;
}
private void ReadFormNodes(XmlNodeList nodesWithForms, LiftMultiText text)
{
foreach (XmlNode formNode in nodesWithForms)
{
try
{
string lang = Utilities.GetStringAttribute(formNode, _wsAttributeLabel);
XmlNode textNode= formNode.SelectSingleNode("text");
if (textNode != null)
{
// Add the separator if we need it.
if (textNode.InnerText.Length > 0)
text.AddOrAppend(lang, "", "; ");
foreach (XmlNode node in textNode.ChildNodes)
{
if (node.Name == "span")
{
var span = text.AddSpan(lang,
Utilities.GetOptionalAttributeString(node, "lang"),
Utilities.GetOptionalAttributeString(node, "class"),
Utilities.GetOptionalAttributeString(node, "href"),
node.InnerText.Length);
ReadSpanContent(text, lang, span, node);
}
else
{
text.AddOrAppend(lang, node.InnerText, "");
}
}
}
var nodelist = formNode.SelectNodes("annotation");
if (nodelist != null)
{
foreach (XmlNode annotationNode in nodelist)
{
Annotation annotation = GetAnnotation(annotationNode);
annotation.LanguageHint = lang;
text.Annotations.Add(annotation);
}
}
}
catch (Exception e)
{
// not a fatal error
NotifyFormatError(e);
}
}
}
private void ReadSpanContent(LiftMultiText text, string lang, LiftSpan span, XmlNode node)
{
Debug.Assert(node.Name == "span");
foreach (XmlNode xn in node.ChildNodes)
{
if (xn.Name == "span")
{
var spanLang = Utilities.GetOptionalAttributeString(xn, "lang");
if (spanLang == lang)
spanLang = null;
var spanInner = new LiftSpan(text.LengthOfAlternative(lang),
xn.InnerText.Length,
spanLang,
Utilities.GetOptionalAttributeString(xn, "class"),
Utilities.GetOptionalAttributeString(xn, "href"));
span.Spans.Add(spanInner);
ReadSpanContent(text, lang, spanInner, xn);
}
else
{
text.AddOrAppend(lang, xn.InnerText, "");
}
}
}
private Trait GetTrait(XmlNode traitNode)
{
Trait t = new Trait(Utilities.GetStringAttribute(traitNode, "name"),
Utilities.GetStringAttribute(traitNode, "value"));
var nodelist = traitNode.SelectNodes("annotation");
if (nodelist != null)
{
foreach (XmlNode annotationNode in nodelist)
{
Annotation annotation = GetAnnotation(annotationNode);
t.Annotations.Add(annotation);
}
}
return t;
}
private Annotation GetAnnotation(XmlNode annotationNode)
{
return new Annotation(Utilities.GetOptionalAttributeString(annotationNode, "name"),
Utilities.GetOptionalAttributeString(annotationNode, "value"),
GetOptionalDate(annotationNode, "when", default(DateTime)),
Utilities.GetOptionalAttributeString(annotationNode, "who"));
}
//private static bool NodeContentIsJustAString(XmlNode node)
//{
// return node.InnerText != null
// && (node.ChildNodes.Count == 1)
// && (node.ChildNodes[0].NodeType == XmlNodeType.Text)
// && node.InnerText.Trim() != string.Empty;
//}
// public LexExampleSentence ReadExample(XmlNode xmlNode)
// {
// LexExampleSentence example = new LexExampleSentence();
// LocateAndReadMultiText(xmlNode, "source", example.Sentence);
// //NB: will only read in one translation
// LocateAndReadMultiText(xmlNode, "trans", example.Translation);
// return example;
// }
//
/// <summary>
/// Read a LIFT file. Must be the current lift version.
/// </summary>
public int ReadLiftFile(string pathToLift)
{
_pathToLift = pathToLift; // may need this to find its ranges file.
if (_defaultCreationModificationUTC == default(DateTime))
{
_defaultCreationModificationUTC = File.GetLastWriteTimeUtc(pathToLift);
}
ProgressTotalSteps = GetEstimatedNumberOfEntriesInFile(pathToLift);
ProgressStepsCompleted = 0;
if (Validator.GetLiftVersion(pathToLift) != Validator.LiftVersion)
{
throw new LiftFormatException("Programmer should migrate the lift file before calling this method.");
}
int numberOfEntriesRead;
if (_changeDetector != null && _changeDetector.CanProvideChangeRecord)
{
ProgressMessage = "Detecting Changes To Lift File...";
_changeReport = _changeDetector.GetChangeReport(new NullProgress());
}
using (XmlReader reader = XmlReader.Create(pathToLift, NormalReaderSettings))
{
reader.ReadStartElement("lift");
ReadHeader(reader);
numberOfEntriesRead = ReadEntries(reader);
}
if (_changeReport != null && _changeReport.IdsOfDeletedEntries.Count > 0)
{
ProgressMessage = "Removing entries that were removed from the Lift file...";
foreach (string id in _changeReport.IdsOfDeletedEntries)
{
Extensible eInfo = new Extensible();
eInfo.Id = id;
_merger.EntryWasDeleted(eInfo, default(DateTime) /* we don't know... why is this part of the interface, anyhow? */);
}
}
return numberOfEntriesRead;
}
/// <summary>
/// Intended to be fast, and only (probably) acurate
/// </summary>
/// <param name="pathToLift"></param>
/// <returns></returns>
internal static int GetEstimatedNumberOfEntriesInFile(string pathToLift)
{
int count = 0;
using (FileStream stream = File.OpenRead(pathToLift))
{
using (StreamReader reader = new StreamReader(stream))
{
while (reader.Peek() >= 0)
{
string line = reader.ReadLine();
if (line != null)
count += System.Text.RegularExpressions.Regex.Matches(line, "<entry").Count;
}
}
}
return count;
}
private static XmlReaderSettings NormalReaderSettings
{
get
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.None;
readerSettings.IgnoreComments = true;
return readerSettings;
}
}
private int ReadEntries(XmlReader reader)
{
// Process all of the entry elements, reading them into memory one at a time.
ProgressMessage = "Reading entries from LIFT file";
if (!reader.IsStartElement("entry"))
reader.ReadToFollowing("entry"); // not needed if no <header> element.
const int kProgressReportingInterval = 50;
int numberOfEntriesRead = 0;
int nextProgressPoint = numberOfEntriesRead + kProgressReportingInterval;
while (reader.IsStartElement("entry"))
{
string entryXml = reader.ReadOuterXml();
if (!String.IsNullOrEmpty(entryXml))
{
ReadEntry(GetNodeFromString(entryXml));
}
numberOfEntriesRead++;
if (numberOfEntriesRead >= nextProgressPoint)
{
ProgressStepsCompleted = numberOfEntriesRead;
nextProgressPoint = numberOfEntriesRead + kProgressReportingInterval;
}
if (_cancelNow)
{
break;
}
}
return numberOfEntriesRead;
}
/// <summary>
/// used to adapt between the DOM/XmlNode-based stuff John wrote initially, and the Reader-based stuff Steve added
/// </summary>
private static XmlNode GetNodeFromString(string xml)
{
XmlDocument document = new XmlDocument();
document.PreserveWhitespace = true; // needed to preserve newlines in "multiparagraph" forms.
document.LoadXml(xml);
return document.FirstChild;
}
private void ReadHeader(XmlReader reader)
{
if (reader.IsStartElement("header"))
{
ProgressMessage = "Reading LIFT file header";
bool headerIsEmpty = reader.IsEmptyElement;
reader.ReadStartElement("header");
if (!headerIsEmpty)
{
ReadRanges(reader); // can exist here or after fields
if (reader.IsStartElement("fields"))
{
bool fieldsIsEmpty = reader.IsEmptyElement;
reader.ReadStartElement("fields");
if (!fieldsIsEmpty)
{
while (reader.IsStartElement("field"))
{
string fieldXml = reader.ReadOuterXml();
if (!String.IsNullOrEmpty(fieldXml))
{
ReadFieldDefinition(GetNodeFromString(fieldXml));
}
}
Debug.Assert(reader.LocalName == "fields");
reader.ReadEndElement(); // </fields>
}
}
ReadRanges(reader); // can exist here or before fields
// Not sure why this is needed, but the assert is sometimes thrown otherwise if
// whitespace separates the end elements here.
reader.MoveToContent();
Debug.Assert(reader.LocalName == "header");
reader.ReadEndElement(); // </header>
}
}
}
private void ReadRanges(XmlReader reader)
{
if (reader.IsStartElement("ranges"))
{
bool rangesIsEmpty = reader.IsEmptyElement;
reader.ReadStartElement("ranges");
if (!rangesIsEmpty)
{
while (reader.IsStartElement("range"))
{
bool rangeIsEmpty = reader.IsEmptyElement;
string id = reader.GetAttribute("id");
string href = reader.GetAttribute("href");
string guid = reader.GetAttribute("guid");
ProgressMessage = string.Format("Reading LIFT range {0}", id);
reader.ReadStartElement();
if (string.IsNullOrEmpty(href))
{
while (reader.IsStartElement("range-element"))
{
string rangeXml = reader.ReadOuterXml();
if (!String.IsNullOrEmpty(rangeXml))
{
ReadRangeElement(id, GetNodeFromString(rangeXml));
}
}
}
else
{
ReadExternalRange(href, id, guid);
}
if (!rangeIsEmpty)
{
reader.MoveToContent();
reader.ReadEndElement(); // </range>
}
}
Debug.Assert(reader.LocalName == "ranges");
reader.ReadEndElement(); // </ranges>
}
}
}
// /// <summary>
// /// Return the number of entries processed from the most recent file.
// /// </summary>
// this was a confusing way to return the results of a parse operation.
// the parser should really return this value, if flex
// needs it
// public int EntryCount
// {
// get { return _count; }
// }
/// <summary>
/// Read a range from a separate file.
/// </summary>
/// <param name="pathToRangeFile"></param>
/// <param name="rangeId"></param>
/// <param name="rangeGuid"></param>
private void ReadExternalRange(string pathToRangeFile, string rangeId, string rangeGuid)
{
if (pathToRangeFile.StartsWith("file://"))
pathToRangeFile = pathToRangeFile.Substring(7);
if (!File.Exists(pathToRangeFile))
{
// try to find range file next to the lift file (may have been copied to another
// directory or another machine)
string dir = Path.GetDirectoryName(_pathToLift);
string file = Path.GetFileName(pathToRangeFile);
if (dir != null && file != null)
pathToRangeFile = Path.Combine(dir, file);
if (!File.Exists(pathToRangeFile))
return; // ignore missing range file without error.
}
using (XmlReader reader = XmlReader.Create(pathToRangeFile, NormalReaderSettings))
{
reader.ReadStartElement("lift-ranges");
while (reader.IsStartElement("range"))
{
string id = reader.GetAttribute("id");
// unused string guid = reader.GetAttribute("guid");
bool foundDesiredRange = id == rangeId;
bool emptyRange = reader.IsEmptyElement;
reader.ReadStartElement();
if (!emptyRange)
{
while (reader.IsStartElement("range-element"))
{
string rangeElementXml = reader.ReadOuterXml();
if (foundDesiredRange && !String.IsNullOrEmpty(rangeElementXml))
{
ReadRangeElement(id, GetNodeFromString(rangeElementXml));
}
}
Debug.Assert(reader.LocalName == "range");
reader.ReadEndElement(); // </range>
}
if (foundDesiredRange)
return; // we've seen the range we wanted from this file.
}
}
}
#region Progress
///<summary>
/// This class passes on progress report related information to an event handler.
///</summary>
public class StepsArgs : EventArgs
{
private int _steps;
///<summary>
/// Get/set the current state of the progress bar in number of steps.
///</summary>
public int Steps
{
get { return _steps; }
set { _steps = value; }
}
}
///<summary>
/// This class passes on an exception that has been caught to an event handler.
///</summary>
public class ErrorArgs : EventArgs
{
private Exception _exception;
///<summary>
/// Get/set the Exception object being passed.
///</summary>
public Exception Exception
{
get { return _exception; }
set { _exception = value; }
}
}
///<summary>
/// This class passes on a a status message string to an event handler.
///</summary>
public class MessageArgs : EventArgs
{
private string _msg;
///<summary>
/// Get/set the status message string.
///</summary>
public string Message
{
get { return _msg; }
set { _msg = value; }
}
}
private int ProgressStepsCompleted
{
set
{
if (SetStepsCompleted != null)
{
ProgressEventArgs e = new ProgressEventArgs(value);
SetStepsCompleted.Invoke(this, e);
_cancelNow = e.Cancel;
}
}
}
private int ProgressTotalSteps
{
set
{
if (SetTotalNumberSteps != null)
{
StepsArgs e = new StepsArgs();
e.Steps = value;
SetTotalNumberSteps.Invoke(this, e);
}
}
}
private string ProgressMessage
{
set
{
if (SetProgressMessage != null)
{
MessageArgs e = new MessageArgs();
e.Message = value;
SetProgressMessage.Invoke(this, e);
}
}
}
///<summary>
/// Get/set the default DateTime value use for creation or modification times.
///</summary>
public DateTime DefaultCreationModificationUTC
{
get { return _defaultCreationModificationUTC; }
set { _defaultCreationModificationUTC = value; }
}
/// <summary>
/// Optional object that will tell us which entries actually need parsing/adding.
/// NB: it is up to the client of this class to do any deleting that the detector says is needed
/// </summary>
public ILiftChangeDetector ChangeDetector
{
get { return _changeDetector; }
set { _changeDetector = value; }
}
///<summary></summary>
public ILiftChangeReport ChangeReport
{
get { return _changeReport; }
set { _changeReport = value; }
}
/// <summary>
/// NB: this will always conver the exception to a LiftFormatException, if it isn't already
/// </summary>
/// <param name="error"></param>
private void NotifyFormatError(Exception error)
{
if (ParsingWarning != null)
{
//it's important to pass this on as a format error, which the client should be expecting
//to report without crashing.
if (!(error is LiftFormatException))
{
error = new LiftFormatException(error.Message, error);
}
ErrorArgs e = new ErrorArgs();
e.Exception = error;
ParsingWarning.Invoke(this, e);
}
}
///<summary>
/// This class passes on progress/cancel information to an event handler.
///</summary>
public class ProgressEventArgs : EventArgs
{
private readonly int _progress;
private bool _cancel;
///<summary>
/// Constructor.
///</summary>
public ProgressEventArgs(int progress)
{
_progress = progress;
}
///<summary>
/// Get the progress value for this event.
///</summary>
public int Progress
{
get { return _progress; }
}
///<summary>
/// Get/set the cancel flag for this event.
///</summary>
public bool Cancel
{
get { return _cancel; }
set { _cancel = value; }
}
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.SignalR.Transports
{
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Disposable fields are disposed from a different method")]
public abstract class TransportDisconnectBase : ITrackingConnection
{
private readonly HttpContext _context;
private readonly ITransportHeartbeat _heartbeat;
private TextWriter _outputWriter;
private ILogger _logger;
private int _timedOut;
private readonly IPerformanceCounterManager _counters;
private int _ended;
private TransportConnectionStates _state;
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "It can be set in any derived class.")]
protected string _lastMessageId;
internal static readonly Func<Task> _emptyTaskFunc = () => TaskAsyncHelper.Empty;
// The TCS that completes when the task returned by PersistentConnection.OnConnected does.
internal TaskCompletionSource<object> _connectTcs;
// Token that represents the end of the connection based on a combination of
// conditions (timeout, disconnect, connection forcibly ended, host shutdown)
private CancellationToken _connectionEndToken;
private SafeCancellationTokenSource _connectionEndTokenSource;
private Task _lastWriteTask = TaskAsyncHelper.Empty;
// Token that represents the host shutting down
private readonly CancellationToken _hostShutdownToken;
private IDisposable _hostRegistration;
private IDisposable _connectionEndRegistration;
// Token that represents the client disconnecting
private readonly CancellationToken _requestAborted;
internal HttpRequestLifeTime _requestLifeTime;
protected TransportDisconnectBase(HttpContext context, ITransportHeartbeat heartbeat, IPerformanceCounterManager performanceCounterManager, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory, IMemoryPool pool)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (heartbeat == null)
{
throw new ArgumentNullException("heartbeat");
}
if (performanceCounterManager == null)
{
throw new ArgumentNullException("performanceCounterManager");
}
if (applicationLifetime == null)
{
throw new ArgumentNullException("applicationLifetime");
}
if (loggerFactory == null)
{
throw new ArgumentNullException("loggerFactory");
}
Pool = pool;
_context = context;
_heartbeat = heartbeat;
_counters = performanceCounterManager;
_hostShutdownToken = applicationLifetime.ApplicationStopping;
_requestAborted = context.RequestAborted;
// Queue to protect against overlapping writes to the underlying response stream
WriteQueue = new TaskQueue();
_logger = loggerFactory.CreateLogger(GetType().FullName);
}
protected IMemoryPool Pool { get; private set; }
protected ILogger Logger
{
get
{
return _logger;
}
}
public string ConnectionId
{
get;
set;
}
protected string LastMessageId
{
get
{
return _lastMessageId;
}
}
protected virtual Task InitializeMessageId()
{
_lastMessageId = Context.Request.Query["messageId"];
return TaskAsyncHelper.Empty;
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This is for async.")]
public virtual Task<string> GetGroupsToken()
{
return TaskAsyncHelper.FromResult(Context.Request.Query["groupsToken"].ToString());
}
internal TaskQueue WriteQueue
{
get;
set;
}
public Func<bool, Task> Disconnected { get; set; }
// Token that represents the client disconnecting
public virtual CancellationToken CancellationToken
{
get
{
return _requestAborted;
}
}
public virtual bool IsAlive
{
get
{
// If the CTS is tripped or the request has ended then the connection isn't alive
return !(
CancellationToken.IsCancellationRequested ||
(_requestLifeTime != null && _requestLifeTime.Task.IsCompleted) ||
_lastWriteTask.IsCanceled ||
_lastWriteTask.IsFaulted
);
}
}
public Task ConnectTask
{
get
{
return _connectTcs.Task;
}
}
protected CancellationToken ConnectionEndToken
{
get
{
return _connectionEndToken;
}
}
protected CancellationToken HostShutdownToken
{
get
{
return _hostShutdownToken;
}
}
public bool IsTimedOut
{
get
{
return _timedOut == 1;
}
}
public virtual bool SupportsKeepAlive
{
get
{
return true;
}
}
public virtual bool RequiresTimeout
{
get
{
return false;
}
}
public virtual TimeSpan DisconnectThreshold
{
get { return TimeSpan.FromSeconds(5); }
}
protected bool IsConnectRequest
{
get
{
return Context.Request.LocalPath().EndsWith("/connect", StringComparison.OrdinalIgnoreCase);
}
}
protected bool IsSendRequest
{
get
{
return Context.Request.LocalPath().EndsWith("/send", StringComparison.OrdinalIgnoreCase);
}
}
protected bool IsAbortRequest
{
get
{
return Context.Request.LocalPath().EndsWith("/abort", StringComparison.OrdinalIgnoreCase);
}
}
protected virtual bool SuppressReconnect
{
get
{
return false;
}
}
protected ITransportConnection Connection { get; set; }
protected HttpContext Context
{
get { return _context; }
}
protected ITransportHeartbeat Heartbeat
{
get { return _heartbeat; }
}
protected void IncrementErrors()
{
_counters.ErrorsTransportTotal.Increment();
_counters.ErrorsTransportPerSec.Increment();
_counters.ErrorsAllTotal.Increment();
_counters.ErrorsAllPerSec.Increment();
}
public abstract void IncrementConnectionsCount();
public abstract void DecrementConnectionsCount();
public Task Disconnect()
{
return Abort(clean: false);
}
protected Task Abort()
{
return Abort(clean: true);
}
private Task Abort(bool clean)
{
if (clean)
{
ApplyState(TransportConnectionStates.Aborted);
}
else
{
ApplyState(TransportConnectionStates.Disconnected);
}
Logger.LogInformation("Abort(" + ConnectionId + ")");
// When a connection is aborted (graceful disconnect) we send a command to it
// telling to to disconnect. At that moment, we raise the disconnect event and
// remove this connection from the heartbeat so we don't end up raising it for the same connection.
Heartbeat.RemoveConnection(this);
// End the connection
End();
var disconnectTask = Disconnected != null ? Disconnected(clean) : TaskAsyncHelper.Empty;
// Ensure delegate continues to use the C# Compiler static delegate caching optimization.
return disconnectTask
.Catch((ex, state) => OnDisconnectError(ex, state), state: Logger, logger: Logger)
.Finally(state =>
{
var counters = (IPerformanceCounterManager)state;
counters.ConnectionsDisconnected.Increment();
}, _counters);
}
public void ApplyState(TransportConnectionStates states)
{
_state |= states;
}
public void Timeout()
{
if (Interlocked.Exchange(ref _timedOut, 1) == 0)
{
Logger.LogInformation("Timeout(" + ConnectionId + ")");
End();
}
}
public virtual Task KeepAlive()
{
return TaskAsyncHelper.Empty;
}
public void End()
{
if (Interlocked.Exchange(ref _ended, 1) == 0)
{
Logger.LogInformation("End(" + ConnectionId + ")");
if (_connectionEndTokenSource != null)
{
_connectionEndTokenSource.Cancel();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_connectionEndTokenSource.Dispose();
_connectionEndRegistration.Dispose();
_hostRegistration.Dispose();
ApplyState(TransportConnectionStates.Disposed);
}
}
protected internal Task EnqueueOperation(Func<Task> writeAsync)
{
return EnqueueOperation(state => ((Func<Task>)state).Invoke(), writeAsync);
}
protected virtual internal Task EnqueueOperation(Func<object, Task> writeAsync, object state)
{
if (!IsAlive)
{
return TaskAsyncHelper.Empty;
}
// Only enqueue new writes if the connection is alive
Task writeTask = WriteQueue.Enqueue(writeAsync, state);
_lastWriteTask = writeTask;
return writeTask;
}
protected virtual Task InitializePersistentState()
{
_requestLifeTime = new HttpRequestLifeTime(this, WriteQueue, Logger, ConnectionId);
// Create the TCS that completes when the task returned by PersistentConnection.OnConnected does.
_connectTcs = new TaskCompletionSource<object>();
// Create a token that represents the end of this connection's life
_connectionEndTokenSource = new SafeCancellationTokenSource();
_connectionEndToken = _connectionEndTokenSource.Token;
// Handle the shutdown token's callback so we can end our token if it trips
_hostRegistration = _hostShutdownToken.SafeRegister(state =>
{
((SafeCancellationTokenSource)state).Cancel();
},
_connectionEndTokenSource);
// When the connection ends release the request
_connectionEndRegistration = CancellationToken.SafeRegister(state =>
{
((HttpRequestLifeTime)state).Complete();
},
_requestLifeTime);
return InitializeMessageId();
}
private static void OnDisconnectError(AggregateException ex, object state)
{
((ILogger)state).LogError("Failed to raise disconnect: " + ex.GetBaseException());
}
}
}
| |
/*
* 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.
*/
namespace Apache.Ignite.Core.Impl.Cache
{
using System;
using System.Collections.Generic;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Cache affinity implementation.
/// </summary>
internal class CacheAffinityImpl : PlatformTargetAdapter, ICacheAffinity
{
/** */
private const int OpAffinityKey = 1;
/** */
private const int OpAllPartitions = 2;
/** */
private const int OpBackupPartitions = 3;
/** */
private const int OpIsBackup = 4;
/** */
private const int OpIsPrimary = 5;
/** */
private const int OpIsPrimaryOrBackup = 6;
/** */
private const int OpMapKeyToNode = 7;
/** */
private const int OpMapKeyToPrimaryAndBackups = 8;
/** */
private const int OpMapKeysToNodes = 9;
/** */
private const int OpMapPartitionToNode = 10;
/** */
private const int OpMapPartitionToPrimaryAndBackups = 11;
/** */
private const int OpMapPartitionsToNodes = 12;
/** */
private const int OpPartition = 13;
/** */
private const int OpPrimaryPartitions = 14;
/** */
private const int OpPartitions = 15;
/** */
private readonly bool _keepBinary;
/** Grid. */
private readonly IIgniteInternal _ignite;
/// <summary>
/// Initializes a new instance of the <see cref="CacheAffinityImpl" /> class.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="keepBinary">Keep binary flag.</param>
public CacheAffinityImpl(IPlatformTargetInternal target, bool keepBinary) : base(target)
{
_keepBinary = keepBinary;
_ignite = target.Marshaller.Ignite;
}
/** <inheritDoc /> */
public int Partitions
{
get { return (int) DoOutInOp(OpPartitions); }
}
/** <inheritDoc /> */
public int GetPartition<TK>(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return (int)DoOutOp(OpPartition, key);
}
/** <inheritDoc /> */
public bool IsPrimary<TK>(IClusterNode n, TK key)
{
IgniteArgumentCheck.NotNull(n, "n");
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(OpIsPrimary, n.Id, key) == True;
}
/** <inheritDoc /> */
public bool IsBackup<TK>(IClusterNode n, TK key)
{
IgniteArgumentCheck.NotNull(n, "n");
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(OpIsBackup, n.Id, key) == True;
}
/** <inheritDoc /> */
public bool IsPrimaryOrBackup<TK>(IClusterNode n, TK key)
{
IgniteArgumentCheck.NotNull(n, "n");
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(OpIsPrimaryOrBackup, n.Id, key) == True;
}
/** <inheritDoc /> */
public int[] GetPrimaryPartitions(IClusterNode n)
{
IgniteArgumentCheck.NotNull(n, "n");
return DoOutInOp<Guid, int[]>(OpPrimaryPartitions, n.Id);
}
/** <inheritDoc /> */
public int[] GetBackupPartitions(IClusterNode n)
{
IgniteArgumentCheck.NotNull(n, "n");
return DoOutInOp<Guid, int[]>(OpBackupPartitions, n.Id);
}
/** <inheritDoc /> */
public int[] GetAllPartitions(IClusterNode n)
{
IgniteArgumentCheck.NotNull(n, "n");
return DoOutInOp<Guid, int[]>(OpAllPartitions, n.Id);
}
/** <inheritDoc /> */
public TR GetAffinityKey<TK, TR>(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp<TK, TR>(OpAffinityKey, key);
}
/** <inheritDoc /> */
public IDictionary<IClusterNode, IList<TK>> MapKeysToNodes<TK>(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOp(OpMapKeysToNodes, w => w.WriteEnumerable(keys),
reader => ReadDictionary(reader, ReadNode, r => (IList<TK>) r.ReadCollectionAsList<TK>()));
}
/** <inheritDoc /> */
public IClusterNode MapKeyToNode<TK>(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return GetNode(DoOutInOp<TK, Guid?>(OpMapKeyToNode, key));
}
/** <inheritDoc /> */
public IList<IClusterNode> MapKeyToPrimaryAndBackups<TK>(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp(OpMapKeyToPrimaryAndBackups, w => w.WriteObject(key), r => ReadNodes(r));
}
/** <inheritDoc /> */
public IClusterNode MapPartitionToNode(int part)
{
return GetNode(DoOutInOp<int, Guid?>(OpMapPartitionToNode, part));
}
/** <inheritDoc /> */
public IDictionary<int, IClusterNode> MapPartitionsToNodes(IEnumerable<int> parts)
{
IgniteArgumentCheck.NotNull(parts, "parts");
return DoOutInOp(OpMapPartitionsToNodes,
w => w.WriteEnumerable(parts),
reader => ReadDictionary(reader, r => r.ReadInt(), ReadNode));
}
/** <inheritDoc /> */
public IList<IClusterNode> MapPartitionToPrimaryAndBackups(int part)
{
return DoOutInOp(OpMapPartitionToPrimaryAndBackups, w => w.WriteObject(part), r => ReadNodes(r));
}
/** <inheritDoc /> */
protected override T Unmarshal<T>(IBinaryStream stream)
{
return Marshaller.Unmarshal<T>(stream, _keepBinary);
}
/// <summary>
/// Gets the node by id.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>Node.</returns>
private IClusterNode GetNode(Guid? id)
{
return _ignite.GetNode(id);
}
/// <summary>
/// Reads a node from stream.
/// </summary>
private IClusterNode ReadNode(BinaryReader r)
{
return GetNode(r.ReadGuid());
}
/// <summary>
/// Reads nodes from stream.
/// </summary>
private IList<IClusterNode> ReadNodes(IBinaryStream reader)
{
return IgniteUtils.ReadNodes(Marshaller.StartUnmarshal(reader, _keepBinary));
}
/// <summary>
/// Reads a dictionary from stream.
/// </summary>
private Dictionary<TK, TV> ReadDictionary<TK, TV>(IBinaryStream reader, Func<BinaryReader, TK> readKey,
Func<BinaryReader, TV> readVal)
{
var r = Marshaller.StartUnmarshal(reader, _keepBinary);
var cnt = r.ReadInt();
var dict = new Dictionary<TK, TV>(cnt);
for (var i = 0; i < cnt; i++)
dict[readKey(r)] = readVal(r);
return dict;
}
}
}
| |
//
// cpArbiter.cs
//
// Author:
// Jose Medrano <josmed@microsoft.com>
//
// Copyright (c) 2015
//
// 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.Linq;
using System;
using System.Collections.Generic;
namespace ChipmunkSharp
{
public class PointsDistance
{
public cpVect pointA, pointB;
/// Penetration distance of the two shapes. Overlapping means it will be negative.
/// This value is calculated as cpvdot(cpvsub(point2, point1), normal) and is ignored by cpArbiterSetContactPointSet().
public float distance;
}
public class cpContactPointSet
{
public int count;
/// The normal of the collision.
public cpVect normal;
public PointsDistance[] points;
}
/// @private
public class cpCollisionHandler
{
public static bool AlwaysCollide(cpArbiter arb, cpSpace space, object data) { return true; }
public static void DoNothing(cpArbiter arb, cpSpace space, object data) { }
public static cpCollisionHandler cpCollisionHandlerDoNothing
{
get
{
return new cpCollisionHandler(
cp.WILDCARD_COLLISION_TYPE,
cp.WILDCARD_COLLISION_TYPE,
AlwaysCollide,
AlwaysCollide,
DoNothing,
DoNothing, null
);
}
}
// Use the wildcard identifier since the default handler should never match any type pair.
public static cpCollisionHandler cpCollisionHandlerDefault
{
get
{
return new cpCollisionHandler(
cp.WILDCARD_COLLISION_TYPE,
cp.WILDCARD_COLLISION_TYPE,
DefaultBegin,
DefaultPreSolve,
DefaultPostSolve,
DefaultSeparate, null
);
}
}
public ulong typeA;
public ulong typeB;
public Func<cpArbiter, cpSpace, object, bool> beginFunc;
public Func<cpArbiter, cpSpace, object, bool> preSolveFunc;
public Action<cpArbiter, cpSpace, object> postSolveFunc;
public Action<cpArbiter, cpSpace, object> separateFunc;
public object userData;
public cpCollisionHandler()
{
this.typeA = cp.WILDCARD_COLLISION_TYPE;
this.typeB = cp.WILDCARD_COLLISION_TYPE;
beginFunc = DefaultBegin;
preSolveFunc = DefaultPreSolve;
postSolveFunc = DefaultPostSolve;
separateFunc = DefaultSeparate;
}
public cpCollisionHandler(ulong a, ulong b,
Func<cpArbiter, cpSpace, object, bool> begin,
Func<cpArbiter, cpSpace, object, bool> preSolve,
Action<cpArbiter, cpSpace, object> postSolve,
Action<cpArbiter, cpSpace, object> separate,
object userData
)
{
this.typeA = a;
this.typeB = b;
this.beginFunc = begin;
this.preSolveFunc = preSolve;
this.postSolveFunc = postSolve;
this.separateFunc = separate;
this.userData = userData;
}
public cpCollisionHandler Clone()
{
cpCollisionHandler copy = new cpCollisionHandler();
copy.typeA = typeA;
copy.typeB = typeB;
copy.beginFunc = beginFunc;
copy.preSolveFunc = preSolveFunc;
copy.postSolveFunc = postSolveFunc;
copy.separateFunc = separateFunc;
copy.userData = userData;
return copy;
}
public static bool DefaultBegin(cpArbiter arb, cpSpace space, object o)
{
return true;
}
public static bool DefaultPreSolve(cpArbiter arb, cpSpace space, object o)
{
return true;
}
public static void DefaultPostSolve(cpArbiter arb, cpSpace space, object o)
{
}
public static void DefaultSeparate(cpArbiter arb, cpSpace space, object o)
{
}
// Equals function for collisionHandlers.
public static bool SetEql(cpCollisionHandler check, cpCollisionHandler pair)
{
return (
(check.typeA == pair.typeA && check.typeB == pair.typeB) ||
(check.typeB == pair.typeA && check.typeA == pair.typeB)
);
}
};
/// @private
public enum cpArbiterState
{
// Arbiter is active and its the first collision.
FirstCollision = 1,
// Arbiter is active and its not the first collision.
Normal = 2,
// Collision has been explicitly ignored.
// Either by returning false from a begin collision handler or calling cpArbiterIgnore().
Ignore = 3,
// Collison is no longer active. A space will cache an arbiter for up to cpSpace.collisionPersistence more steps.
Cached = 4,
Invalidated = 5
} ;
/// A colliding pair of shapes.
public class cpArbiter
{
public ulong Key { get { return cp.CP_HASH_PAIR(a.hashid, b.hashid); } }
public static int CP_MAX_CONTACTS_PER_ARBITER = 4;
#region PUBLIC PROPS
/// Calculated value to use for the elasticity coefficient.
/// Override in a pre-solve collision handler for custom behavior.
public float e;
/// Calculated value to use for the friction coefficient.
/// Override in a pre-solve collision handler for custom behavior.
public float u;
/// Calculated value to use for applying surface velocities.
/// Override in a pre-solve collision handler for custom behavior.
public cpVect surface_vr { get; set; }
/// User definable data pointer.
/// The value will persist for the pair of shapes until the separate() callback is called.
/// NOTE: If you need to clean up this pointer, you should implement the separate() callback to do it.
//public cpDataPointer data;
public object data;
#endregion
#region PRIVATE PROPS
public cpShape a, b;
public cpBody body_a, body_b;
public cpArbiterThread thread_a, thread_b;
public List<cpContact> contacts { get; set; }
cpVect n;
public cpCollisionHandler handler, handlerA, handlerB;
public bool swapped;
public int stamp;
public cpArbiterState state;
#endregion
public int Count { get { return contacts.Count; } }
/// A colliding pair of shapes.
public cpArbiter(cpShape a, cpShape b)
{
this.handler = null;
this.swapped = false;
this.handlerA = null;
this.handlerB = null;
/// Calculated value to use for the elasticity coefficient.
/// Override in a pre-solve collision handler for custom behavior.
this.e = 0;
/// Calculated value to use for the friction coefficient.
/// Override in a pre-solve collision handler for custom behavior.
this.u = 0;
/// Calculated value to use for applying surface velocities.
/// Override in a pre-solve collision handler for custom behavior.
this.surface_vr = cpVect.Zero;
this.a = a; this.body_a = a.body;
this.b = b; this.body_b = b.body;
this.thread_a = new cpArbiterThread(null, null);
this.thread_b = new cpArbiterThread(null, null);
this.contacts = new List<cpContact>();
this.stamp = 0;
this.state = cpArbiterState.FirstCollision;
}
public void Unthread()
{
UnthreadHelper(this, this.body_a, this.thread_a.prev, this.thread_a.next);
UnthreadHelper(this, this.body_b, this.thread_b.prev, this.thread_b.next);
this.thread_a.prev = null;
this.thread_a.next = null;
this.thread_b.prev = null;
this.thread_b.next = null;
}
//public static void UnthreadHelper(cpArbiter arb, cpBody body)
//{
// cpArbiterThread thread = arb.ThreadForBody(body);
// cpArbiter prev = thread.prev;
// cpArbiter next = thread.next;
// // thread_x_y is quite ugly, but it avoids making unnecessary js objects per arbiter.
// if (prev != null)
// {
// cpArbiterThread nextPrev = prev.ThreadForBody(body);
// nextPrev.next = next;
// }
// else if (body.arbiterList == arb)
// {
// // IFF prev is NULL and body->arbiterList == arb, is arb at the head of the list.
// // This function may be called for an arbiter that was never in a list.
// // In that case, we need to protect it from wiping out the body->arbiterList pointer.
// body.arbiterList = next;
// }
// if (next != null)
// {
// cpArbiterThread threadNext = next.ThreadForBody(body);
// threadNext.prev = prev;
// }
// thread.prev = null;
// thread.next = null;
//}
public static void UnthreadHelper(cpArbiter arb, cpBody body, cpArbiter prev, cpArbiter next)
{
// thread_x_y is quite ugly, but it avoids making unnecessary js objects per arbiter.
if (prev != null)
{
// cpArbiterThreadForBody(prev, body)->next = next;
if (prev.body_a == body)
{
prev.thread_a.next = next;
}
else
{
prev.thread_b.next = next;
}
}
else
{
body.arbiterList = next;
}
if (next != null)
{
// cpArbiterThreadForBody(next, body)->prev = prev;
if (next.body_a == body)
{
next.thread_a.prev = prev;
}
else
{
next.thread_b.prev = prev;
}
}
}
/// Returns true if this is the first step a pair of objects started colliding.
public bool IsFirstContact()
{
return state == cpArbiterState.FirstCollision;
}
public bool IsRemoval()
{
return state == cpArbiterState.Invalidated;
}
public int GetCount()
{
// Return 0 contacts if we are in a separate callback.
return ((int)state < (int)cpArbiterState.Cached ? Count : 0);
}
/// Get the normal of the @c ith contact point.
public cpVect GetNormal()
{
return cpVect.cpvmult(n, this.swapped ? -1.0f : 1.0f);
}
public cpVect GetPointA(int i)
{
cp.AssertHard(0 <= i && i < GetCount(), "Index error: The specified contact index is invalid for this arbiter");
return cpVect.cpvadd(this.body_a.p, this.contacts[i].r1);
}
public cpVect GetPointB(int i)
{
cp.AssertHard(0 <= i && i < GetCount(), "Index error: The specified contact index is invalid for this arbiter");
return cpVect.cpvadd(this.body_b.p, this.contacts[i].r2);
}
/// Get the depth of the @c ith contact point.
public float GetDepth(int i)
{
// return this.contacts[i].dist;
cp.AssertHard(0 <= i && i < GetCount(), "Index error: The specified contact index is invalid for this arbiter");
cpContact con = contacts[i];
return cpVect.cpvdot(cpVect.cpvadd(cpVect.cpvsub(con.r2, con.r1), cpVect.cpvsub(this.body_b.p, this.body_a.p)), this.n);
}
/// Return a contact set from an arbiter.
public cpContactPointSet GetContactPointSet()
{
cpContactPointSet set = new cpContactPointSet();
set.count = GetCount();
set.points = new PointsDistance[set.count];
bool swapped = this.swapped;
set.normal = (swapped ? cpVect.cpvneg(this.n) : this.n);
for (int i = 0; i < set.count; i++)
{
// Contact points are relative to body CoGs;
cpVect p1 = cpVect.cpvadd(this.body_a.p, this.contacts[i].r1);
cpVect p2 = cpVect.cpvadd(this.body_b.p, this.contacts[i].r2);
set.points[i] = new PointsDistance();
set.points[i].pointA = (swapped ? p2 : p1);
set.points[i].pointB = (swapped ? p1 : p2);
set.points[i].distance = cpVect.cpvdot(cpVect.cpvsub(p2, p1), this.n);
}
return set;
}
public void SetContactPointSet(ref cpContactPointSet set)
{
int count = set.count;
cp.AssertHard(count == Count, "The number of contact points cannot be changed.");
this.n = (this.swapped ? cpVect.cpvneg(set.normal) : set.normal);
for (int i = 0; i < count; i++)
{
// Convert back to CoG relative offsets.
cpVect p1 = set.points[i].pointA;
cpVect p2 = set.points[i].pointB;
this.contacts[i].r1 = cpVect.cpvsub(swapped ? p2 : p1, this.body_a.p);
this.contacts[i].r2 = cpVect.cpvsub(swapped ? p1 : p2, this.body_b.p);
}
}
/// Calculate the total impulse that was applied by this arbiter.
/// This function should only be called from a post-solve, post-step or cpBodyEachArbiter callback.
public cpVect TotalImpulse()
{
cpVect sum = cpVect.Zero;
for (int i = 0, count = GetCount(); i < count; i++)
{
cpContact con = contacts[i];
// sum.Add(con.n.Multiply(con.jnAcc));
sum = cpVect.cpvadd(sum, cpVect.cpvrotate(n, new cpVect(con.jnAcc, con.jtAcc)));
}
return this.swapped ? sum : cpVect.cpvneg(sum);
}
/// Calculate the amount of energy lost in a collision including static, but not dynamic friction.
/// This function should only be called from a post-solve, post-step or cpBodyEachArbiter callback.
public float TotalKE()
{
float eCoef = (1f - this.e) / (1f + this.e);
float sum = 0.0f;
//cpContact contacts = contacts;
for (int i = 0, count = GetCount(); i < count; i++)
{
cpContact con = contacts[i];
float jnAcc = con.jnAcc;
float jtAcc = con.jtAcc;
sum += eCoef * jnAcc * jnAcc / con.nMass + jtAcc * jtAcc / con.tMass;
}
return sum;
}
/// Causes a collision pair to be ignored as if you returned false from a begin callback.
/// If called from a pre-step callback, you will still need to return false
/// if you want it to be ignored in the current step.
public bool Ignore()
{
this.state = cpArbiterState.Ignore;
return false;
}
public float GetRestitution()
{
return this.e;
}
public void SetRestitution(float restitution)
{
this.e = restitution;
}
public float GetFriction()
{
return this.u;
}
public void SetFriction(float friction)
{
this.u = friction;
}
public cpVect GetSurfaceVelocity()
{
return cpVect.cpvmult(this.surface_vr, this.swapped ? -1.0f : 1.0f);
}
public void SetSurfaceVelocity(cpVect vr)
{
this.surface_vr = cpVect.cpvmult(vr, this.swapped ? -1.0f : 1.0f);
}
public object GetUserData()
{
return this.data;
}
public void SetUserData(object userData)
{
this.data = userData;
}
/// Return the colliding shapes involved for this arbiter.
/// The order of their cpSpace.collision_type values will match
/// the order set when the collision handler was registered.
public void GetShapes(out cpShape a, out cpShape b)
{
if (swapped)
{
a = this.b; b = this.a;
}
else
a = this.a; b = this.b;
}
public void GetBodies(out cpBody a, out cpBody b)
{
cpShape shape_a, shape_b;
GetShapes(out shape_a, out shape_b);
a = shape_a.body;
b = shape_b.body;
}
public bool CallWildcardBeginA(cpSpace space)
{
cpCollisionHandler handler = this.handlerA;
return handler.beginFunc(this, space, handler.userData);
}
public bool CallWildcardBeginB(cpSpace space)
{
cpCollisionHandler handler = this.handlerB;
this.swapped = !this.swapped;
bool retval = handler.beginFunc(this, space, handler.userData);
this.swapped = !this.swapped;
return retval;
}
public bool CallWildcardPreSolveA(cpSpace space)
{
cpCollisionHandler handler = this.handlerA;
return handler.preSolveFunc(this, space, handler.userData);
}
public bool CallWildcardPreSolveB(cpSpace space)
{
cpCollisionHandler handler = this.handlerB;
this.swapped = !this.swapped;
bool retval = handler.preSolveFunc(this, space, handler.userData);
this.swapped = !this.swapped;
return retval;
}
public void CallWildcardPostSolveA(cpSpace space)
{
cpCollisionHandler handler = this.handlerA;
handler.postSolveFunc(this, space, handler.userData);
}
public void CallWildcardPostSolveB(cpSpace space)
{
cpCollisionHandler handler = this.handlerB;
this.swapped = !this.swapped;
handler.postSolveFunc(this, space, handler.userData);
this.swapped = !this.swapped;
}
public void CallWildcardSeparateA(cpSpace space)
{
cpCollisionHandler handler = this.handlerA;
handler.separateFunc(this, space, handler.userData);
}
public void CallWildcardSeparateB(cpSpace space)
{
cpCollisionHandler handler = this.handlerB;
this.swapped = !this.swapped;
handler.separateFunc(this, space, handler.userData);
this.swapped = !this.swapped;
}
public void Update(cpCollisionInfo info, cpSpace space)
{
cpShape a = info.a, b = info.b;
// For collisions between two similar primitive types, the order could have been swapped since the last frame.
this.a = a; this.body_a = a.body;
this.b = b; this.body_b = b.body;
// Iterate over the possible pairs to look for hash value matches.
for (int i = 0; i < info.count; i++)
{
cpContact con = info.arr[i];
// r1 and r2 store absolute offsets at init time.
// Need to convert them to relative offsets.
con.r1 = cpVect.cpvsub(con.r1, a.body.p);
con.r2 = cpVect.cpvsub(con.r2, b.body.p);
// Cached impulses are not zeroed at init time.
con.jnAcc = con.jtAcc = 0.0f;
for (int j = 0; j < this.Count; j++)
{
cpContact old = this.contacts[j];
// This could trigger false positives, but is fairly unlikely nor serious if it does.
if (con.hash == old.hash)
{
// Copy the persistant contact information.
con.jnAcc = old.jnAcc;
con.jtAcc = old.jtAcc;
}
}
}
//TODO: revise
this.contacts = info.arr.ToList();
//this.count = info.count;
this.n = info.n;
this.e = a.e * b.e;
this.u = a.u * b.u;
cpVect surface_vr = cpVect.cpvsub(b.surfaceV, a.surfaceV);
this.surface_vr = cpVect.cpvsub(surface_vr, cpVect.cpvmult(info.n, cpVect.cpvdot(surface_vr, info.n)));
ulong typeA = info.a.type, typeB = info.b.type;
cpCollisionHandler defaultHandler = space.defaultHandler;
cpCollisionHandler handler = this.handler = space.LookupHandler(typeA, typeB, defaultHandler);
// Check if the types match, but don't swap for a default handler which use the wildcard for type A.
bool swapped = this.swapped = (typeA != handler.typeA && handler.typeA != cp.WILDCARD_COLLISION_TYPE);
if (handler != defaultHandler || space.usesWildcards)
{
// The order of the main handler swaps the wildcard handlers too. Uffda.
this.handlerA = space.LookupHandler(swapped ? typeB : typeA, cp.WILDCARD_COLLISION_TYPE, cpCollisionHandler.cpCollisionHandlerDoNothing);
this.handlerB = space.LookupHandler(swapped ? typeA : typeB, cp.WILDCARD_COLLISION_TYPE, cpCollisionHandler.cpCollisionHandlerDoNothing);
}
// mark it as new if it's been cached
if (this.state == cpArbiterState.Cached)
this.state = cpArbiterState.FirstCollision;
}
public void PreStep(float dt, float slop, float bias)
{
cpBody a = this.body_a;
cpBody b = this.body_b;
cpVect n = this.n;
cpVect body_delta = cpVect.cpvsub(b.p, a.p);
for (var i = 0; i < Count; i++)
{
var con = this.contacts[i];
// Calculate the mass normal and mass tangent.
con.nMass = 1f / cp.k_scalar(a, b, con.r1, con.r2, n);
con.tMass = 1f / cp.k_scalar(a, b, con.r1, con.r2, cpVect.cpvperp(n));
// Calculate the target bias velocity.
// Calculate the target bias velocity.
float dist = cpVect.cpvdot(cpVect.cpvadd(cpVect.cpvsub(con.r2, con.r1), body_delta), n);
con.bias = -bias * cp.cpfmin(0.0f, dist + slop) / dt;
con.jBias = 0.0f;
// Calculate the target bounce velocity.
con.bounce = cp.normal_relative_velocity(a, b, con.r1, con.r2, n) * this.e;
}
}
public static cpArbiterThread ThreadForBody(cpArbiter arb, cpBody body)
{
return (arb.body_a == body ? arb.thread_a : arb.thread_b);
}
public cpArbiterThread ThreadForBody(cpBody body)
{
//TODO: THIS NEEDS RETURN THE ORIGINAL MEMORY REFERENCE IN ARBITER
if (this.body_a == body)
return thread_a;
else
return thread_b;
}
// Equal function for arbiterSet.
public static bool SetEql(cpShape[] shapes, cpArbiter arb)
{
cpShape a = shapes[0];
cpShape b = shapes[1];
return ((a == arb.a && b == arb.b) || (b == arb.a && a == arb.b));
}
public void ApplyCachedImpulse(float dt_coef)
{
if (this.IsFirstContact()) return;
var a = this.body_a;
var b = this.body_b;
cpVect n = this.n;
for (int i = 0; i < this.Count; i++)
{
cpContact con = this.contacts[i];
cpVect j = cpVect.cpvrotate(n, new cpVect(con.jnAcc, con.jtAcc));
cp.apply_impulses(a, b, con.r1, con.r2, cpVect.cpvmult(j, dt_coef));
}
}
public cpArbiter Next(cpBody body)
{
return (this.body_a == body ? this.thread_a.next : this.thread_b.next);
}
public void ApplyImpulse(float dt)
{
cpBody a = this.body_a;
cpBody b = this.body_b;
cpVect n = this.n;
cpVect surface_vr = this.surface_vr;
float friction = this.u;
for (int i = 0; i < this.Count; i++)
{
cpContact con = this.contacts[i];
float nMass = con.nMass;
cpVect r1 = con.r1;
cpVect r2 = con.r2;
cpVect vb1 = cpVect.cpvadd(a.v_bias, cpVect.cpvmult(cpVect.cpvperp(r1), a.w_bias));
cpVect vb2 = cpVect.cpvadd(b.v_bias, cpVect.cpvmult(cpVect.cpvperp(r2), b.w_bias));
cpVect vr = cpVect.cpvadd(cp.relative_velocity(a, b, r1, r2), surface_vr);
float vbn = cpVect.cpvdot(cpVect.cpvsub(vb2, vb1), n);
float vrn = cpVect.cpvdot(vr, n);
float vrt = cpVect.cpvdot(vr, cpVect.cpvperp(n));
float jbn = (con.bias - vbn) * nMass;
float jbnOld = con.jBias;
con.jBias = cp.cpfmax(jbnOld + jbn, 0.0f);
float jn = -(con.bounce + vrn) * nMass;
float jnOld = con.jnAcc;
con.jnAcc = cp.cpfmax(jnOld + jn, 0.0f);
float jtMax = friction * con.jnAcc;
float jt = -vrt * con.tMass;
float jtOld = con.jtAcc;
con.jtAcc = cp.cpfclamp(jtOld + jt, -jtMax, jtMax);
cp.apply_bias_impulses(a, b, r1, r2, cpVect.cpvmult(n, con.jBias - jbnOld));
cp.apply_impulses(a, b, r1, r2, cpVect.cpvrotate(n, new cpVect(con.jnAcc - jnOld, con.jtAcc - jtOld)));
};
}
}
///////////////////////////////////////////////////
public struct cpArbiterThread
{
public cpArbiter next, prev;
public cpArbiterThread(cpArbiter next, cpArbiter prev)
{
this.next = next;
this.prev = prev;
}
};
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
namespace System.Xml
{
internal class Base64Decoder : IncrementalReadDecoder
{
//
// Fields
//
byte[] buffer;
int startIndex;
int curIndex;
int endIndex;
int bits;
int bitsFilled;
private const string CharsBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private static readonly byte[] MapBase64 = ConstructMapBase64();
private const int MaxValidChar = (int)'z';
private const byte Invalid = unchecked((byte)-1);
//
// IncrementalReadDecoder interface
//
internal override int DecodedCount
{
get
{
return curIndex - startIndex;
}
}
internal override bool IsFull
{
get
{
return curIndex == endIndex;
}
}
internal override unsafe int Decode(char[] chars, int startPos, int len)
{
if (chars == null)
{
throw new ArgumentNullException("chars");
}
if (len < 0)
{
throw new ArgumentOutOfRangeException("len");
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException("startPos");
}
if (chars.Length - startPos < len)
{
throw new ArgumentOutOfRangeException("len");
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = &chars[startPos])
{
fixed (byte* pBytes = &buffer[curIndex])
{
Decode(pChars, pChars + len, pBytes, pBytes + (endIndex - curIndex), out charsDecoded, out bytesDecoded);
}
}
curIndex += bytesDecoded;
return charsDecoded;
}
internal override unsafe int Decode(string str, int startPos, int len)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (len < 0)
{
throw new ArgumentOutOfRangeException("len");
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException("startPos");
}
if (str.Length - startPos < len)
{
throw new ArgumentOutOfRangeException("len");
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = str)
{
fixed (byte* pBytes = &buffer[curIndex])
{
Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (endIndex - curIndex), out charsDecoded, out bytesDecoded);
}
}
curIndex += bytesDecoded;
return charsDecoded;
}
internal override void Reset()
{
bitsFilled = 0;
bits = 0;
}
internal override void SetNextOutputBuffer(byte[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(index >= 0);
Debug.Assert(buffer.Length - index >= count);
Debug.Assert((buffer as byte[]) != null);
this.buffer = (byte[])buffer;
this.startIndex = index;
this.curIndex = index;
this.endIndex = index + count;
}
//
// Private methods
//
private static byte[] ConstructMapBase64()
{
byte[] mapBase64 = new byte[MaxValidChar + 1];
for (int i = 0; i < mapBase64.Length; i++)
{
mapBase64[i] = Invalid;
}
for (int i = 0; i < CharsBase64.Length; i++)
{
mapBase64[(int)CharsBase64[i]] = (byte)i;
}
return mapBase64;
}
private unsafe void Decode(char* pChars, char* pCharsEndPos,
byte* pBytes, byte* pBytesEndPos,
out int charsDecoded, out int bytesDecoded)
{
#if DEBUG
Debug.Assert(pCharsEndPos - pChars >= 0);
Debug.Assert(pBytesEndPos - pBytes >= 0);
#endif
// walk hex digits pairing them up and shoving the value of each pair into a byte
byte* pByte = pBytes;
char* pChar = pChars;
int b = bits;
int bFilled = bitsFilled;
XmlCharType xmlCharType = XmlCharType.Instance;
while (pChar < pCharsEndPos && pByte < pBytesEndPos)
{
char ch = *pChar;
// end?
if (ch == '=')
{
break;
}
pChar++;
// ignore white space
if ((xmlCharType.charProperties[ch] & XmlCharType.fWhitespace) != 0)
{
continue;
}
int digit;
if (ch > 122 || (digit = MapBase64[ch]) == Invalid)
{
throw new XmlException(SR.Format(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars))));
}
b = (b << 6) | digit;
bFilled += 6;
if (bFilled >= 8)
{
// get top eight valid bits
*pByte++ = (byte)((b >> (bFilled - 8)) & 0xFF);
bFilled -= 8;
if (pByte == pBytesEndPos)
{
goto Return;
}
}
}
if (pChar < pCharsEndPos && *pChar == '=')
{
bFilled = 0;
// ignore padding chars
do
{
pChar++;
} while (pChar < pCharsEndPos && *pChar == '=');
// ignore whitespace after the padding chars
if (pChar < pCharsEndPos)
{
do
{
if (!((xmlCharType.charProperties[*pChar++] & XmlCharType.fWhitespace) != 0))
{
throw new XmlException(SR.Format(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars))));
}
} while (pChar < pCharsEndPos);
}
}
Return:
bits = b;
bitsFilled = bFilled;
bytesDecoded = (int)(pByte - pBytes);
charsDecoded = (int)(pChar - pChars);
}
}
}
| |
/***************************************************************************
* PodcastItem.cs
*
* Copyright (C) 2008 Michael C. Urbanski
* Written by Mike Urbanski <michael.c.urbanski@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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.Text;
using Mono.Unix;
using System.Collections.Generic;
using Hyena.Data.Sqlite;
using Banshee.MediaEngine;
using Banshee.ServiceStack;
using Banshee.Database;
using Banshee.Collection;
using Banshee.Collection.Database;
using Migo.Syndication;
namespace Banshee.Podcasting.Data
{
public enum PodcastItemActivity : int {
Downloading = 0,
DownloadPending = 1,
DownloadFailed = 2,
DownloadPaused = 3,
//NewPodcastItem = 4,
//Video = 5,
Downloaded = 6,
None = 7
}
public class PodcastTrackInfo : IPodcastInfo
{
public static PodcastTrackInfo From (TrackInfo track)
{
if (track != null) {
PodcastTrackInfo pi = track.ExternalObject as PodcastTrackInfo;
if (pi != null) {
track.ReleaseDate = pi.PublishedDate;
track.Enabled = !pi.Item.IsRead;
}
return pi;
}
return null;
}
public static IEnumerable<PodcastTrackInfo> From (IEnumerable<TrackInfo> tracks)
{
foreach (TrackInfo track in tracks) {
PodcastTrackInfo pi = From (track);
if (pi != null) {
yield return pi;
}
}
}
private DatabaseTrackInfo track;
#region Properties
public DatabaseTrackInfo Track {
get { return track; }
}
public Feed Feed {
get { return Item.Feed; }
}
private FeedItem item;
public FeedItem Item {
get {
if (item == null && track.ExternalId > 0) {
item = FeedItem.Provider.FetchSingle (track.ExternalId);
}
return item;
}
set { item = value; track.ExternalId = value.DbId; }
}
public DateTime PublishedDate {
get { return Item.PubDate; }
}
public string Description {
get { return Item.StrippedDescription; }
}
public bool IsNew {
get { return !Item.IsRead; }
}
public bool IsDownloaded {
get { return !String.IsNullOrEmpty (Enclosure.LocalPath); }
}
public DateTime ReleaseDate {
get { return Item.PubDate; }
}
public FeedEnclosure Enclosure {
get { return (Item == null) ? null : Item.Enclosure; }
}
public PodcastItemActivity Activity {
get {
switch (Item.Enclosure.DownloadStatus) {
case FeedDownloadStatus.Downloaded:
return PodcastItemActivity.Downloaded;
case FeedDownloadStatus.DownloadFailed:
return PodcastItemActivity.Downloaded;
case FeedDownloadStatus.Downloading:
return PodcastItemActivity.Downloading;
case FeedDownloadStatus.Pending:
return PodcastItemActivity.DownloadPending;
case FeedDownloadStatus.Paused:
return PodcastItemActivity.DownloadPaused;
default:
return PodcastItemActivity.None;
}
}
}
#endregion
#region Constructors
public PodcastTrackInfo (DatabaseTrackInfo track) : base ()
{
this.track = track;
}
public PodcastTrackInfo (DatabaseTrackInfo track, FeedItem feed_item) : this (track)
{
Item = feed_item;
SyncWithFeedItem ();
}
#endregion
static PodcastTrackInfo ()
{
TrackInfo.PlaybackFinished += OnPlaybackFinished;
}
private static void OnPlaybackFinished (TrackInfo track, double percentCompleted)
{
if (percentCompleted > 0.5 && track.PlayCount > 0) {
PodcastTrackInfo pi = PodcastTrackInfo.From (track);
if (pi != null && !pi.Item.IsRead) {
pi.Item.IsRead = true;
pi.Item.Save ();
}
}
}
public void SyncWithFeedItem ()
{
//Console.WriteLine ("Syncing item, enclosure == null? {0}", Item.Enclosure == null);
track.ArtistName = Item.Author;
track.AlbumTitle = Item.Feed.Title;
track.TrackTitle = Item.Title;
track.Year = Item.PubDate.Year;
track.CanPlay = true;
track.Genre = track.Genre ?? "Podcast";
track.ReleaseDate = Item.PubDate;
track.MimeType = Item.Enclosure.MimeType;
track.Duration = Item.Enclosure.Duration;
track.FileSize = Item.Enclosure.FileSize;
track.LicenseUri = Item.LicenseUri;
track.Uri = new Banshee.Base.SafeUri (Item.Enclosure.LocalPath ?? Item.Enclosure.Url);
if (!String.IsNullOrEmpty (Item.Enclosure.LocalPath)) {
try {
TagLib.File file = Banshee.Streaming.StreamTagger.ProcessUri (track.Uri);
Banshee.Streaming.StreamTagger.TrackInfoMerge (track, file, true);
} catch {}
}
track.MediaAttributes |= TrackMediaAttributes.Podcast;
}
}
}
| |
// 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.IO;
using FluentAssertions;
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Tools.Test.Utilities;
using NuGet.Frameworks;
using Xunit;
namespace Microsoft.DotNet.Cli.Utils.Tests
{
public class GivenAProjectDependenciesCommandFactory : TestBase
{
private static readonly NuGetFramework s_desktopTestFramework = FrameworkConstants.CommonFrameworks.Net451;
private RepoDirectoriesProvider _repoDirectoriesProvider;
public GivenAProjectDependenciesCommandFactory()
{
_repoDirectoriesProvider = new RepoDirectoriesProvider();
Environment.SetEnvironmentVariable(
Constants.MSBUILD_EXE_PATH,
Path.Combine(_repoDirectoriesProvider.Stage2Sdk, "MSBuild.dll"));
}
[WindowsOnlyFact]
public void It_resolves_desktop_apps_defaulting_to_Debug_Configuration()
{
var runtime = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var configuration = "Debug";
var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx")
.CreateInstance()
.WithSourceFiles()
.WithNuGetConfig(_repoDirectoriesProvider.TestPackages);
var restoreCommand = new RestoreCommand()
.WithWorkingDirectory(testInstance.Root)
.WithRuntime(runtime)
.ExecuteWithCapturedOutput()
.Should().Pass();
var buildCommand = new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithRuntime(runtime)
.WithCapturedOutput()
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
s_desktopTestFramework,
null,
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-desktop-and-portable", null);
command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName);
Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe");
}
[WindowsOnlyFact]
public void It_resolves_desktop_apps_when_configuration_is_Debug()
{
var runtime = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var configuration = "Debug";
var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx")
.CreateInstance()
.WithSourceFiles()
.WithNuGetConfig(_repoDirectoriesProvider.TestPackages);
var restoreCommand = new RestoreCommand()
.WithWorkingDirectory(testInstance.Root)
.WithRuntime(runtime)
.ExecuteWithCapturedOutput()
.Should().Pass();
var buildCommand = new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithRuntime(runtime)
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
s_desktopTestFramework,
configuration,
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-desktop-and-portable", null);
command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName);
Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe");
}
[WindowsOnlyFact]
public void It_resolves_desktop_apps_when_configuration_is_Release()
{
var runtime = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var configuration = "Debug";
var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx")
.CreateInstance()
.WithSourceFiles()
.WithNuGetConfig(_repoDirectoriesProvider.TestPackages);
var restoreCommand = new RestoreCommand()
.WithWorkingDirectory(testInstance.Root)
.WithRuntime(runtime)
.ExecuteWithCapturedOutput()
.Should().Pass();
var buildCommand = new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithRuntime(runtime)
.WithCapturedOutput()
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
s_desktopTestFramework,
configuration,
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-desktop-and-portable", null);
command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName);
Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe");
}
[WindowsOnlyFact]
public void It_resolves_desktop_apps_using_configuration_passed_to_create()
{
var runtime = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var configuration = "Debug";
var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx")
.CreateInstance()
.WithSourceFiles()
.WithNuGetConfig(_repoDirectoriesProvider.TestPackages);
var restoreCommand = new RestoreCommand()
.WithWorkingDirectory(testInstance.Root)
.WithRuntime(runtime)
.ExecuteWithCapturedOutput()
.Should().Pass();
var buildCommand = new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithRuntime(runtime)
.WithCapturedOutput()
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
s_desktopTestFramework,
"Debug",
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-desktop-and-portable", null, configuration: configuration);
command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName);
Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe");
}
[Fact]
public void It_resolves_tools_whose_package_name_is_different_than_dll_name()
{
Environment.SetEnvironmentVariable(
Constants.MSBUILD_EXE_PATH,
Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "MSBuild.dll"));
var configuration = "Debug";
var testInstance = TestAssets.Get("AppWithDirectDepWithOutputName")
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var buildCommand = new BuildCommand()
.WithProjectDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithCapturedOutput()
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
FrameworkConstants.CommonFrameworks.NetCoreApp10,
configuration,
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-tool-with-output-name", null);
command.CommandArgs.Should().Contain(
Path.Combine("toolwithoutputname", "1.0.0", "lib", "netcoreapp1.0", "dotnet-tool-with-output-name.dll"));
}
}
}
| |
// Copyright 2009 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
//#define USE_GLIB
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using DBus.Transports;
using org.freedesktop.DBus;
namespace DBus
{
public class ServerBus : org.freedesktop.DBus.IBus
{
public static readonly ObjectPath Path = new ObjectPath ("/org/freedesktop/DBus");
public const string DBusBusName = "org.freedesktop.DBus";
public const string DBusInterface = "org.freedesktop.DBus";
static string ValidateBusName (string name)
{
if (name == String.Empty)
return "cannot be empty";
//if (name.StartsWith (":"))
// return "cannot be a unique name";
return null;
}
static bool BusNameIsValid (string name, out string nameError)
{
nameError = ValidateBusName (name);
return nameError == null;
}
readonly List<Connection> conns = new List<Connection> ();
internal Server server;
ServerConnection Caller
{
get
{
return server.CurrentMessageConnection as ServerConnection;
}
}
public void AddConnection (Connection conn)
{
if (conns.Contains (conn))
throw new Exception ("Cannot add connection");
conns.Add (conn);
conn.Register (Path, this);
//((ExportObject)conn.RegisteredObjects[Path]).Registered = false;
}
public void RemoveConnection (Connection conn)
{
Console.Error.WriteLine ("RemoveConn");
if (!conns.Remove (conn))
throw new Exception ("Cannot remove connection");
//conn.Unregister (Path);
List<string> namesToDisown = new List<string> ();
foreach (KeyValuePair<string, Connection> pair in Names) {
if (pair.Value == conn)
namesToDisown.Add (pair.Key);
}
List<MatchRule> toRemove = new List<MatchRule> ();
foreach (KeyValuePair<MatchRule, List<Connection>> pair in Rules) {
//while (pair.Value.Remove (Caller)) { }
while (pair.Value.Remove (conn)) { }
//while (pair.Value.Remove (Caller)) { Console.WriteLine ("Remove!"); }
//pair.Value.RemoveAll ( delegate (Connection conn) { conn == Caller; } )
if (pair.Value.Count == 0)
toRemove.Add (pair.Key);
//Rules.Remove (pair);
//Rules.Remove<KeyValuePair<MatchRule,List<Connection>>> (pair);
//((ICollection<System.Collections.Generic.KeyValuePair<MatchRule,List<Connection>>>)Rules).Remove<KeyValuePair<MatchRule,List<Connection>>> (pair);
//((ICollection<System.Collections.Generic.KeyValuePair<MatchRule,List<Connection>>>)Rules).Remove (pair);
}
foreach (MatchRule r in toRemove)
Rules.Remove (r);
// TODO: Check the order of signals
// TODO: Atomicity
foreach (string name in namesToDisown)
Names.Remove (name);
foreach (string name in namesToDisown)
NameOwnerChanged (name, ((ServerConnection)conn).UniqueName, String.Empty);
// TODO: Unregister earlier?
conn.Unregister (Path);
}
struct NameRequisition
{
public NameRequisition (Connection connection, bool allowReplacement)
{
this.Connection = connection;
this.AllowReplacement = allowReplacement;
}
public readonly Connection Connection;
public readonly bool AllowReplacement;
}
//SortedList<>
readonly Dictionary<string, Connection> Names = new Dictionary<string, Connection> ();
//readonly SortedList<string,Connection> Names = new SortedList<string,Connection> ();
//readonly SortedDictionary<string,Connection> Names = new SortedDictionary<string,Connection> ();
public RequestNameReply RequestName (string name, NameFlag flags)
{
Console.Error.WriteLine ("RequestName " + name);
string nameError;
if (!BusNameIsValid (name, out nameError))
throw new ArgumentException (String.Format ("Requested name \"{0}\" is not valid: {1}", name, nameError), "name");
if (name.StartsWith (":"))
throw new ArgumentException (String.Format ("Cannot acquire a name starting with ':' such as \"{0}\"", name), "name");
if (name == DBusBusName)
throw new ArgumentException (String.Format ("Connection \"{0}\" is not allowed to own the name \"{1}\" because it is reserved for D-Bus' use only", Caller.UniqueName ?? "(inactive)", name), "name");
// TODO: Policy delegate support
// TODO: NameFlag support
if (flags != NameFlag.None)
Console.Error.WriteLine ("Warning: Ignoring unimplemented NameFlags: " + flags);
Connection c;
if (!Names.TryGetValue (name, out c)) {
Names[name] = Caller;
RaiseNameSignal ("Acquired", name);
NameOwnerChanged (name, String.Empty, Caller.UniqueName);
Message activationMessage;
if (activationMessages.TryGetValue (name, out activationMessage)) {
activationMessages.Remove (name);
Caller.SendReal (activationMessage);
}
return RequestNameReply.PrimaryOwner;
} else if (c == Caller)
return RequestNameReply.AlreadyOwner;
else
return RequestNameReply.Exists;
}
public ReleaseNameReply ReleaseName (string name)
{
string nameError;
if (!BusNameIsValid (name, out nameError))
throw new ArgumentException (String.Format ("Given bus name \"{0}\" is not valid: {1}", name, nameError), "name");
if (name.StartsWith (":"))
throw new ArgumentException (String.Format ("Cannot release a name starting with ':' such as \"{0}\"", name), "name");
if (name == DBusBusName)
throw new ArgumentException (String.Format ("Cannot release the \"{0}\" name because it is owned by the bus", name), "name");
Connection c;
if (!Names.TryGetValue (name, out c))
return ReleaseNameReply.NonExistent;
if (c != Caller)
return ReleaseNameReply.NotOwner;
Names.Remove (name);
// TODO: Does official daemon send NameLost signal here? Do the same.
RaiseNameSignal ("Lost", name);
NameOwnerChanged (name, Caller.UniqueName, String.Empty);
return ReleaseNameReply.Released;
}
int uniqueMajor = 1;
int uniqueMinor = -1;
string CreateUniqueName ()
{
int newMajor = uniqueMajor;
int newMinor = Interlocked.Increment (ref uniqueMinor);
// Major wrapping should probably be made atomic too.
if (newMinor == Int32.MaxValue) {
if (uniqueMajor == Int32.MaxValue)
uniqueMajor = 1;
else
uniqueMajor++;
uniqueMinor = -1;
}
string uniqueName = String.Format (":{0}.{1}", newMajor, newMinor);
// We could check if the unique name already has an owner here for absolute correctness.
Debug.Assert (!NameHasOwner (uniqueName));
return uniqueName;
}
public string Hello ()
{
if (Caller.UniqueName != null)
throw new DBusException ("Failed", "Already handled an Hello message");
string uniqueName = CreateUniqueName ();
Console.Error.WriteLine ("Hello " + uniqueName + "!");
Caller.UniqueName = uniqueName;
Names[uniqueName] = Caller;
// TODO: Verify the order in which these messages are sent.
//NameAcquired (uniqueName);
RaiseNameSignal ("Acquired", uniqueName);
NameOwnerChanged (uniqueName, String.Empty, uniqueName);
return uniqueName;
}
void RaiseNameSignal (string memberSuffix, string name)
{
// Name* signals on org.freedesktop.DBus are connection-specific.
// We handle them here as a special case.
Signal nameSignal = new Signal (Path, DBusInterface, "Name" + memberSuffix);
MessageWriter mw = new MessageWriter ();
mw.Write (name);
nameSignal.message.Body = mw.ToArray ();
nameSignal.message.Signature = Signature.StringSig;
Caller.Send (nameSignal.message);
}
public string[] ListNames ()
{
List<string> names = new List<string> ();
names.Add (DBusBusName);
names.AddRange (Names.Keys);
return names.ToArray ();
}
public string[] ListActivatableNames ()
{
List<string> names = new List<string> ();
names.AddRange (services.Keys);
return names.ToArray ();
}
public bool NameHasOwner (string name)
{
if (name == DBusBusName)
return true;
return Names.ContainsKey (name);
}
public event NameOwnerChangedHandler NameOwnerChanged;
public event NameLostHandler NameLost;
public event NameAcquiredHandler NameAcquired;
public StartReply StartServiceByName (string name, uint flags)
{
if (name == DBusBusName)
return StartReply.AlreadyRunning;
if (Names.ContainsKey (name))
return StartReply.AlreadyRunning;
if (!StartProcessNamed (name))
throw new DBusException ("Spawn.ServiceNotFound", "The name {0} was not provided by any .service files", name);
return StartReply.Success;
}
Dictionary<string, string> activationEnv = new Dictionary<string, string> ();
public void UpdateActivationEnvironment (IDictionary<string, string> environment)
{
foreach (KeyValuePair<string, string> pair in environment) {
if (pair.Key == String.Empty)
continue;
if (pair.Value == String.Empty)
activationEnv.Remove (pair.Key);
else
activationEnv[pair.Key] = pair.Value;
}
}
public string GetNameOwner (string name)
{
if (name == DBusBusName)
return DBusBusName;
Connection c;
if (!Names.TryGetValue (name, out c))
throw new DBusException ("NameHasNoOwner", "Could not get owner of name '{0}': no such name", name);
return ((ServerConnection)c).UniqueName;
}
public uint GetConnectionUnixUser (string name)
{
if (name == DBusBusName)
return (uint)Process.GetCurrentProcess ().Id;
Connection c;
if (!Names.TryGetValue (name, out c))
throw new DBusException ("NameHasNoOwner", "Could not get UID of name '{0}': no such name", name);
if (((ServerConnection)c).UserId == 0)
throw new DBusException ("Failed", "Could not determine UID for '{0}'", name);
return (uint)((ServerConnection)c).UserId;
}
Dictionary<string, Message> activationMessages = new Dictionary<string, Message> ();
internal void HandleMessage (Message msg)
{
if (msg == null)
return;
//List<Connection> recipients = new List<Connection> ();
HashSet<Connection> recipients = new HashSet<Connection> ();
//HashSet<Connection> recipientsAll = new HashSet<Connection> (Connections);
object fieldValue = msg.Header[FieldCode.Destination];
if (fieldValue != null) {
string destination = (string)fieldValue;
Connection destConn;
if (Names.TryGetValue (destination, out destConn))
recipients.Add (destConn);
else if (destination != DBusBusName && !destination.StartsWith (":") && (msg.Header.Flags & HeaderFlag.NoAutoStart) != HeaderFlag.NoAutoStart) {
// Attempt activation
StartProcessNamed (destination);
//Thread.Sleep (5000);
// TODO: Route the message to the newly activated service!
activationMessages[destination] = msg;
//if (Names.TryGetValue (destination, out destConn))
// recipients.Add (destConn);
//else
// Console.Error.WriteLine ("Couldn't route message to activated service");
} else if (destination != DBusBusName) {
// Send an error when there's no hope of getting the requested reply
if (msg.ReplyExpected) {
// Error org.freedesktop.DBus.Error.ServiceUnknown: The name {0} was not provided by any .service files
Message rmsg = MessageHelper.CreateUnknownMethodError (new MethodCall (msg));
if (rmsg != null) {
//Caller.Send (rmsg);
Caller.SendReal (rmsg);
return;
}
}
}
}
HashSet<Connection> recipientsMatchingHeader = new HashSet<Connection> ();
HashSet<ArgMatchTest> a = new HashSet<ArgMatchTest> ();
foreach (KeyValuePair<MatchRule, List<Connection>> pair in Rules) {
if (recipients.IsSupersetOf (pair.Value))
continue;
if (pair.Key.MatchesHeader (msg)) {
a.UnionWith (pair.Key.Args);
recipientsMatchingHeader.UnionWith (pair.Value);
}
}
MatchRule.Test (a, msg);
foreach (KeyValuePair<MatchRule, List<Connection>> pair in Rules) {
if (recipients.IsSupersetOf (pair.Value))
continue;
if (!recipientsMatchingHeader.IsSupersetOf (pair.Value))
continue;
if (a.IsSupersetOf (pair.Key.Args))
recipients.UnionWith (pair.Value);
}
foreach (Connection conn in recipients) {
// TODO: rewrite/don't header fields
//conn.Send (msg);
// TODO: Zero the Serial or not?
//msg.Header.Serial = 0;
((ServerConnection)conn).SendReal (msg);
}
}
//SortedDictionary<MatchRule,int> Rules = new SortedDictionary<MatchRule,int> ();
//Dictionary<MatchRule,int> Rules = new Dictionary<MatchRule,int> ();
Dictionary<MatchRule, List<Connection>> Rules = new Dictionary<MatchRule, List<Connection>> ();
public void AddMatch (string rule)
{
MatchRule r = MatchRule.Parse (rule);
if (r == null)
throw new Exception ("r == null");
if (!Rules.ContainsKey (r))
Rules[r] = new List<Connection> ();
// Each occurrence of a Connection in the list represents one value-unique AddMatch call
Rules[r].Add (Caller);
Console.WriteLine ("Added. Rules count: " + Rules.Count);
}
public void RemoveMatch (string rule)
{
MatchRule r = MatchRule.Parse (rule);
if (r == null)
throw new Exception ("r == null");
if (!Rules.ContainsKey (r))
throw new Exception ();
// We remove precisely one occurrence of the calling connection
Rules[r].Remove (Caller);
if (Rules[r].Count == 0)
Rules.Remove (r);
Console.WriteLine ("Removed. Rules count: " + Rules.Count);
}
public string GetId ()
{
return Caller.Id.ToString ();
}
// Undocumented in spec
public string[] ListQueuedOwners (string name)
{
// ?
if (name == DBusBusName)
return new string[] { DBusBusName };
Connection c;
if (!Names.TryGetValue (name, out c))
throw new DBusException ("NameHasNoOwner", "Could not get owners of name '{0}': no such name", name);
return new string[] { ((ServerConnection)c).UniqueName };
}
// Undocumented in spec
public uint GetConnectionUnixProcessID (string connection_name)
{
Connection c;
if (!Names.TryGetValue (connection_name, out c))
throw new DBusException ("NameHasNoOwner", "Could not get PID of name '{0}': no such name", connection_name);
uint pid;
if (!c.Transport.TryGetPeerPid (out pid))
throw new DBusException ("UnixProcessIdUnknown", "Could not determine PID for '{0}'", connection_name);
return pid;
}
// Undocumented in spec
public byte[] GetConnectionSELinuxSecurityContext (string connection_name)
{
throw new DBusException ("SELinuxSecurityContextUnknown", "Could not determine security context for '{0}'", connection_name);
}
// Undocumented in spec
public void ReloadConfig ()
{
ScanServices ();
}
Dictionary<string, string> services = new Dictionary<string, string> ();
public string svcPath = "/usr/share/dbus-1/services";
public void ScanServices ()
{
services.Clear ();
string[] svcs = Directory.GetFiles (svcPath, "*.service");
foreach (string svc in svcs) {
string fname = System.IO.Path.Combine (svcPath, svc);
using (TextReader r = new StreamReader (fname)) {
string ln;
string cmd = null;
string name = null;
while ((ln = r.ReadLine ()) != null) {
if (ln.StartsWith ("Exec="))
cmd = ln.Remove (0, 5);
else if (ln.StartsWith ("Name="))
name = ln.Remove (0, 5);
}
// TODO: use XdgNet
// TODO: Validate names and trim strings
if (name != null && cmd != null)
services[name] = cmd;
}
}
}
public bool allowActivation = false;
bool StartProcessNamed (string name)
{
Console.Error.WriteLine ("Start " + name);
if (!allowActivation)
return false;
string cmd;
if (!services.TryGetValue (name, out cmd))
return false;
try {
StartProcess (cmd);
} catch (Exception e) {
Console.Error.WriteLine (e);
return false;
}
return true;
}
// Can be "session" or "system"
public string busType = "session";
void StartProcess (string fname)
{
if (!allowActivation)
return;
try {
ProcessStartInfo startInfo = new ProcessStartInfo (fname);
startInfo.UseShellExecute = false;
foreach (KeyValuePair<string, string> pair in activationEnv) {
startInfo.EnvironmentVariables[pair.Key] = pair.Value;
}
startInfo.EnvironmentVariables["DBUS_STARTER_BUS_TYPE"] = busType;
startInfo.EnvironmentVariables["DBUS_" + busType.ToUpper () + "_BUS_ADDRESS"] = server.address;
startInfo.EnvironmentVariables["DBUS_STARTER_ADDRESS"] = server.address;
startInfo.EnvironmentVariables["DBUS_STARTER_BUS_TYPE"] = busType;
Process myProcess = Process.Start (startInfo);
} catch (Exception e) {
Console.Error.WriteLine (e);
}
}
}
class ServerConnection : Connection
{
public Server Server;
public ServerConnection (Transport t)
: base (t)
{
}
bool shouldDump = false;
override internal void HandleMessage (Message msg)
{
if (!isConnected)
return;
if (msg == null) {
Console.Error.WriteLine ("Disconnected!");
isConnected = false;
//Server.Bus.RemoveConnection (this);
//ServerBus sbus = Unregister (new ObjectPath ("/org/freedesktop/DBus")) as ServerBus;
/*
ServerBus sbus = Unregister (new ObjectPath ("/org/freedesktop/DBus")) as ServerBus;
Register (new ObjectPath ("/org/freedesktop/DBus"), sbus);
sbus.RemoveConnection (this);
*/
Server.SBus.RemoveConnection (this);
//Server.ConnectionLost (this);
return;
}
Server.CurrentMessageConnection = this;
Server.CurrentMessage = msg;
try {
if (shouldDump) {
MessageDumper.WriteComment ("Handling:", Console.Out);
MessageDumper.WriteMessage (msg, Console.Out);
}
if (UniqueName != null)
msg.Header[FieldCode.Sender] = UniqueName;
object fieldValue = msg.Header[FieldCode.Destination];
if (fieldValue != null) {
if ((string)fieldValue == ServerBus.DBusBusName) {
// Workaround for our daemon only listening on a single path
if (msg.Header.MessageType == DBus.MessageType.MethodCall)
msg.Header[FieldCode.Path] = ServerBus.Path;
base.HandleMessage (msg);
//return;
}
}
//base.HandleMessage (msg);
Server.SBus.HandleMessage (msg);
} finally {
Server.CurrentMessageConnection = null;
Server.CurrentMessage = null;
}
}
override internal uint Send (Message msg)
{
if (!isConnected)
return 0;
/*
if (msg.Header.MessageType == DBus.MessageType.Signal) {
Signal signal = new Signal (msg);
if (signal.Member == "NameAcquired" || signal.Member == "NameLost") {
string dest = (string)msg.Header[FieldCode.Destination];
if (dest != UniqueName)
return 0;
}
}
*/
if (msg.Header.MessageType != DBus.MessageType.MethodReturn) {
msg.Header[FieldCode.Sender] = ServerBus.DBusBusName;
}
if (UniqueName != null)
msg.Header[FieldCode.Destination] = UniqueName;
if (shouldDump) {
MessageDumper.WriteComment ("Sending:", Console.Out);
MessageDumper.WriteMessage (msg, Console.Out);
}
//return base.Send (msg);
return SendReal (msg);
}
internal uint SendReal (Message msg)
{
if (!isConnected)
return 0;
try {
return base.Send (msg);
} catch {
//} catch (System.IO.IOException) {
isConnected = false;
Server.SBus.RemoveConnection (this);
}
return 0;
}
//ServerBus SBus;
public string UniqueName = null;
public long UserId = 0;
~ServerConnection ()
{
Console.Error.WriteLine ("Good! ~ServerConnection () for {0}", UniqueName ?? "(inactive)");
}
}
internal class BusContext
{
protected Connection connection = null;
public Connection Connection
{
get
{
return connection;
}
}
protected Message message = null;
internal Message CurrentMessage
{
get
{
return message;
}
}
public string SenderName = null;
}
class DBusException : BusException
{
public DBusException (string errorNameSuffix, string format, params object[] args)
: base (ServerBus.DBusInterface + ".Error." + errorNameSuffix, format, args)
{
// Note: This won't log ArgumentExceptions which are used in some places.
if (Protocol.Verbose)
Console.Error.WriteLine (Message);
}
}
}
| |
// <copyright file="Keys.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.Globalization;
using System.Text;
namespace OpenQA.Selenium
{
/// <summary>
/// Representations of keys able to be pressed that are not text keys for sending to the browser.
/// </summary>
public static class Keys
{
/// <summary>
/// Represents the NUL keystroke.
/// </summary>
public static readonly string Null = Convert.ToString(Convert.ToChar(0xE000, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Cancel keystroke.
/// </summary>
public static readonly string Cancel = Convert.ToString(Convert.ToChar(0xE001, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Help keystroke.
/// </summary>
public static readonly string Help = Convert.ToString(Convert.ToChar(0xE002, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Backspace key.
/// </summary>
public static readonly string Backspace = Convert.ToString(Convert.ToChar(0xE003, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Tab key.
/// </summary>
public static readonly string Tab = Convert.ToString(Convert.ToChar(0xE004, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Clear keystroke.
/// </summary>
public static readonly string Clear = Convert.ToString(Convert.ToChar(0xE005, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Return key.
/// </summary>
public static readonly string Return = Convert.ToString(Convert.ToChar(0xE006, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Enter key.
/// </summary>
public static readonly string Enter = Convert.ToString(Convert.ToChar(0xE007, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Shift key.
/// </summary>
public static readonly string Shift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Shift key.
/// </summary>
public static readonly string LeftShift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Control key.
/// </summary>
public static readonly string Control = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Control key.
/// </summary>
public static readonly string LeftControl = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Alt key.
/// </summary>
public static readonly string Alt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Alt key.
/// </summary>
public static readonly string LeftAlt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Pause key.
/// </summary>
public static readonly string Pause = Convert.ToString(Convert.ToChar(0xE00B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Escape key.
/// </summary>
public static readonly string Escape = Convert.ToString(Convert.ToChar(0xE00C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Spacebar key.
/// </summary>
public static readonly string Space = Convert.ToString(Convert.ToChar(0xE00D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Page Up key.
/// </summary>
public static readonly string PageUp = Convert.ToString(Convert.ToChar(0xE00E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Page Down key.
/// </summary>
public static readonly string PageDown = Convert.ToString(Convert.ToChar(0xE00F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the End key.
/// </summary>
public static readonly string End = Convert.ToString(Convert.ToChar(0xE010, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Home key.
/// </summary>
public static readonly string Home = Convert.ToString(Convert.ToChar(0xE011, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the left arrow key.
/// </summary>
public static readonly string Left = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the left arrow key.
/// </summary>
public static readonly string ArrowLeft = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the up arrow key.
/// </summary>
public static readonly string Up = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the up arrow key.
/// </summary>
public static readonly string ArrowUp = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the right arrow key.
/// </summary>
public static readonly string Right = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the right arrow key.
/// </summary>
public static readonly string ArrowRight = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Left arrow key.
/// </summary>
public static readonly string Down = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Left arrow key.
/// </summary>
public static readonly string ArrowDown = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Insert key.
/// </summary>
public static readonly string Insert = Convert.ToString(Convert.ToChar(0xE016, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Delete key.
/// </summary>
public static readonly string Delete = Convert.ToString(Convert.ToChar(0xE017, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the semi-colon key.
/// </summary>
public static readonly string Semicolon = Convert.ToString(Convert.ToChar(0xE018, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the equal sign key.
/// </summary>
public static readonly string Equal = Convert.ToString(Convert.ToChar(0xE019, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
// Number pad keys
/// <summary>
/// Represents the number pad 0 key.
/// </summary>
public static readonly string NumberPad0 = Convert.ToString(Convert.ToChar(0xE01A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 1 key.
/// </summary>
public static readonly string NumberPad1 = Convert.ToString(Convert.ToChar(0xE01B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 2 key.
/// </summary>
public static readonly string NumberPad2 = Convert.ToString(Convert.ToChar(0xE01C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 3 key.
/// </summary>
public static readonly string NumberPad3 = Convert.ToString(Convert.ToChar(0xE01D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 4 key.
/// </summary>
public static readonly string NumberPad4 = Convert.ToString(Convert.ToChar(0xE01E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 5 key.
/// </summary>
public static readonly string NumberPad5 = Convert.ToString(Convert.ToChar(0xE01F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 6 key.
/// </summary>
public static readonly string NumberPad6 = Convert.ToString(Convert.ToChar(0xE020, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 7 key.
/// </summary>
public static readonly string NumberPad7 = Convert.ToString(Convert.ToChar(0xE021, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 8 key.
/// </summary>
public static readonly string NumberPad8 = Convert.ToString(Convert.ToChar(0xE022, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 9 key.
/// </summary>
public static readonly string NumberPad9 = Convert.ToString(Convert.ToChar(0xE023, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad multiplication key.
/// </summary>
public static readonly string Multiply = Convert.ToString(Convert.ToChar(0xE024, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad addition key.
/// </summary>
public static readonly string Add = Convert.ToString(Convert.ToChar(0xE025, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad thousands separator key.
/// </summary>
public static readonly string Separator = Convert.ToString(Convert.ToChar(0xE026, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad subtraction key.
/// </summary>
public static readonly string Subtract = Convert.ToString(Convert.ToChar(0xE027, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad decimal separator key.
/// </summary>
public static readonly string Decimal = Convert.ToString(Convert.ToChar(0xE028, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad division key.
/// </summary>
public static readonly string Divide = Convert.ToString(Convert.ToChar(0xE029, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
// Function keys
/// <summary>
/// Represents the function key F1.
/// </summary>
public static readonly string F1 = Convert.ToString(Convert.ToChar(0xE031, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F2.
/// </summary>
public static readonly string F2 = Convert.ToString(Convert.ToChar(0xE032, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F3.
/// </summary>
public static readonly string F3 = Convert.ToString(Convert.ToChar(0xE033, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F4.
/// </summary>
public static readonly string F4 = Convert.ToString(Convert.ToChar(0xE034, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F5.
/// </summary>
public static readonly string F5 = Convert.ToString(Convert.ToChar(0xE035, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F6.
/// </summary>
public static readonly string F6 = Convert.ToString(Convert.ToChar(0xE036, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F7.
/// </summary>
public static readonly string F7 = Convert.ToString(Convert.ToChar(0xE037, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F8.
/// </summary>
public static readonly string F8 = Convert.ToString(Convert.ToChar(0xE038, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F9.
/// </summary>
public static readonly string F9 = Convert.ToString(Convert.ToChar(0xE039, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F10.
/// </summary>
public static readonly string F10 = Convert.ToString(Convert.ToChar(0xE03A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F11.
/// </summary>
public static readonly string F11 = Convert.ToString(Convert.ToChar(0xE03B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F12.
/// </summary>
public static readonly string F12 = Convert.ToString(Convert.ToChar(0xE03C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key META.
/// </summary>
public static readonly string Meta = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key COMMAND.
/// </summary>
public static readonly string Command = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising 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.Runtime.InteropServices;
using System.IO;
namespace WOSI.Utilities
{
/// <summary>
/// Summary description for SoundUtilities.
/// </summary>
public sealed class SoundUtils
{
private const int MMSYSERR_NOERROR = 0;
private const int MAXPNAMELEN = 32;
private const int MIXER_LONG_NAME_CHARS = 64;
private const int MIXER_SHORT_NAME_CHARS = 16;
private const int MIXER_GETLINEINFOF_COMPONENTTYPE = 0x3;
private const int MIXER_GETCONTROLDETAILSF_VALUE = 0x0;
private const int MIXER_GETLINECONTROLSF_ONEBYTYPE = 0x2;
private const int MIXER_SETCONTROLDETAILSF_VALUE = 0x0;
private const int MIXERLINE_COMPONENTTYPE_DST_FIRST = 0x0;
private const int MIXERLINE_COMPONENTTYPE_SRC_FIRST = 0x1000;
private const int MIXERLINE_COMPONENTTYPE_DST_SPEAKERS = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 4);
private const int MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 3);
private const int MIXERLINE_COMPONENTTYPE_SRC_LINE = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 2);
private const int MIXERCONTROL_CT_CLASS_FADER = 0x50000000;
private const int MIXERCONTROL_CT_UNITS_UNSIGNED = 0x30000;
private const int MIXERCONTROL_CT_CLASS_SWITCH = 0x20000000;
private const int MIXERCONTROL_CT_SC_SWITCH_BOOLEAN = 0x0;
private const int MIXERCONTROL_CT_UNITS_BOOLEAN = 0x10000;
private const int MIXERCONTROL_CONTROLTYPE_FADER = (MIXERCONTROL_CT_CLASS_FADER | MIXERCONTROL_CT_UNITS_UNSIGNED);
private const int MIXERCONTROL_CONTROLTYPE_VOLUME = (MIXERCONTROL_CONTROLTYPE_FADER + 1);
private const int MIXERCONTROL_CONTROLTYPE_BOOLEAN = (MIXERCONTROL_CT_CLASS_SWITCH | MIXERCONTROL_CT_SC_SWITCH_BOOLEAN | MIXERCONTROL_CT_UNITS_BOOLEAN);
private const int MIXERCONTROL_CONTROLTYPE_MUTE = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 2);
private struct MIXERCAPS
{
public int wMid;
public int wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAXPNAMELEN)]
public string szPname;
public int fdwSupport;
public int cDestinations;
}
private struct MIXERCONTROL
{
public int cbStruct;
public int dwControlID;
public int dwControlType;
public int fdwControl;
public int cMultipleItems;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MIXER_SHORT_NAME_CHARS)]
public string szShortName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MIXER_LONG_NAME_CHARS)]
public string szName;
public int lMinimum;
public int lMaximum;
[MarshalAs(UnmanagedType.U4, SizeConst = 10)]
public int reserved;
}
private struct MIXERCONTROLDETAILS
{
public int cbStruct;
public int dwControlID;
public int cChannels;
public int item;
public int cbDetails;
public IntPtr paDetails;
}
private struct MIXERCONTROLDETAILS_UNSIGNED
{
public int dwValue;
}
private struct MIXERCONTROLDETAILS_BOOLEAN
{
public int dwValue;
}
private struct MIXERLINE
{
public int cbStruct;
public int dwDestination;
public int dwSource;
public int dwLineID;
public int fdwLine;
public int dwUser;
public int dwComponentType;
public int cChannels;
public int cConnections;
public int cControls;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MIXER_SHORT_NAME_CHARS)]
public string szShortName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MIXER_LONG_NAME_CHARS)]
public string szName;
public int dwType;
public int dwDeviceID;
public int wMid;
public int wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAXPNAMELEN)]
public string szPname;
}
private struct MIXERLINECONTROLS
{
public int cbStruct;
public int dwLineID;
public int dwControl;
public int cControls;
public int cbmxctrl;
public IntPtr pamxctrl;
}
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerClose(int hmx);
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerGetControlDetailsA(int hmxobj, ref MIXERCONTROLDETAILS pmxcd, int fdwDetails);
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerGetDevCapsA(int uMxId, MIXERCAPS pmxcaps, int cbmxcaps);
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerGetID(int hmxobj, int pumxID, int fdwId);
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerGetLineControlsA(int hmxobj, ref MIXERLINECONTROLS pmxlc, int fdwControls);
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerGetLineInfoA(int hmxobj, ref MIXERLINE pmxl, int fdwInfo);
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerGetNumDevs();
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerMessage(int hmx, int uMsg, int dwParam1, int dwParam2);
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerOpen(out int phmx, int uMxId, int dwCallback, int dwInstance, int fdwOpen);
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
private static extern int mixerSetControlDetails(int hmxobj, ref MIXERCONTROLDETAILS pmxcd, int fdwDetails);
[DllImport("winmm.dll", EntryPoint = "sndPlaySoundA")]
private static extern int sndPlaySound(string lpszSoundName, int uFlags);
private const int SND_ASYNC = 0x1;
private const int SND_LOOP = 0x8;
private SoundUtils()
{
}
public static void PlaySound(string filename, bool loop)
{
if (File.Exists(filename))
{
if (loop)
sndPlaySound(filename, SND_ASYNC | SND_LOOP);
else
sndPlaySound(filename, SND_ASYNC);
}
}
public static void StopSound()
{
sndPlaySound(null, SND_ASYNC);
}
public static void Mute(bool mute)
{
// Check if this is vista or XP
if (System.Environment.OSVersion.Version.Major >= 6)
{
EndpointVolume epVol = new EndpointVolume();
epVol.Mute = mute;
epVol.Dispose();
}
else
{
int mixerID = 0;
if (mixerOpen(out mixerID, 0, 0, 0, 0) == MMSYSERR_NOERROR)
{
MIXERLINE line = new MIXERLINE();
line.cbStruct = Marshal.SizeOf(line);
line.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS;
if (mixerGetLineInfoA(mixerID, ref line, MIXER_GETLINEINFOF_COMPONENTTYPE) == MMSYSERR_NOERROR)
{
int sizeofMIXERCONTROL = 152;
MIXERCONTROL mixerControl = new MIXERCONTROL();
MIXERLINECONTROLS lineControl = new MIXERLINECONTROLS();
lineControl.pamxctrl = Marshal.AllocCoTaskMem(sizeofMIXERCONTROL);
lineControl.cbStruct = Marshal.SizeOf(lineControl);
lineControl.dwLineID = line.dwLineID;
lineControl.dwControl = MIXERCONTROL_CONTROLTYPE_MUTE;
lineControl.cControls = 1;
lineControl.cbmxctrl = sizeofMIXERCONTROL;
mixerControl.cbStruct = sizeofMIXERCONTROL;
if (mixerGetLineControlsA(mixerID, ref lineControl, MIXER_GETLINECONTROLSF_ONEBYTYPE) == MMSYSERR_NOERROR)
{
mixerControl = (MIXERCONTROL)Marshal.PtrToStructure(lineControl.pamxctrl, typeof(MIXERCONTROL));
MIXERCONTROLDETAILS controlDetails = new MIXERCONTROLDETAILS();
MIXERCONTROLDETAILS_BOOLEAN muteValue = new MIXERCONTROLDETAILS_BOOLEAN();
controlDetails.item = 0;
controlDetails.dwControlID = mixerControl.dwControlID;
controlDetails.cbStruct = Marshal.SizeOf(controlDetails);
controlDetails.cbDetails = Marshal.SizeOf(muteValue);
controlDetails.cChannels = 1;
muteValue.dwValue = Convert.ToInt32(mute);
controlDetails.paDetails = Marshal.AllocCoTaskMem(Marshal.SizeOf(muteValue));
Marshal.StructureToPtr(muteValue, controlDetails.paDetails, false);
int rc = mixerSetControlDetails(mixerID, ref controlDetails, MIXER_SETCONTROLDETAILSF_VALUE);
Marshal.FreeCoTaskMem(controlDetails.paDetails);
Marshal.FreeCoTaskMem(lineControl.pamxctrl);
}
}
}
}
}
}
public class EndpointVolume
{
#region Interface to COM objects
const int DEVICE_STATE_ACTIVE = 0x00000001;
const int DEVICE_STATE_DISABLE = 0x00000002;
const int DEVICE_STATE_NOTPRESENT = 0x00000004;
const int DEVICE_STATE_UNPLUGGED = 0x00000008;
const int DEVICE_STATEMASK_ALL = 0x0000000f;
[DllImport("ole32.Dll")]
static public extern uint CoCreateInstance(ref Guid clsid,
[MarshalAs(UnmanagedType.IUnknown)] object inner,
uint context,
ref Guid uuid,
[MarshalAs(UnmanagedType.IUnknown)] out object rReturnedComObject);
// C Header file : Include Mmdeviceapi.h (Windows Vista SDK)
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioEndpointVolume
{
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RegisterControlChangeNotify(/* [in] */__in IAudioEndpointVolumeCallback *pNotify) = 0;
//int RegisterControlChangeNotify(IntPtr pNotify);
int RegisterControlChangeNotify(DelegateMixerChange pNotify);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE UnregisterControlChangeNotify(/* [in] */ __in IAudioEndpointVolumeCallback *pNotify) = 0;
//int UnregisterControlChangeNotify(IntPtr pNotify);
int UnregisterControlChangeNotify(DelegateMixerChange pNotify);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetChannelCount(/* [out] */ __out UINT *pnChannelCount) = 0;
int GetChannelCount(ref uint pnChannelCount);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetMasterVolumeLevel( /* [in] */ __in float fLevelDB,/* [unique][in] */ LPCGUID pguidEventContext) = 0;
int SetMasterVolumeLevel(float fLevelDB, Guid pguidEventContext);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetMasterVolumeLevelScalar( /* [in] */ __in float fLevel,/* [unique][in] */ LPCGUID pguidEventContext) = 0;
int SetMasterVolumeLevelScalar(float fLevel, Guid pguidEventContext);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetMasterVolumeLevel(/* [out] */ __out float *pfLevelDB) = 0;
int GetMasterVolumeLevel(ref float pfLevelDB);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetMasterVolumeLevelScalar( /* [out] */ __out float *pfLevel) = 0;
int GetMasterVolumeLevelScalar(ref float pfLevel);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetChannelVolumeLevel(/* [in] */__in UINT nChannel,float fLevelDB,/* [unique][in] */ LPCGUID pguidEventContext) = 0;
int SetChannelVolumeLevel(uint nChannel, float fLevelDB, Guid pguidEventContext);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetChannelVolumeLevelScalar(/* [in] */ __in UINT nChannel,float fLevel,/* [unique][in] */ LPCGUID pguidEventContext) = 0;
int SetChannelVolumeLevelScalar(uint nChannel, float fLevel, Guid pguidEventContext);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetChannelVolumeLevel(/* [in] */ __in UINT nChannel,/* [out] */__out float *pfLevelDB) = 0;
int GetChannelVolumeLevel(uint nChannel, ref float pfLevelDB);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetChannelVolumeLevelScalar(/* [in] */__in UINT nChannel,/* [out] */__out float *pfLevel) = 0;
int GetChannelVolumeLevelScalar(uint nChannel, ref float pfLevel);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetMute( /* [in] *__in BOOL bMute, /* [unique][in] */ LPCGUID pguidEventContext) = 0;
int SetMute(int bMute, Guid pguidEventContext);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetMute( /* [out] */ __out BOOL *pbMute) = 0;
int GetMute(ref bool pbMute);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetVolumeStepInfo( /* [out] */ __out UINT *pnStep,/* [out] */__out UINT *pnStepCount) = 0;
int GetVolumeStepInfo(ref uint pnStep, ref uint pnStepCount);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE VolumeStepUp( /* [unique][in] */ LPCGUID pguidEventContext) = 0;
int VolumeStepUp(Guid pguidEventContext);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE VolumeStepDown(/* [unique][in] */ LPCGUID pguidEventContext) = 0;
int VolumeStepDown(Guid pguidEventContext);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE QueryHardwareSupport(/* [out] */ __out DWORD *pdwHardwareSupportMask) = 0;
int QueryHardwareSupport(ref uint pdwHardwareSupportMask);
//virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetVolumeRange( /* [out] */ __out float *pflVolumeMindB,/* [out] */ __out float *pflVolumeMaxdB,/* [out] */ __out float *pflVolumeIncrementdB) = 0;
int GetVolumeRange(ref float pflVolumeMindB, ref float pflVolumeMaxdB, ref float pflVolumeIncrementdB);
}
[Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDeviceCollection
{
//HRESULT GetCount([out, annotation("__out")] UINT* pcDevices);
int GetCount(ref uint pcDevices);
//HRESULT Item([in, annotation("__in")]UINT nDevice, [out, annotation("__out")] IMMDevice** ppDevice);
int Item(uint nDevice, ref IntPtr ppDevice);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDevice
{
//HRESULT Activate([in, annotation("__in")] REFIID iid, [in, annotation("__in")] DWORD dwClsCtx, [in,unique, annotation("__in_opt")] PROPVARIANT* pActivationParams, [out,iid_is(iid), annotation("__out")] void** ppInterface);
int Activate(ref Guid iid, uint dwClsCtx, IntPtr pActivationParams, ref IntPtr ppInterface);
//HRESULT OpenPropertyStore([in, annotation("__in")] DWORD stgmAccess, [out, annotation("__out")] IPropertyStore** ppProperties);
int OpenPropertyStore(int stgmAccess, ref IntPtr ppProperties);
//HRESULT GetId([out,annotation("__deref_out")] LPWSTR* ppstrId);
int GetId(ref string ppstrId);
//HRESULT GetState([out, annotation("__out")] DWORD* pdwState);
int GetState(ref int pdwState);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"),
//[Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDeviceEnumerator
{
//HRESULT EnumAudioEndpoints([in, annotation("__in")] EDataFlow dataFlow, [in, annotation("__in")] DWORD dwStateMask, [out, annotation("__out")] IMMDeviceCollection** ppDevices);
int EnumAudioEndpoints(EDataFlow dataFlow, int dwStateMask, ref IntPtr ppDevices);
//HRESULT GetDefaultAudioEndpoint([in, annotation("__in")] EDataFlow dataFlow, [in, annotation("__in")] ERole role, [out, annotation("__out")] IMMDevice** ppEndpoint);
int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, ref IntPtr ppEndpoint);
//HRESULT GetDevice([, annotation("__in")]LPCWSTR pwstrId, [out, annotation("__out")] IMMDevice** ppDevice);
int GetDevice(string pwstrId, ref IntPtr ppDevice);
//HRESULT RegisterEndpointNotificationCallback([in, annotation("__in")] IMMNotificationClient* pClient);
int RegisterEndpointNotificationCallback(IntPtr pClient);
//HRESULT UnregisterEndpointNotificationCallback([in, annotation("__in")] IMMNotificationClient* pClient);
int UnregisterEndpointNotificationCallback(IntPtr pClient);
}
[Flags]
enum CLSCTX : uint
{
CLSCTX_INPROC_SERVER = 0x1,
CLSCTX_INPROC_HANDLER = 0x2,
CLSCTX_LOCAL_SERVER = 0x4,
CLSCTX_INPROC_SERVER16 = 0x8,
CLSCTX_REMOTE_SERVER = 0x10,
CLSCTX_INPROC_HANDLER16 = 0x20,
CLSCTX_RESERVED1 = 0x40,
CLSCTX_RESERVED2 = 0x80,
CLSCTX_RESERVED3 = 0x100,
CLSCTX_RESERVED4 = 0x200,
CLSCTX_NO_CODE_DOWNLOAD = 0x400,
CLSCTX_RESERVED5 = 0x800,
CLSCTX_NO_CUSTOM_MARSHAL = 0x1000,
CLSCTX_ENABLE_CODE_DOWNLOAD = 0x2000,
CLSCTX_NO_FAILURE_LOG = 0x4000,
CLSCTX_DISABLE_AAA = 0x8000,
CLSCTX_ENABLE_AAA = 0x10000,
CLSCTX_FROM_DEFAULT_CONTEXT = 0x20000,
CLSCTX_INPROC = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER,
CLSCTX_SERVER = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER,
CLSCTX_ALL = CLSCTX_SERVER | CLSCTX_INPROC_HANDLER
}
public enum EDataFlow
{
eRender,
eCapture,
eAll,
EDataFlow_enum_count
}
public enum ERole
{
eConsole,
eMultimedia,
eCommunications,
ERole_enum_count
}
#endregion
// Private internal var
object oEnumerator = null;
IMMDeviceEnumerator iMde = null;
object oDevice = null;
IMMDevice imd = null;
object oEndPoint = null;
IAudioEndpointVolume iAudioEndpoint = null;
// TODO
// Problem #1 : I can't handle a volume changed event by other applications
// (example while using the program SndVol.exe)
public delegate void DelegateMixerChange();
//public DelegateMixerChange delMixerChange = null;
public delegate void MixerChangedEventHandler();
//public event MixerChangedEventHandler MixerChanged;
#region Class Constructor and Dispose public methods
/// <summary>
/// Constructor
/// </summary>
public EndpointVolume()
{
const uint CLSCTX_INPROC_SERVER = 1;
Guid clsid = new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E");
Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
oEnumerator = null;
uint hResult = CoCreateInstance(ref clsid, null, CLSCTX_INPROC_SERVER, ref IID_IUnknown, out oEnumerator);
if (hResult != 0 || oEnumerator == null)
{
throw new Exception("CoCreateInstance() pInvoke failed");
}
iMde = oEnumerator as IMMDeviceEnumerator;
if (iMde == null)
{
throw new Exception("COM cast failed to IMMDeviceEnumerator");
}
IntPtr pDevice = IntPtr.Zero;
int retVal = iMde.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eConsole, ref pDevice);
if (retVal != 0)
{
throw new Exception("IMMDeviceEnumerator.GetDefaultAudioEndpoint()");
}
int dwStateMask = DEVICE_STATE_ACTIVE | DEVICE_STATE_NOTPRESENT | DEVICE_STATE_UNPLUGGED;
IntPtr pCollection = IntPtr.Zero;
retVal = iMde.EnumAudioEndpoints(EDataFlow.eRender, dwStateMask, ref pCollection);
if (retVal != 0)
{
throw new Exception("IMMDeviceEnumerator.EnumAudioEndpoints()");
}
oDevice = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pDevice);
imd = oDevice as IMMDevice;
if (imd == null)
{
throw new Exception("COM cast failed to IMMDevice");
}
Guid iid = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A");
uint dwClsCtx = (uint)CLSCTX.CLSCTX_ALL;
IntPtr pActivationParams = IntPtr.Zero;
IntPtr pEndPoint = IntPtr.Zero;
retVal = imd.Activate(ref iid, dwClsCtx, pActivationParams, ref pEndPoint);
if (retVal != 0)
{
throw new Exception("IMMDevice.Activate()");
}
oEndPoint = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pEndPoint);
iAudioEndpoint = oEndPoint as IAudioEndpointVolume;
if (iAudioEndpoint == null)
{
throw new Exception("COM cast failed to IAudioEndpointVolume");
}
/*
delMixerChange = new DelegateMixerChange(MixerChange);
retVal = iAudioEndpoint.RegisterControlChangeNotify(delMixerChange);
if (retVal != 0)
{
throw new Exception("iAudioEndpoint.RegisterControlChangeNotify(delMixerChange)");
}
*/
}
/// <summary>
/// Call this method to release all com objetcs
/// </summary>
public virtual void Dispose()
{
/*
if (delMixerChange != null && iAudioEndpoint != null)
{
iAudioEndpoint.UnregisterControlChangeNotify(delMixerChange);
}
*/
if (iAudioEndpoint != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(iAudioEndpoint);
iAudioEndpoint = null;
}
if (oEndPoint != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(oEndPoint);
oEndPoint = null;
}
if (imd != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(imd);
imd = null;
}
if (oDevice != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(oDevice);
oDevice = null;
}
//System.Runtime.InteropServices.Marshal.ReleaseComObject(pCollection);
if (iMde != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(iMde);
iMde = null;
}
if (oEnumerator != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(oEnumerator);
oEnumerator = null;
}
}
#endregion
#region Private internal functions
private void MixerChange()
{
/*
if (MixerChanged != null)
// Notify (raise) event
MixerChanged();
*/
}
#endregion
#region Public properties
/// <summary>
/// Get/set the master mute. WARNING : The set mute do NOT work!
/// </summary>
public bool Mute
{
get
{
bool mute = false;
int retVal = iAudioEndpoint.GetMute(ref mute);
if (retVal != 0)
{
throw new Exception("IAudioEndpointVolume.GetMute() failed!");
}
return mute;
}
set
{
//nullGuid = new Guid("{00000000-0000-0000-0000-000000000000}"); // null
// {dddddddd-dddd-dddd-dddd-dddddddddddd}
Guid nullGuid = Guid.Empty;
bool mute = value;
// TODO
// Problem #2 : This function always terminate with an internal error!
int retVal = iAudioEndpoint.SetMute(Convert.ToInt32(mute), nullGuid);
if (retVal != 0)
{
throw new Exception("IAudioEndpointVolume.SetMute() failed!");
}
}
}
/// <summary>
/// Get/set the master volume level. Valid range is from 0.00F (0%) to 1.00F (100%).
/// </summary>
public float MasterVolume
{
get
{
float level = 0.0F;
int retVal = iAudioEndpoint.GetMasterVolumeLevelScalar(ref level);
if (retVal != 0)
{
throw new Exception("IAudioEndpointVolume.GetMasterVolumeLevelScalar()");
}
return level;
}
set
{
float level = value;
Guid nullGuid;
//nullGuid = new Guid("{00000000-0000-0000-0000-000000000000}"); // null
// {dddddddd-dddd-dddd-dddd-dddddddddddd}
nullGuid = Guid.Empty;
int retVal = iAudioEndpoint.SetMasterVolumeLevelScalar(level, nullGuid);
if (retVal != 0)
{
throw new Exception("IAudioEndpointVolume.SetMasterVolumeLevelScalar()");
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Increase the master volume
/// </summary>
public void VolumeUp()
{
Guid nullGuid;
//nullGuid = new Guid("{00000000-0000-0000-0000-000000000000}"); // null
// {dddddddd-dddd-dddd-dddd-dddddddddddd}
nullGuid = Guid.Empty;
int retVal = iAudioEndpoint.VolumeStepUp(nullGuid);
if (retVal != 0)
{
throw new Exception("IAudioEndpointVolume.SetMute()");
}
}
/// <summary>
/// Decrease the master volume
/// </summary>
public void VolumeDown()
{
Guid nullGuid;
//nullGuid = new Guid("{00000000-0000-0000-0000-000000000000}"); // null
// {dddddddd-dddd-dddd-dddd-dddddddddddd}
nullGuid = Guid.Empty;
int retVal = iAudioEndpoint.VolumeStepDown(nullGuid);
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function EditorGui::buildMenus(%this)
{
if(isObject(%this.menuBar))
return;
//set up %cmdctrl variable so that it matches OS standards
if( $platform $= "macos" )
{
%cmdCtrl = "Cmd";
%menuCmdCtrl = "Cmd";
%quitShortcut = "Cmd Q";
%redoShortcut = "Cmd-Shift Z";
}
else
{
%cmdCtrl = "Ctrl";
%menuCmdCtrl = "Alt";
%quitShortcut = "Alt F4";
%redoShortcut = "Ctrl Y";
}
// Sub menus (temporary, until MenuBuilder gets updated)
// The speed increments located here are overwritten in EditorCameraSpeedMenu::setupDefaultState.
// The new min/max for the editor camera speed range can be set in each level's levelInfo object.
if(!isObject(EditorCameraSpeedOptions))
{
%this.cameraSpeedMenu = new PopupMenu(EditorCameraSpeedOptions)
{
superClass = "MenuBuilder";
class = "EditorCameraSpeedMenu";
item[0] = "Slowest" TAB %cmdCtrl @ "-Shift 1" TAB "5";
item[1] = "Slow" TAB %cmdCtrl @ "-Shift 2" TAB "35";
item[2] = "Slower" TAB %cmdCtrl @ "-Shift 3" TAB "70";
item[3] = "Normal" TAB %cmdCtrl @ "-Shift 4" TAB "100";
item[4] = "Faster" TAB %cmdCtrl @ "-Shift 5" TAB "130";
item[5] = "Fast" TAB %cmdCtrl @ "-Shift 6" TAB "165";
item[6] = "Fastest" TAB %cmdCtrl @ "-Shift 7" TAB "200";
};
}
if(!isObject(EditorFreeCameraTypeOptions))
{
%this.freeCameraTypeMenu = new PopupMenu(EditorFreeCameraTypeOptions)
{
superClass = "MenuBuilder";
class = "EditorFreeCameraTypeMenu";
item[0] = "Standard" TAB "Ctrl 1" TAB "EditorGuiStatusBar.setCamera(\"Standard Camera\");";
item[1] = "Orbit Camera" TAB "Ctrl 2" TAB "EditorGuiStatusBar.setCamera(\"Orbit Camera\");";
Item[2] = "-";
item[3] = "Smoothed" TAB "" TAB "EditorGuiStatusBar.setCamera(\"Smooth Camera\");";
item[4] = "Smoothed Rotate" TAB "" TAB "EditorGuiStatusBar.setCamera(\"Smooth Rot Camera\");";
};
}
if(!isObject(EditorPlayerCameraTypeOptions))
{
%this.playerCameraTypeMenu = new PopupMenu(EditorPlayerCameraTypeOptions)
{
superClass = "MenuBuilder";
class = "EditorPlayerCameraTypeMenu";
Item[0] = "First Person" TAB "" TAB "EditorGuiStatusBar.setCamera(\"1st Person Camera\");";
Item[1] = "Third Person" TAB "" TAB "EditorGuiStatusBar.setCamera(\"3rd Person Camera\");";
};
}
if(!isObject(EditorCameraBookmarks))
{
%this.cameraBookmarksMenu = new PopupMenu(EditorCameraBookmarks)
{
superClass = "MenuBuilder";
class = "EditorCameraBookmarksMenu";
//item[0] = "None";
};
}
%this.viewTypeMenu = new PopupMenu()
{
superClass = "MenuBuilder";
item[ 0 ] = "Top" TAB "Alt 2" TAB "EditorGuiStatusBar.setCamera(\"Top View\");";
item[ 1 ] = "Bottom" TAB "Alt 5" TAB "EditorGuiStatusBar.setCamera(\"Bottom View\");";
item[ 2 ] = "Front" TAB "Alt 3" TAB "EditorGuiStatusBar.setCamera(\"Front View\");";
item[ 3 ] = "Back" TAB "Alt 6" TAB "EditorGuiStatusBar.setCamera(\"Back View\");";
item[ 4 ] = "Left" TAB "Alt 4" TAB "EditorGuiStatusBar.setCamera(\"Left View\");";
item[ 5 ] = "Right" TAB "Alt 7" TAB "EditorGuiStatusBar.setCamera(\"Right View\");";
item[ 6 ] = "Perspective" TAB "Alt 1" TAB "EditorGuiStatusBar.setCamera(\"Standard Camera\");";
item[ 7 ] = "Isometric" TAB "Alt 8" TAB "EditorGuiStatusBar.setCamera(\"Isometric View\");";
};
// Menu bar
%this.menuBar = new GuiMenuBar(WorldEditorMenubar)
{
dynamicItemInsertPos = 3;
extent = "1024 20";
minExtent = "320 20";
horizSizing = "width";
profile = "GuiMenuBarProfile";
};
// File Menu
%fileMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorFileMenu";
barTitle = "File";
};
%fileMenu.appendItem("New Level" TAB "" TAB "schedule( 1, 0, \"EditorNewLevel\" );");
%fileMenu.appendItem("Open Level..." TAB %cmdCtrl SPC "O" TAB "schedule( 1, 0, \"EditorOpenMission\" );");
%fileMenu.appendItem("Save Level" TAB %cmdCtrl SPC "S" TAB "EditorSaveMissionMenu();");
%fileMenu.appendItem("Save Level As..." TAB "" TAB "EditorSaveMissionAs();");
%fileMenu.appendItem("-");
if( $platform $= "windows" )
{
%fileMenu.appendItem( "Open Project in Torsion" TAB "" TAB "EditorOpenTorsionProject();" );
%fileMenu.appendItem( "Open Level File in Torsion" TAB "" TAB "EditorOpenFileInTorsion();" );
%fileMenu.appendItem( "-" );
}
%fileMenu.appendItem("Create Blank Terrain" TAB "" TAB "Canvas.pushDialog( CreateNewTerrainGui );");
%fileMenu.appendItem("Import Terrain Heightmap" TAB "" TAB "Canvas.pushDialog( TerrainImportGui );");
%fileMenu.appendItem("Export Terrain Heightmap" TAB "" TAB "Canvas.pushDialog( TerrainExportGui );");
%fileMenu.appendItem("-");
%fileMenu.appendItem("Export To COLLADA..." TAB "" TAB "EditorExportToCollada();");
//item[5] = "Import Terraform Data..." TAB "" TAB "Heightfield::import();";
//item[6] = "Import Texture Data..." TAB "" TAB "Texture::import();";
//item[7] = "-";
//item[8] = "Export Terraform Data..." TAB "" TAB "Heightfield::saveBitmap(\"\");";
%fileMenu.appendItem( "-" );
%fileMenu.appendItem( "Add FMOD Designer Audio..." TAB "" TAB "AddFMODProjectDlg.show();" );
%fileMenu.appendItem("-");
%fileMenu.appendItem("Play Level" TAB "F11" TAB "Editor.close(\"PlayGui\");");
%fileMenu.appendItem("Exit Level" TAB "" TAB "EditorExitMission();");
%fileMenu.appendItem("Quit" TAB %quitShortcut TAB "EditorQuitGame();");
%this.menuBar.insert(%fileMenu);
// Edit Menu
%editMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorEditMenu";
internalName = "EditMenu";
barTitle = "Edit";
item[0] = "Undo" TAB %cmdCtrl SPC "Z" TAB "Editor.getUndoManager().undo();";
item[1] = "Redo" TAB %redoShortcut TAB "Editor.getUndoManager().redo();";
item[2] = "-";
item[3] = "Cut" TAB %cmdCtrl SPC "X" TAB "EditorMenuEditCut();";
item[4] = "Copy" TAB %cmdCtrl SPC "C" TAB "EditorMenuEditCopy();";
item[5] = "Paste" TAB %cmdCtrl SPC "V" TAB "EditorMenuEditPaste();";
item[6] = "Delete" TAB "Delete" TAB "EditorMenuEditDelete();";
item[7] = "-";
item[8] = "Deselect" TAB "X" TAB "EditorMenuEditDeselect();";
Item[9] = "Select..." TAB "" TAB "EditorGui.toggleObjectSelectionsWindow();";
item[10] = "-";
item[11] = "Audio Parameters..." TAB "" TAB "EditorGui.toggleSFXParametersWindow();";
item[12] = "Editor Settings..." TAB "" TAB "ESettingsWindow.ToggleVisibility();";
item[13] = "Snap Options..." TAB "" TAB "ESnapOptions.ToggleVisibility();";
item[14] = "-";
item[15] = "Game Options..." TAB "" TAB "Canvas.pushDialog(optionsDlg);";
item[16] = "PostEffect Manager" TAB "" TAB "Canvas.pushDialog(PostFXManager);";
};
%this.menuBar.insert(%editMenu);
// View Menu
%viewMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorViewMenu";
internalName = "viewMenu";
barTitle = "View";
item[ 0 ] = "Visibility Layers" TAB "Alt V" TAB "VisibilityDropdownToggle();";
item[ 1 ] = "Show Grid in Ortho Views" TAB %cmdCtrl @ "-Shift-Alt G" TAB "EditorGui.toggleOrthoGrid();";
};
%this.menuBar.insert(%viewMenu);
// Camera Menu
%cameraMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorCameraMenu";
barTitle = "Camera";
item[0] = "World Camera" TAB %this.freeCameraTypeMenu;
item[1] = "Player Camera" TAB %this.playerCameraTypeMenu;
item[2] = "-";
Item[3] = "Toggle Camera" TAB %menuCmdCtrl SPC "C" TAB "commandToServer('ToggleCamera');";
item[4] = "Place Camera at Selection" TAB "Ctrl Q" TAB "EWorldEditor.dropCameraToSelection();";
item[5] = "Place Camera at Player" TAB "Alt Q" TAB "commandToServer('dropCameraAtPlayer');";
item[6] = "Place Player at Camera" TAB "Alt W" TAB "commandToServer('DropPlayerAtCamera');";
item[7] = "-";
item[8] = "Fit View to Selection" TAB "F" TAB "commandToServer('EditorCameraAutoFit', EWorldEditor.getSelectionRadius()+1);";
item[9] = "Fit View To Selection and Orbit" TAB "Alt F" TAB "EditorGuiStatusBar.setCamera(\"Orbit Camera\"); commandToServer('EditorCameraAutoFit', EWorldEditor.getSelectionRadius()+1);";
item[10] = "-";
item[11] = "Speed" TAB %this.cameraSpeedMenu;
item[12] = "View" TAB %this.viewTypeMenu;
item[13] = "-";
Item[14] = "Add Bookmark..." TAB "Ctrl B" TAB "EditorGui.addCameraBookmarkByGui();";
Item[15] = "Manage Bookmarks..." TAB "Ctrl-Shift B" TAB "EditorGui.toggleCameraBookmarkWindow();";
item[16] = "Jump to Bookmark" TAB %this.cameraBookmarksMenu;
};
%this.menuBar.insert(%cameraMenu);
// Editors Menu
%editorsMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorToolsMenu";
barTitle = "Editors";
//item[0] = "Object Editor" TAB "F1" TAB WorldEditorInspectorPlugin;
//item[1] = "Material Editor" TAB "F2" TAB MaterialEditorPlugin;
//item[2] = "-";
//item[3] = "Terrain Editor" TAB "F3" TAB TerrainEditorPlugin;
//item[4] = "Terrain Painter" TAB "F4" TAB TerrainPainterPlugin;
//item[5] = "-";
};
%this.menuBar.insert(%editorsMenu);
// Lighting Menu
%lightingMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorLightingMenu";
barTitle = "Lighting";
item[0] = "Full Relight" TAB "Alt L" TAB "Editor.lightScene(\"\", forceAlways);";
item[1] = "Toggle ShadowViz" TAB "" TAB "toggleShadowViz();";
item[2] = "-";
// NOTE: The light managers will be inserted as the
// last menu items in EditorLightingMenu::onAdd().
};
%this.menuBar.insert(%lightingMenu);
// Tools Menu
%toolsMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorUtilitiesMenu";
barTitle = "Tools";
item[0] = "Network Graph" TAB "n" TAB "toggleNetGraph();";
item[1] = "Profiler" TAB "ctrl F2" TAB "showMetrics(true);";
item[2] = "Torque SimView" TAB "" TAB "tree();";
item[3] = "Make Selected a Mesh" TAB "" TAB "makeSelectedAMesh();";
};
%this.menuBar.insert(%toolsMenu);
// Help Menu
%helpMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorHelpMenu";
barTitle = "Help";
item[0] = "Online Documentation..." TAB "Alt F1" TAB "gotoWebPage(EWorldEditor.documentationURL);";
item[1] = "Offline User Guide..." TAB "" TAB "gotoWebPage(EWorldEditor.documentationLocal);";
item[2] = "Offline Reference Guide..." TAB "" TAB "shellexecute(EWorldEditor.documentationReference);";
item[3] = "Torque 3D Forums..." TAB "" TAB "gotoWebPage(EWorldEditor.forumURL);";
};
%this.menuBar.insert(%helpMenu);
// Menus that are added/removed dynamically (temporary)
// World Menu
if(! isObject(%this.worldMenu))
{
%this.dropTypeMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorDropTypeMenu";
// The onSelectItem() callback for this menu re-purposes the command field
// as the MenuBuilder version is not used.
item[0] = "at Origin" TAB "" TAB "atOrigin";
item[1] = "at Camera" TAB "" TAB "atCamera";
item[2] = "at Camera w/Rotation" TAB "" TAB "atCameraRot";
item[3] = "Below Camera" TAB "" TAB "belowCamera";
item[4] = "Screen Center" TAB "" TAB "screenCenter";
item[5] = "at Centroid" TAB "" TAB "atCentroid";
item[6] = "to Terrain" TAB "" TAB "toTerrain";
item[7] = "Below Selection" TAB "" TAB "belowSelection";
item[8] = "At Gizmo" TAB "" TAB "atGizmo";
};
%this.alignBoundsMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorAlignBoundsMenu";
// The onSelectItem() callback for this menu re-purposes the command field
// as the MenuBuilder version is not used.
item[0] = "+X Axis" TAB "" TAB "0";
item[1] = "+Y Axis" TAB "" TAB "1";
item[2] = "+Z Axis" TAB "" TAB "2";
item[3] = "-X Axis" TAB "" TAB "3";
item[4] = "-Y Axis" TAB "" TAB "4";
item[5] = "-Z Axis" TAB "" TAB "5";
};
%this.alignCenterMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorAlignCenterMenu";
// The onSelectItem() callback for this menu re-purposes the command field
// as the MenuBuilder version is not used.
item[0] = "X Axis" TAB "" TAB "0";
item[1] = "Y Axis" TAB "" TAB "1";
item[2] = "Z Axis" TAB "" TAB "2";
};
%this.worldMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorWorldMenu";
barTitle = "Object";
item[0] = "Lock Selection" TAB %cmdCtrl @ " L" TAB "EWorldEditor.lockSelection(true); EWorldEditor.syncGui();";
item[1] = "Unlock Selection" TAB %cmdCtrl @ "-Shift L" TAB "EWorldEditor.lockSelection(false); EWorldEditor.syncGui();";
item[2] = "-";
item[3] = "Hide Selection" TAB %cmdCtrl @ " H" TAB "EWorldEditor.hideSelection(true); EWorldEditor.syncGui();";
item[4] = "Show Selection" TAB %cmdCtrl @ "-Shift H" TAB "EWorldEditor.hideSelection(false); EWorldEditor.syncGui();";
item[5] = "-";
item[6] = "Align Bounds" TAB %this.alignBoundsMenu;
item[7] = "Align Center" TAB %this.alignCenterMenu;
item[8] = "-";
item[9] = "Reset Transforms" TAB "Ctrl R" TAB "EWorldEditor.resetTransforms();";
item[10] = "Reset Selected Rotation" TAB "" TAB "EWorldEditor.resetSelectedRotation();";
item[11] = "Reset Selected Scale" TAB "" TAB "EWorldEditor.resetSelectedScale();";
item[12] = "Transform Selection..." TAB "Ctrl T" TAB "ETransformSelection.ToggleVisibility();";
item[13] = "-";
//item[13] = "Drop Camera to Selection" TAB "Ctrl Q" TAB "EWorldEditor.dropCameraToSelection();";
//item[14] = "Add Selection to Instant Group" TAB "" TAB "EWorldEditor.addSelectionToAddGroup();";
item[14] = "Drop Selection" TAB "Ctrl D" TAB "EWorldEditor.dropSelection();";
//item[15] = "-";
item[15] = "Drop Location" TAB %this.dropTypeMenu;
Item[16] = "-";
Item[17] = "Make Selection Prefab" TAB "" TAB "EditorMakePrefab();";
Item[18] = "Explode Selected Prefab" TAB "" TAB "EditorExplodePrefab();";
Item[19] = "-";
Item[20] = "Mount Selection A to B" TAB "" TAB "EditorMount();";
Item[21] = "Unmount Selected Object" TAB "" TAB "EditorUnmount();";
};
}
}
//////////////////////////////////////////////////////////////////////////
function EditorGui::attachMenus(%this)
{
%this.menuBar.attachToCanvas(Canvas, 0);
}
function EditorGui::detachMenus(%this)
{
%this.menuBar.removeFromCanvas();
}
function EditorGui::setMenuDefaultState(%this)
{
if(! isObject(%this.menuBar))
return 0;
for(%i = 0;%i < %this.menuBar.getMenuCount();%i++)
{
%menu = %this.menuBar.getMenu(%i);
%menu.setupDefaultState();
}
%this.worldMenu.setupDefaultState();
}
//////////////////////////////////////////////////////////////////////////
function EditorGui::findMenu(%this, %name)
{
if(! isObject(%this.menuBar))
return 0;
for(%i = 0; %i < %this.menuBar.getMenuCount(); %i++)
{
%menu = %this.menuBar.getMenu(%i);
if(%name $= %menu.barTitle)
return %menu;
}
return 0;
}
| |
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityTest.UnitTestRunner;
namespace UnityTest
{
[Serializable]
public class UnitTestView : EditorWindow
{
private static class Styles
{
public static GUIStyle buttonLeft;
public static GUIStyle buttonMid;
public static GUIStyle buttonRight;
static Styles ()
{
buttonLeft = GUI.skin.FindStyle (GUI.skin.button.name + "left");
buttonMid = GUI.skin.FindStyle (GUI.skin.button.name + "mid");
buttonRight = GUI.skin.FindStyle (GUI.skin.button.name + "right");
}
}
private List<IUnitTestEngine> testEngines = new List<IUnitTestEngine> ();
[SerializeField]
private List<UnitTestResult> testList = new List<UnitTestResult> ();
#region renderer list
[SerializeField]
private int selectedRenderer;
[SerializeField]
private List<GroupedByHierarchyRenderer> rendererList = new List<GroupedByHierarchyRenderer> ()
{
new GroupedByHierarchyRenderer()
};
#endregion
#region runner steering vars
private bool isCompiling;
private Vector2 testListScroll, testInfoScroll, toolbarScroll;
private bool shouldUpdateTestList;
private string[] testsToRunList;
private bool readyToRun;
#endregion
#region runner options vars
private bool optionsFoldout;
private bool runOnRecompilation;
private bool horizontalSplit = true;
private bool autoSaveSceneBeforeRun;
private bool runTestOnANewScene = true;
private bool notifyOnSlowRun;
private float slowTestThreshold = 1f;
#endregion
#region test filter vars
private bool filtersFoldout;
private string testFilter = "";
private bool showFailed = true;
private bool showIgnored = true;
private bool showNotRun = true;
private bool showSucceeded = true;
private Rect toolbarRect;
#endregion
#region GUI Contents
private readonly GUIContent guiRunSelectedTestsIcon = new GUIContent (Icons.runImg, "Run selected tests");
private readonly GUIContent guiRunAllTestsIcon = new GUIContent (Icons.runAllImg, "Run all tests");
private readonly GUIContent guiRerunFailedTestsIcon = new GUIContent (Icons.runFailedImg, "Rerun failed tests");
private readonly GUIContent guiOptionButton = new GUIContent ("Options", Icons.gearImg);
private readonly GUIContent guiRunOnRecompile = new GUIContent ("Run on recompile", "Run on recompile");
private readonly GUIContent guiRunTestsOnNewScene = new GUIContent ("Run tests on a new scene", "Run tests on a new scene");
private readonly GUIContent guiAutoSaveSceneBeforeRun = new GUIContent ("Autosave scene", "The runner will automaticall save current scene changes before it starts");
private readonly GUIContent guiShowDetailsBelowTests = new GUIContent ("Show details below tests", "Show run details below test list");
private readonly GUIContent guiNotifyWhenSlow = new GUIContent ("Notify when test is slow", "When test will run longer that set threshold, it will be marked as slow");
private readonly GUIContent guiSlowTestThreshold = new GUIContent ("Slow test threshold");
#endregion
public UnitTestView ()
{
title = "Unit Tests Runner";
if (EditorPrefs.HasKey ("UTR-runOnRecompilation"))
{
runOnRecompilation = EditorPrefs.GetBool ("UTR-runOnRecompilation");
runTestOnANewScene = EditorPrefs.GetBool ("UTR-runTestOnANewScene");
autoSaveSceneBeforeRun = EditorPrefs.GetBool ("UTR-autoSaveSceneBeforeRun");
horizontalSplit = EditorPrefs.GetBool ("UTR-horizontalSplit");
notifyOnSlowRun = EditorPrefs.GetBool ("UTR-notifyOnSlowRun");
slowTestThreshold = EditorPrefs.GetFloat ("UTR-slowTestThreshold");
filtersFoldout = EditorPrefs.GetBool ("UTR-filtersFoldout");
showFailed = EditorPrefs.GetBool ("UTR-showFailed");
showIgnored = EditorPrefs.GetBool ("UTR-showIgnored");
showNotRun = EditorPrefs.GetBool ("UTR-showNotRun");
showSucceeded = EditorPrefs.GetBool ("UTR-showSucceeded");
}
InstantiateUnitTestEngines();
}
private void InstantiateUnitTestEngines()
{
var type = typeof(IUnitTestEngine);
var types =
AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(type.IsAssignableFrom)
.Where(t => !t.IsInterface);
IEnumerable<IUnitTestEngine> instances = types.Select(t => Activator.CreateInstance(t)).Cast<IUnitTestEngine>();
testEngines.AddRange(instances);
}
public void SaveOptions()
{
EditorPrefs.SetBool("UTR-runOnRecompilation", runOnRecompilation);
EditorPrefs.SetBool("UTR-runTestOnANewScene", runTestOnANewScene);
EditorPrefs.SetBool("UTR-autoSaveSceneBeforeRun", autoSaveSceneBeforeRun);
EditorPrefs.SetBool("UTR-horizontalSplit", horizontalSplit);
EditorPrefs.SetBool("UTR-notifyOnSlowRun", notifyOnSlowRun);
EditorPrefs.SetFloat("UTR-slowTestThreshold", slowTestThreshold);
EditorPrefs.GetBool("UTR-filtersFoldout", filtersFoldout);
EditorPrefs.SetBool("UTR-showFailed", showFailed);
EditorPrefs.SetBool("UTR-showIgnored", showIgnored);
EditorPrefs.SetBool("UTR-showNotRun", showNotRun);
EditorPrefs.SetBool("UTR-showSucceeded", showSucceeded);
}
public void OnEnable ()
{
RefreshTests ();
shouldUpdateTestList = true;
}
public void OnGUI ()
{
GUILayout.Space (10);
EditorGUILayout.BeginVertical ();
EditorGUILayout.BeginHorizontal ();
var layoutOptions = new[] {
GUILayout.Width(32),
GUILayout.Height(24)
};
if (GUILayout.Button (guiRunAllTestsIcon, Styles.buttonLeft, layoutOptions))
{
RunTests (GetAllVisibleTests ());
}
if (GUILayout.Button (guiRunSelectedTestsIcon, Styles.buttonMid, layoutOptions))
{
RunTests(GetAllSelectedTests());
}
if (GUILayout.Button (guiRerunFailedTestsIcon, Styles.buttonRight, layoutOptions))
{
RunTests(GetAllFailedTests());
}
GUILayout.FlexibleSpace ();
if (GUILayout.Button (guiOptionButton, GUILayout.Height(24), GUILayout.Width(80)))
{
optionsFoldout = !optionsFoldout;
}
EditorGUILayout.EndHorizontal ();
if (optionsFoldout) DrawOptions();
EditorGUILayout.BeginHorizontal ();
EditorGUILayout.LabelField("Filter:", GUILayout.Width(33));
testFilter = EditorGUILayout.TextField(testFilter, EditorStyles.textField);
if (GUILayout.Button(filtersFoldout ? "Hide" : "Advanced", GUILayout.Width(80)))
filtersFoldout = !filtersFoldout;
EditorGUILayout.EndHorizontal ();
if (filtersFoldout)
DrawFilters ();
GUILayout.Box ("", new [] {GUILayout.ExpandWidth (true), GUILayout.Height (1)});
GetRenderer ().RenderOptions ();
if (horizontalSplit)
EditorGUILayout.BeginVertical ();
else
EditorGUILayout.BeginHorizontal ();
RenderToolbar ();
RenderTestList ();
if (horizontalSplit)
GUILayout.Box ("", new[] {GUILayout.ExpandWidth (true), GUILayout.Height (1)});
else
GUILayout.Box ("", new[] {GUILayout.ExpandHeight (true), GUILayout.Width (1)});
RenderTestInfo ();
if (horizontalSplit)
EditorGUILayout.EndVertical ();
else
EditorGUILayout.EndHorizontal ();
EditorGUILayout.EndVertical ();
}
private void RenderToolbar ()
{
if (rendererList.Count > 1)
{
toolbarScroll = EditorGUILayout.BeginScrollView(toolbarScroll, GUILayout.ExpandHeight(false));
EditorGUILayout.BeginHorizontal ();
var toolbarList = rendererList.Select(hierarchyRenderer =>
{
var label = hierarchyRenderer.filterString;
if (string.IsNullOrEmpty (label)) label = "All tests";
return new GUIContent (label, label);
}).ToArray();
if (toolbarRect.Contains (Event.current.mousePosition)
&& Event.current.type == EventType.MouseDown
&& Event.current.button == 1)
{
var tabWidth = toolbarRect.width / rendererList.Count;
var tabNo = (int)(Event.current.mousePosition.x / tabWidth);
if(tabNo != 0)
{
var menu = new GenericMenu ();
menu.AddItem (new GUIContent ("Remove"), false, ()=>RemoveSelectedTab(tabNo));
menu.ShowAsContext ();
}
Event.current.Use ();
}
selectedRenderer = GUILayout.Toolbar(selectedRenderer, toolbarList);
if (Event.current.type == EventType.Repaint)
toolbarRect = GUILayoutUtility.GetLastRect ();
EditorGUILayout.EndHorizontal ();
EditorGUILayout.EndScrollView();
}
}
private void RemoveSelectedTab (int idx)
{
rendererList.RemoveAt (idx);
selectedRenderer--;
}
private GroupedByHierarchyRenderer GetRenderer ()
{
var r = rendererList.ElementAtOrDefault (selectedRenderer);
if (r == null)
{
selectedRenderer = 0;
r = rendererList[selectedRenderer];
}
return r;
}
private void RenderTestList ()
{
testListScroll = EditorGUILayout.BeginScrollView (testListScroll,
GUILayout.ExpandHeight (true),
GUILayout.ExpandWidth (true),
horizontalSplit ? GUILayout.MinHeight (0) : GUILayout.MaxWidth (500),
horizontalSplit ? GUILayout.MinWidth (0) : GUILayout.MinWidth (200));
var filteredResults = FilterResults (testList);
GetRenderer().notifyOnSlowRun = notifyOnSlowRun;
GetRenderer().slowTestThreshold = slowTestThreshold;
if (rendererList.ElementAtOrDefault(selectedRenderer) == null)
selectedRenderer = 0;
shouldUpdateTestList = rendererList[selectedRenderer].RenderTests (filteredResults, RunTests);
EditorGUILayout.EndScrollView ();
}
private void RenderTestInfo ()
{
testInfoScroll = EditorGUILayout.BeginScrollView (testInfoScroll,
GUILayout.ExpandHeight (true),
GUILayout.ExpandWidth (true),
horizontalSplit ? GUILayout.MaxHeight (200) : GUILayout.MinWidth (0));
GetRenderer().RenderInfo();
EditorGUILayout.EndScrollView ();
}
private void DrawFilters ()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal ();
EditorGUILayout.BeginVertical ();
showSucceeded = EditorGUILayout.Toggle("Show succeeded", showSucceeded, GUILayout.MinWidth (120));
showFailed = EditorGUILayout.Toggle("Show failed", showFailed, GUILayout.MinWidth (120));
EditorGUILayout.EndVertical ();
EditorGUILayout.BeginVertical ();
showIgnored = EditorGUILayout.Toggle("Show ignored", showIgnored);
showNotRun = EditorGUILayout.Toggle("Show not runned", showNotRun);
EditorGUILayout.EndVertical ();
EditorGUILayout.EndHorizontal ();
if (EditorGUI.EndChangeCheck())
SaveOptions();
}
private void DrawOptions ()
{
EditorGUI.BeginChangeCheck ();
runOnRecompilation = EditorGUILayout.Toggle (guiRunOnRecompile, runOnRecompilation);
runTestOnANewScene = EditorGUILayout.Toggle (guiRunTestsOnNewScene, runTestOnANewScene);
if (runTestOnANewScene)
autoSaveSceneBeforeRun = EditorGUILayout.Toggle (guiAutoSaveSceneBeforeRun, autoSaveSceneBeforeRun);
horizontalSplit = EditorGUILayout.Toggle (guiShowDetailsBelowTests, horizontalSplit);
notifyOnSlowRun = EditorGUILayout.Toggle(guiNotifyWhenSlow, notifyOnSlowRun);
if (notifyOnSlowRun)
slowTestThreshold = EditorGUILayout.FloatField(guiSlowTestThreshold, slowTestThreshold);
if (EditorGUI.EndChangeCheck())
SaveOptions();
EditorGUILayout.Space ();
}
private IEnumerable<UnitTestResult> FilterResults (IEnumerable<UnitTestResult> mTestResults)
{
var results = mTestResults;
if (!string.IsNullOrEmpty(GetRenderer ().filterString))
results = results.Where(result => result.Test.FullClassName == GetRenderer().filterString);
results = results.Where(r => r.Test.FullName.ToLower().Contains(testFilter.ToLower()));
if (!showIgnored)
results = results.Where (r => !r.IsIgnored);
if (!showFailed)
results = results.Where (r => !(r.IsFailure || r.IsError || r.IsInconclusive));
if (!showNotRun)
results = results.Where (r => r.Executed);
if (!showSucceeded)
results = results.Where (r => !r.IsSuccess);
return results;
}
private string[] GetAllVisibleTests ()
{
return FilterResults (testList).Select (result => result.Test.FullName).ToArray ();
}
private string[] GetAllSelectedTests()
{
return GetRenderer().GetSelectedTests();
}
private string[] GetAllFailedTests ()
{
return FilterResults (testList).Where (result => result.IsError || result.IsFailure).Select (result => result.Test.FullName).ToArray ();
}
private void RefreshTests ()
{
var newTestResults = new List<UnitTestResult> ();
var allTests = new List<UnitTestResult> ();
foreach (var unitTestEngine in testEngines)
{
allTests.AddRange (unitTestEngine.GetTests (true));
}
foreach (var result in testList)
{
var test = allTests.SingleOrDefault (testResult => testResult.Test == result.Test);
if (test != null)
{
newTestResults.Add (result);
allTests.Remove(test);
}
}
newTestResults.AddRange(allTests);
testList = newTestResults;
}
private void UpdateTestInfo(ITestResult result)
{
FindTestResultByName(result.FullName).Update(result);
}
private UnitTestResult FindTestResultByName (string name)
{
var idx = testList.FindIndex(testResult => testResult.Test.FullName == name);
return testList.ElementAt (idx);
}
public void Update ()
{
if (readyToRun)
{
readyToRun = false;
StartTestRun();
}
if (shouldUpdateTestList)
{
shouldUpdateTestList = false;
Repaint ();
}
if (EditorApplication.isCompiling && !isCompiling)
{
isCompiling = true;
}
if (isCompiling && !EditorApplication.isCompiling)
{
isCompiling = false;
OnRecompile ();
}
}
public void OnRecompile ()
{
RefreshTests ();
if (runOnRecompilation && IsCompilationCompleted())
RunTests (GetAllVisibleTests ());
}
private bool IsCompilationCompleted ()
{
return File.Exists (Path.GetFullPath ("Library/ScriptAssemblies/CompilationCompleted.txt"));
}
private void RunTests (string[] tests)
{
if (readyToRun)
{
Debug.LogWarning ("Tests are already running");
return;
}
testsToRunList = tests;
readyToRun = true;
}
private void StartTestRun ()
{
var okToRun = true;
if (runTestOnANewScene && !UnityEditorInternal.InternalEditorUtility.inBatchMode)
{
if (autoSaveSceneBeforeRun)
EditorApplication.SaveScene ();
okToRun = EditorApplication.SaveCurrentSceneIfUserWantsTo ();
}
if (okToRun)
{
var currentScene = EditorApplication.currentScene;
if (runTestOnANewScene || UnityEditorInternal.InternalEditorUtility.inBatchMode)
EditorApplication.NewScene ();
var callbackList = new TestRunnerCallbackList ();
callbackList.Add (new TestRunnerEventListener (this));
try
{
foreach (var unitTestEngine in testEngines)
{
unitTestEngine.RunTests (testsToRunList,
callbackList);
}
}
catch (Exception e)
{
Debug.LogException (e);
callbackList.RunFinishedException (e);
}
finally
{
EditorUtility.ClearProgressBar();
if (runTestOnANewScene && !UnityEditorInternal.InternalEditorUtility.inBatchMode)
EditorApplication.OpenScene (currentScene);
if (UnityEditorInternal.InternalEditorUtility.inBatchMode)
EditorApplication.Exit(0);
shouldUpdateTestList = true;
}
}
}
[MenuItem ("Unity Test Tools/Unit Test Runner %#&u")]
public static void ShowWindow ()
{
GetWindow (typeof (UnitTestView)).Show ();
}
[MenuItem("Unity Test Tools/Run all unit tests")]
public static void RunAllTestsBatch()
{
var window = GetWindow(typeof(UnitTestView)) as UnitTestView;
window.RefreshTests ();
window.RunTests (new string[0]);
}
[MenuItem("Assets/Unity Test Tools/Load tests from this file")]
static void LoadTestsFromFile(MenuCommand command)
{
if (!ValidateLoadTestsFromFile() && Selection.objects.Any())
{
Debug.Log ("Not all selected files are script files");
}
var window = GetWindow(typeof(UnitTestView)) as UnitTestView;
foreach (var o in Selection.objects)
{
window.selectedRenderer = window.AddNewRenderer((o as MonoScript).GetClass());
}
window.toolbarScroll = new Vector2(float.MaxValue, 0);
}
private int AddNewRenderer (Type classFilter)
{
var elem = rendererList.SingleOrDefault (hierarchyRenderer => hierarchyRenderer.filterString == classFilter.FullName);
if ( elem == null)
{
elem = new GroupedByHierarchyRenderer (classFilter);
rendererList.Add(elem);
}
return rendererList.IndexOf (elem);
}
[MenuItem("Assets/Unity Test Tools/Load tests from this file", true)]
static bool ValidateLoadTestsFromFile()
{
return Selection.objects.All (o => o is MonoScript);
}
private class TestRunnerEventListener : ITestRunnerCallback
{
private UnitTestView unitTestView;
public TestRunnerEventListener(UnitTestView unitTestView)
{
this.unitTestView = unitTestView;
}
public void TestStarted (string fullName)
{
EditorUtility.DisplayProgressBar("Unit Tests Runner",
fullName,
1);
}
public void TestFinished(ITestResult result)
{
unitTestView.UpdateTestInfo(result);
}
public void RunStarted (string suiteName, int testCount)
{
}
public void RunFinished ()
{
var resultWriter = new XmlResultWriter("UnitTestResults.xml");
resultWriter.SaveTestResult ("Unit Tests", unitTestView.testList.ToArray ());
EditorUtility.ClearProgressBar();
}
public void RunFinishedException (Exception exception)
{
RunFinished ();
}
}
}
}
| |
// 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 ShiftLeftLogicalInt6464()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogicalInt6464();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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 SimpleUnaryOpTest__ShiftLeftLogicalInt6464
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int64);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar;
private Vector128<Int64> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable;
static SimpleUnaryOpTest__ShiftLeftLogicalInt6464()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftLeftLogicalInt6464()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.ShiftLeftLogical(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.ShiftLeftLogical(
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.ShiftLeftLogical(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.ShiftLeftLogical(
_clsVar,
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftLeftLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogicalInt6464();
var result = Sse2.ShiftLeftLogical(test._fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.ShiftLeftLogical(_fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
if (0 != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical)}<Int64>(Vector128<Int64><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;
namespace RSAEncryption
{
/// <summary>
/// A RSA enccryption provider.
/// </summary>
public class RSAEncryptionProvider
{
/// <summary>
/// Get the RSA provider from the PEM file.
/// </summary>
/// <param name="pemfile">PEM file.</param>
/// <param name="keyPassPhrase">Key pass phrase.</param>
/// <returns>Get an instance of RSACryptoServiceProvider.</returns>
public static RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile,SecureString keyPassPhrase = null)
{
const String pempubheader = "-----BEGIN PUBLIC KEY-----";
const String pempubfooter = "-----END PUBLIC KEY-----";
bool isPrivateKeyFile = true;
byte[] pemkey = null;
if (!File.Exists(pemfile))
{
throw new Exception("private key file does not exist.");
}
string pemstr = File.ReadAllText(pemfile).Trim();
if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter))
{
isPrivateKeyFile = false;
}
if (isPrivateKeyFile)
{
pemkey = ConvertPrivateKeyToBytes(pemstr,keyPassPhrase);
if (pemkey == null)
{
return null;
}
return DecodeRSAPrivateKey(pemkey);
}
return null ;
}
/// <summary>
/// Convert the private key to bytes.
/// </summary>
/// <param name="instr">Private key.</param>
/// <param name="keyPassPhrase">Key pass phrase.</param>
/// <returns>The private key in the form of bytes.</returns>
static byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPhrase = null)
{
const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----";
const String pemprivfooter = "-----END RSA PRIVATE KEY-----";
String pemstr = instr.Trim();
byte[] binkey;
if (!pemstr.StartsWith(pemprivheader) || !pemstr.EndsWith(pemprivfooter))
{
return null;
}
StringBuilder sb = new StringBuilder(pemstr);
sb.Replace(pemprivheader, "");
sb.Replace(pemprivfooter, "");
String pvkstr = sb.ToString().Trim();
try
{ // if there are no PEM encryption info lines, this is an UNencrypted PEM private key
binkey = Convert.FromBase64String(pvkstr);
return binkey;
}
catch (System.FormatException)
{
StringReader str = new StringReader(pvkstr);
//-------- read PEM encryption info. lines and extract salt -----
if (!str.ReadLine().StartsWith("Proc-Type: 4,ENCRYPTED"))
{
return null;
}
String saltline = str.ReadLine();
if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,"))
{
return null;
}
String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim();
byte[] salt = new byte[saltstr.Length / 2];
for (int i = 0; i < salt.Length; i++)
{
salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16);
}
if (str.ReadLine() != "")
{
return null;
}
//------ remaining b64 data is encrypted RSA key ----
String encryptedstr = str.ReadToEnd();
try
{ //should have b64 encrypted RSA key now
binkey = Convert.FromBase64String(encryptedstr);
}
catch (System.FormatException)
{ //data is not in base64 format
return null;
}
byte[] deskey = GetEncryptedKey(salt, keyPassPhrase, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes
if (deskey == null)
{
return null;
}
//------ Decrypt the encrypted 3des-encrypted RSA private key ------
byte[] rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV
return rsakey;
}
}
/// <summary>
/// Decode the RSA private key.
/// </summary>
/// <param name="privkey">Private key.</param>
/// <returns>An instance of RSACryptoServiceProvider.</returns>
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
byte[] bytesModules, bytesE, bytesD, bytesP, bytesQ, bytesDp, bytesDq, bytesIq;
// --------- Set up stream to decode the asn.1 encoded RSA private key ------
MemoryStream mem = new MemoryStream(privkey);
BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
byte bt = 0;
ushort twobytes = 0;
int elems = 0;
try
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
{
binr.ReadByte(); //advance 1 byte
}
else if (twobytes == 0x8230)
{
binr.ReadInt16(); //advance 2 bytes
}
else
{
return null;
}
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
{
return null;
}
bt = binr.ReadByte();
if (bt != 0x00)
{
return null;
}
//------ all private key components are Integer sequences ----
elems = GetIntegerSize(binr);
bytesModules = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
bytesE = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
bytesD = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
bytesP = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
bytesQ = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
bytesDp = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
bytesDq = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
bytesIq = binr.ReadBytes(elems);
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters RSAparams = new RSAParameters();
RSAparams.Modulus = bytesModules;
RSAparams.Exponent = bytesE;
RSAparams.D = bytesD;
RSAparams.P = bytesP;
RSAparams.Q = bytesQ;
RSAparams.DP = bytesDp;
RSAparams.DQ = bytesDq;
RSAparams.InverseQ = bytesIq;
rsa.ImportParameters(RSAparams);
return rsa;
}
catch (Exception)
{
return null;
}
finally
{
binr.Close();
}
}
private static int GetIntegerSize(BinaryReader binr)
{
byte bt = 0;
byte lowbyte = 0x00;
byte highbyte = 0x00;
int count = 0;
bt = binr.ReadByte();
if (bt != 0x02) //expect integer
{
return 0;
}
bt = binr.ReadByte();
if (bt == 0x81)
{
count = binr.ReadByte(); // data size in next byte
}
else if (bt == 0x82)
{
highbyte = binr.ReadByte(); // data size in next 2 bytes
lowbyte = binr.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, 0);
}
else
{
count = bt; // we already have the data size
}
while (binr.ReadByte() == 0x00)
{ //remove high order zeros in data
count -= 1;
}
binr.BaseStream.Seek(-1, SeekOrigin.Current);
//last ReadByte wasn't a removed zero, so back up a byte
return count;
}
/// <summary>
/// Get the encrypted key.
/// </summary>
/// <param name="salt">Random bytes to be added.</param>
/// <param name="secpswd">Password.</param>
/// <param name="count">Count.</param>
/// <param name="miter">Miter.</param>
/// <returns>Decrypted key.</returns>
static byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter)
{
IntPtr unmanagedPswd = IntPtr.Zero;
const int HASHLENGTH = 16; //MD5 bytes
byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results
byte[] psbytes = new byte[secpswd.Length];
unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd);
Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length);
Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd);
// --- concatenate salt and pswd bytes into fixed data array ---
byte[] data00 = new byte[psbytes.Length + salt.Length];
Array.Copy(psbytes, data00, psbytes.Length); //copy the pswd bytes
Array.Copy(salt, 0, data00, psbytes.Length, salt.Length); //concatenate the salt bytes
// ---- do multi-hashing and concatenate results D1, D2 ... into keymaterial bytes ----
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = null;
byte[] hashtarget = new byte[HASHLENGTH + data00.Length]; //fixed length initial hashtarget
for (int j = 0; j < miter; j++)
{
// ---- Now hash consecutively for count times ------
if (j == 0)
{
result = data00; //initialize
}
else
{
Array.Copy(result, hashtarget, result.Length);
Array.Copy(data00, 0, hashtarget, result.Length, data00.Length);
result = hashtarget;
}
for (int i = 0; i < count; i++)
{
result = md5.ComputeHash(result);
}
Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial
}
byte[] deskey = new byte[24];
Array.Copy(keymaterial, deskey, deskey.Length);
Array.Clear(psbytes, 0, psbytes.Length);
Array.Clear(data00, 0, data00.Length);
Array.Clear(result, 0, result.Length);
Array.Clear(hashtarget, 0, hashtarget.Length);
Array.Clear(keymaterial, 0, keymaterial.Length);
return deskey;
}
/// <summary>
/// Decrypt the key.
/// </summary>
/// <param name="chipherData">Cipher data.</param>
/// <param name="desKey">Key to decrypt.</param>
/// <param name="IV">Initialization vector.</param>
/// <returns>Decrypted key.</returns>
static byte[] DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV)
{
MemoryStream memst = new MemoryStream();
TripleDES alg = TripleDES.Create();
alg.Key = desKey;
alg.IV = IV;
try
{
CryptoStream cs = new CryptoStream(memst, alg.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherData, 0, cipherData.Length);
cs.Close();
}
catch (Exception)
{
return null;
}
byte[] decryptedData = memst.ToArray();
return decryptedData;
}
}
}
| |
/*
* 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.Reflection;
using Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Data;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.AssetService
{
public class AssetService : AssetServiceBase, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected static AssetService m_RootInstance;
public AssetService(IConfigSource config)
: this(config, "AssetService")
{
}
public AssetService(IConfigSource config, string configName) : base(config, configName)
{
if (m_RootInstance == null)
{
m_RootInstance = this;
if (m_AssetLoader != null)
{
IConfig assetConfig = config.Configs[m_ConfigName];
if (assetConfig == null)
throw new Exception("No " + m_ConfigName + " configuration");
string loaderArgs = assetConfig.GetString("AssetLoaderArgs",
String.Empty);
bool assetLoaderEnabled = assetConfig.GetBoolean("AssetLoaderEnabled", true);
if (assetLoaderEnabled)
{
m_log.DebugFormat("[ASSET SERVICE]: Loading default asset set from {0}", loaderArgs);
m_AssetLoader.ForEachDefaultXmlAsset(
loaderArgs,
delegate(AssetBase a)
{
AssetBase existingAsset = Get(a.ID);
// AssetMetadata existingMetadata = GetMetadata(a.ID);
if (existingAsset == null || Util.SHA1Hash(existingAsset.Data) != Util.SHA1Hash(a.Data))
{
// m_log.DebugFormat("[ASSET]: Storing {0} {1}", a.Name, a.ID);
Store(a);
}
});
}
m_log.Debug("[ASSET SERVICE]: Local asset service enabled");
}
}
}
public virtual AssetBase Get(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset for {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
{
m_log.WarnFormat("[ASSET SERVICE]: Could not parse requested asset id {0}", id);
return null;
}
try
{
return m_Database.GetAsset(assetID);
}
catch (Exception e)
{
m_log.ErrorFormat("[ASSET SERVICE]: Exception getting asset {0} {1}", assetID, e);
return null;
}
}
public virtual AssetBase GetCached(string id)
{
return Get(id);
}
public virtual AssetMetadata GetMetadata(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset metadata for {0}", id);
AssetBase asset = Get(id);
if (asset != null)
return asset.Metadata;
else
return null;
}
public virtual byte[] GetData(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset data for {0}", id);
AssetBase asset = Get(id);
if (asset != null)
return asset.Data;
else
return null;
}
public virtual bool Get(string id, Object sender, AssetRetrieved handler)
{
//m_log.DebugFormat("[AssetService]: Get asset async {0}", id);
handler(id, sender, Get(id));
return true;
}
public virtual bool[] AssetsExist(string[] ids)
{
try
{
UUID[] uuid = Array.ConvertAll(ids, id => UUID.Parse(id));
return m_Database.AssetsExist(uuid);
}
catch (Exception e)
{
m_log.Error("[ASSET SERVICE]: Exception getting assets ", e);
return new bool[ids.Length];
}
}
public virtual string Store(AssetBase asset)
{
bool exists = m_Database.AssetsExist(new[] { asset.FullID })[0];
if (!exists)
{
// m_log.DebugFormat(
// "[ASSET SERVICE]: Storing asset {0} {1}, bytes {2}", asset.Name, asset.FullID, asset.Data.Length);
m_Database.StoreAsset(asset);
}
// else
// {
// m_log.DebugFormat(
// "[ASSET SERVICE]: Not storing asset {0} {1}, bytes {2} as it already exists", asset.Name, asset.FullID, asset.Data.Length);
// }
return asset.ID;
}
public bool UpdateContent(string id, byte[] data)
{
return false;
}
public virtual bool Delete(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Deleting asset {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
return m_Database.Delete(id);
}
}
}
| |
/*
* 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.Threading;
using Thrift.Collections;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Test;
namespace Test
{
public class TestClient
{
private static int numIterations = 1;
public static void Execute(string[] args)
{
try
{
string host = "localhost";
int port = 9090;
string url = null;
int numThreads = 1;
bool buffered = false;
try
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-h")
{
string[] hostport = args[++i].Split(':');
host = hostport[0];
if (hostport.Length > 1)
{
port = Convert.ToInt32(hostport[1]);
}
}
else if (args[i] == "-u")
{
url = args[++i];
}
else if (args[i] == "-n")
{
numIterations = Convert.ToInt32(args[++i]);
}
else if (args[i] == "-b" || args[i] == "-buffered")
{
buffered = true;
Console.WriteLine("Using buffered sockets");
}
else if (args[i] == "-t")
{
numThreads = Convert.ToInt32(args[++i]);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
//issue tests on separate threads simultaneously
Thread[] threads = new Thread[numThreads];
DateTime start = DateTime.Now;
for (int test = 0; test < numThreads; test++)
{
Thread t = new Thread(new ParameterizedThreadStart(ClientThread));
threads[test] = t;
TSocket socket = new TSocket(host, port);
if (buffered)
{
TBufferedTransport buffer = new TBufferedTransport(socket);
t.Start(buffer);
}
else
{
t.Start(socket);
}
}
for (int test = 0; test < numThreads; test++)
{
threads[test].Join();
}
Console.Write("Total time: " + (DateTime.Now - start));
}
catch (Exception outerEx)
{
Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
}
Console.WriteLine();
Console.WriteLine();
}
public static void ClientThread(object obj)
{
TTransport transport = (TTransport)obj;
for (int i = 0; i < numIterations; i++)
{
ClientTest(transport);
}
transport.Close();
}
public static void ClientTest(TTransport transport)
{
TBinaryProtocol binaryProtocol = new TBinaryProtocol(transport);
ThriftTest.Client client = new ThriftTest.Client(binaryProtocol);
try
{
if (!transport.IsOpen)
{
transport.Open();
}
}
catch (TTransportException ttx)
{
Console.WriteLine("Connect failed: " + ttx.Message);
return;
}
long start = DateTime.Now.ToFileTime();
Console.Write("testVoid()");
client.testVoid();
Console.WriteLine(" = void");
Console.Write("testString(\"Test\")");
string s = client.testString("Test");
Console.WriteLine(" = \"" + s + "\"");
Console.Write("testByte(1)");
byte i8 = client.testByte((byte)1);
Console.WriteLine(" = " + i8);
Console.Write("testI32(-1)");
int i32 = client.testI32(-1);
Console.WriteLine(" = " + i32);
Console.Write("testI64(-34359738368)");
long i64 = client.testI64(-34359738368);
Console.WriteLine(" = " + i64);
Console.Write("testDouble(5.325098235)");
double dub = client.testDouble(5.325098235);
Console.WriteLine(" = " + dub);
Console.Write("testStruct({\"Zero\", 1, -3, -5})");
Xtruct o = new Xtruct();
o.String_thing = "Zero";
o.Byte_thing = (byte)1;
o.I32_thing = -3;
o.I64_thing = -5;
Xtruct i = client.testStruct(o);
Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
Xtruct2 o2 = new Xtruct2();
o2.Byte_thing = (byte)1;
o2.Struct_thing = o;
o2.I32_thing = 5;
Xtruct2 i2 = client.testNest(o2);
i = i2.Struct_thing;
Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
Dictionary<int, int> mapout = new Dictionary<int, int>();
for (int j = 0; j < 5; j++)
{
mapout[j] = j - 10;
}
Console.Write("testMap({");
bool first = true;
foreach (int key in mapout.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapout[key]);
}
Console.Write("})");
Dictionary<int, int> mapin = client.testMap(mapout);
Console.Write(" = {");
first = true;
foreach (int key in mapin.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapin[key]);
}
Console.WriteLine("}");
List<int> listout = new List<int>();
for (int j = -2; j < 3; j++)
{
listout.Add(j);
}
Console.Write("testList({");
first = true;
foreach (int j in listout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
List<int> listin = client.testList(listout);
Console.Write(" = {");
first = true;
foreach (int j in listin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
//set
THashSet<int> setout = new THashSet<int>();
for (int j = -2; j < 3; j++)
{
setout.Add(j);
}
Console.Write("testSet({");
first = true;
foreach (int j in setout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
THashSet<int> setin = client.testSet(setout);
Console.Write(" = {");
first = true;
foreach (int j in setin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
Console.Write("testEnum(ONE)");
Numberz ret = client.testEnum(Numberz.ONE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(TWO)");
ret = client.testEnum(Numberz.TWO);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(THREE)");
ret = client.testEnum(Numberz.THREE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(FIVE)");
ret = client.testEnum(Numberz.FIVE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(EIGHT)");
ret = client.testEnum(Numberz.EIGHT);
Console.WriteLine(" = " + ret);
Console.Write("testTypedef(309858235082523)");
long uid = client.testTypedef(309858235082523L);
Console.WriteLine(" = " + uid);
Console.Write("testMapMap(1)");
Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1);
Console.Write(" = {");
foreach (int key in mm.Keys)
{
Console.Write(key + " => {");
Dictionary<int, int> m2 = mm[key];
foreach (int k2 in m2.Keys)
{
Console.Write(k2 + " => " + m2[k2] + ", ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
Insanity insane = new Insanity();
insane.UserMap = new Dictionary<Numberz, long>();
insane.UserMap[Numberz.FIVE] = 5000L;
Xtruct truck = new Xtruct();
truck.String_thing = "Truck";
truck.Byte_thing = (byte)8;
truck.I32_thing = 8;
truck.I64_thing = 8;
insane.Xtructs = new List<Xtruct>();
insane.Xtructs.Add(truck);
Console.Write("testInsanity()");
Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane);
Console.Write(" = {");
foreach (long key in whoa.Keys)
{
Dictionary<Numberz, Insanity> val = whoa[key];
Console.Write(key + " => {");
foreach (Numberz k2 in val.Keys)
{
Insanity v2 = val[k2];
Console.Write(k2 + " => {");
Dictionary<Numberz, long> userMap = v2.UserMap;
Console.Write("{");
if (userMap != null)
{
foreach (Numberz k3 in userMap.Keys)
{
Console.Write(k3 + " => " + userMap[k3] + ", ");
}
}
else
{
Console.Write("null");
}
Console.Write("}, ");
List<Xtruct> xtructs = v2.Xtructs;
Console.Write("{");
if (xtructs != null)
{
foreach (Xtruct x in xtructs)
{
Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
}
}
else
{
Console.Write("null");
}
Console.Write("}");
Console.Write("}, ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
byte arg0 = 1;
int arg1 = 2;
long arg2 = long.MaxValue;
Dictionary<short, string> multiDict = new Dictionary<short, string>();
multiDict[1] = "one";
Numberz arg4 = Numberz.FIVE;
long arg5 = 5000000;
Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")");
Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5);
Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
+ ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
Console.WriteLine("Test Oneway(1)");
client.testOneway(1);
}
}
}
| |
using System;
using System.Text;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using HETSAPI.Models;
namespace HETSAPI.ViewModels
{
/// <summary>
/// Uploaded documents related to entity in the application - e.g. piece of Equipment, an Owner, a Project and so on.
/// </summary>
[MetaData (Description = "Uploaded documents related to entity in the application - e.g. piece of Equipment, an Owner, a Project and so on.")]
[DataContract]
public sealed class AttachmentViewModel : IEquatable<AttachmentViewModel>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public AttachmentViewModel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AttachmentViewModel" /> class.
/// </summary>
/// <param name="id">A system-generated unique identifier for an Attachment (required).</param>
/// <param name="fileName">Filename as passed by the user uploading the file (required).</param>
/// <param name="fileSize">FileSize.</param>
/// <param name="description">A note about the attachment, optionally maintained by the user..</param>
/// <param name="type">Type of attachment.</param>
/// <param name="lastUpdateUserid">Audit information - SM User Id for the User who most recently updated the record..</param>
/// <param name="lastUpdateTimestamp">Audit information - Timestamp for record modification.</param>
public AttachmentViewModel(int id, string fileName, int? fileSize = null, string description = null,
string type = null, string lastUpdateUserid = null, DateTime? lastUpdateTimestamp = null)
{
Id = id;
FileName = fileName;
FileSize = fileSize;
Description = description;
Type = type;
LastUpdateUserid = lastUpdateUserid;
LastUpdateTimestamp = lastUpdateTimestamp;
}
/// <summary>
/// A system-generated unique identifier for an Attachment
/// </summary>
/// <value>A system-generated unique identifier for an Attachment</value>
[DataMember(Name="id")]
[MetaData (Description = "A system-generated unique identifier for an Attachment")]
public int Id { get; set; }
/// <summary>
/// Filename as passed by the user uploading the file
/// </summary>
/// <value>Filename as passed by the user uploading the file</value>
[DataMember(Name="fileName")]
[MetaData (Description = "Filename as passed by the user uploading the file")]
public string FileName { get; set; }
/// <summary>
/// Gets or Sets FileSize
/// </summary>
[DataMember(Name="fileSize")]
public int? FileSize { get; set; }
/// <summary>
/// A note about the attachment, optionally maintained by the user.
/// </summary>
/// <value>A note about the attachment, optionally maintained by the user.</value>
[DataMember(Name="description")]
[MetaData (Description = "A note about the attachment, optionally maintained by the user.")]
public string Description { get; set; }
/// <summary>
/// Type of attachment
/// </summary>
/// <value>Type of attachment</value>
[DataMember(Name="type")]
[MetaData (Description = "Type of attachment")]
public string Type { get; set; }
/// <summary>
/// Audit information - SM User Id for the User who most recently updated the record.
/// </summary>
/// <value>Audit information - SM User Id for the User who most recently updated the record.</value>
[DataMember(Name="lastUpdateUserid")]
[MetaData (Description = "Audit information - SM User Id for the User who most recently updated the record.")]
public string LastUpdateUserid { get; set; }
/// <summary>
/// Audit information - Timestamp for record modification
/// </summary>
/// <value>Audit information - Timestamp for record modification</value>
[DataMember(Name="lastUpdateTimestamp")]
[MetaData (Description = "Audit information - Timestamp for record modification")]
public DateTime? LastUpdateTimestamp { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AttachmentViewModel {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" FileName: ").Append(FileName).Append("\n");
sb.Append(" FileSize: ").Append(FileSize).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" LastUpdateUserid: ").Append(LastUpdateUserid).Append("\n");
sb.Append(" LastUpdateTimestamp: ").Append(LastUpdateTimestamp).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj.GetType() == GetType() && Equals((AttachmentViewModel)obj);
}
/// <summary>
/// Returns true if AttachmentViewModel instances are equal
/// </summary>
/// <param name="other">Instance of AttachmentViewModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AttachmentViewModel other)
{
if (other is null) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
Id == other.Id ||
Id.Equals(other.Id)
) &&
(
FileName == other.FileName ||
FileName != null &&
FileName.Equals(other.FileName)
) &&
(
FileSize == other.FileSize ||
FileSize != null &&
FileSize.Equals(other.FileSize)
) &&
(
Description == other.Description ||
Description != null &&
Description.Equals(other.Description)
) &&
(
Type == other.Type ||
Type != null &&
Type.Equals(other.Type)
) &&
(
LastUpdateUserid == other.LastUpdateUserid ||
LastUpdateUserid != null &&
LastUpdateUserid.Equals(other.LastUpdateUserid)
) &&
(
LastUpdateTimestamp == other.LastUpdateTimestamp ||
LastUpdateTimestamp != null &&
LastUpdateTimestamp.Equals(other.LastUpdateTimestamp)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + Id.GetHashCode(); if (FileName != null)
{
hash = hash * 59 + FileName.GetHashCode();
}
if (FileSize != null)
{
hash = hash * 59 + FileSize.GetHashCode();
}
if (Description != null)
{
hash = hash * 59 + Description.GetHashCode();
}
if (Type != null)
{
hash = hash * 59 + Type.GetHashCode();
}
if (LastUpdateUserid != null)
{
hash = hash * 59 + LastUpdateUserid.GetHashCode();
}
if (LastUpdateTimestamp != null)
{
hash = hash * 59 + LastUpdateTimestamp.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(AttachmentViewModel left, AttachmentViewModel right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(AttachmentViewModel left, AttachmentViewModel right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using J2N.Threading.Atomic;
using Lucene.Net.Index;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.IO;
namespace Lucene.Net.Codecs.Lucene45
{
/*
* 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 BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
using IBits = Lucene.Net.Util.IBits;
using BlockPackedReader = Lucene.Net.Util.Packed.BlockPackedReader;
using BytesRef = Lucene.Net.Util.BytesRef;
using ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput;
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
using DocsEnum = Lucene.Net.Index.DocsEnum;
using DocValues = Lucene.Net.Index.DocValues;
using DocValuesType = Lucene.Net.Index.DocValuesType;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IOUtils = Lucene.Net.Util.IOUtils;
using Int64Values = Lucene.Net.Util.Int64Values;
using MonotonicBlockPackedReader = Lucene.Net.Util.Packed.MonotonicBlockPackedReader;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using RandomAccessOrds = Lucene.Net.Index.RandomAccessOrds;
using SegmentReadState = Lucene.Net.Index.SegmentReadState;
using SortedDocValues = Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues;
using TermsEnum = Lucene.Net.Index.TermsEnum;
/// <summary>
/// Reader for <see cref="Lucene45DocValuesFormat"/>. </summary>
public class Lucene45DocValuesProducer : DocValuesProducer, IDisposable
{
private readonly IDictionary<int, NumericEntry> numerics;
private readonly IDictionary<int, BinaryEntry> binaries;
private readonly IDictionary<int, SortedSetEntry> sortedSets;
private readonly IDictionary<int, NumericEntry> ords;
private readonly IDictionary<int, NumericEntry> ordIndexes;
private readonly AtomicInt64 ramBytesUsed;
private readonly IndexInput data;
private readonly int maxDoc;
private readonly int version;
// memory-resident structures
private readonly IDictionary<int, MonotonicBlockPackedReader> addressInstances = new Dictionary<int, MonotonicBlockPackedReader>();
private readonly IDictionary<int, MonotonicBlockPackedReader> ordIndexInstances = new Dictionary<int, MonotonicBlockPackedReader>();
/// <summary>
/// Expert: instantiates a new reader. </summary>
protected internal Lucene45DocValuesProducer(SegmentReadState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension)
{
string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension);
// read in the entries from the metadata file.
ChecksumIndexInput @in = state.Directory.OpenChecksumInput(metaName, state.Context);
this.maxDoc = state.SegmentInfo.DocCount;
bool success = false;
try
{
version = CodecUtil.CheckHeader(@in, metaCodec, Lucene45DocValuesFormat.VERSION_START, Lucene45DocValuesFormat.VERSION_CURRENT);
numerics = new Dictionary<int, NumericEntry>();
ords = new Dictionary<int, NumericEntry>();
ordIndexes = new Dictionary<int, NumericEntry>();
binaries = new Dictionary<int, BinaryEntry>();
sortedSets = new Dictionary<int, SortedSetEntry>();
ReadFields(@in, state.FieldInfos);
if (version >= Lucene45DocValuesFormat.VERSION_CHECKSUM)
{
CodecUtil.CheckFooter(@in);
}
else
{
#pragma warning disable 612, 618
CodecUtil.CheckEOF(@in);
#pragma warning restore 612, 618
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(@in);
}
else
{
IOUtils.DisposeWhileHandlingException(@in);
}
}
success = false;
try
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension);
data = state.Directory.OpenInput(dataName, state.Context);
int version2 = CodecUtil.CheckHeader(data, dataCodec, Lucene45DocValuesFormat.VERSION_START, Lucene45DocValuesFormat.VERSION_CURRENT);
if (version != version2)
{
throw new Exception("Format versions mismatch");
}
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(this.data);
}
}
ramBytesUsed = new AtomicInt64(RamUsageEstimator.ShallowSizeOfInstance(this.GetType()));
}
private void ReadSortedField(int fieldNumber, IndexInput meta, FieldInfos infos)
{
// sorted = binary + numeric
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.BINARY)
{
throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
BinaryEntry b = ReadBinaryEntry(meta);
binaries[fieldNumber] = b;
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.NUMERIC)
{
throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
NumericEntry n = ReadNumericEntry(meta);
ords[fieldNumber] = n;
}
private void ReadSortedSetFieldWithAddresses(int fieldNumber, IndexInput meta, FieldInfos infos)
{
// sortedset = binary + numeric (addresses) + ordIndex
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.BINARY)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
BinaryEntry b = ReadBinaryEntry(meta);
binaries[fieldNumber] = b;
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.NUMERIC)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
NumericEntry n1 = ReadNumericEntry(meta);
ords[fieldNumber] = n1;
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.NUMERIC)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
NumericEntry n2 = ReadNumericEntry(meta);
ordIndexes[fieldNumber] = n2;
}
private void ReadFields(IndexInput meta, FieldInfos infos)
{
int fieldNumber = meta.ReadVInt32();
while (fieldNumber != -1)
{
// check should be: infos.fieldInfo(fieldNumber) != null, which incorporates negative check
// but docvalues updates are currently buggy here (loading extra stuff, etc): LUCENE-5616
if (fieldNumber < 0)
{
// trickier to validate more: because we re-use for norms, because we use multiple entries
// for "composite" types like sortedset, etc.
throw new Exception("Invalid field number: " + fieldNumber + " (resource=" + meta + ")");
}
byte type = meta.ReadByte();
if (type == Lucene45DocValuesFormat.NUMERIC)
{
numerics[fieldNumber] = ReadNumericEntry(meta);
}
else if (type == Lucene45DocValuesFormat.BINARY)
{
BinaryEntry b = ReadBinaryEntry(meta);
binaries[fieldNumber] = b;
}
else if (type == Lucene45DocValuesFormat.SORTED)
{
ReadSortedField(fieldNumber, meta, infos);
}
else if (type == Lucene45DocValuesFormat.SORTED_SET)
{
SortedSetEntry ss = ReadSortedSetEntry(meta);
sortedSets[fieldNumber] = ss;
if (ss.Format == Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES)
{
ReadSortedSetFieldWithAddresses(fieldNumber, meta, infos);
}
else if (ss.Format == Lucene45DocValuesConsumer.SORTED_SET_SINGLE_VALUED_SORTED)
{
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.SORTED)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
ReadSortedField(fieldNumber, meta, infos);
}
else
{
throw new Exception();
}
}
else
{
throw new Exception("invalid type: " + type + ", resource=" + meta);
}
fieldNumber = meta.ReadVInt32();
}
}
internal static NumericEntry ReadNumericEntry(IndexInput meta)
{
NumericEntry entry = new NumericEntry();
entry.format = meta.ReadVInt32();
entry.missingOffset = meta.ReadInt64();
entry.PackedInt32sVersion = meta.ReadVInt32();
entry.Offset = meta.ReadInt64();
entry.Count = meta.ReadVInt64();
entry.BlockSize = meta.ReadVInt32();
switch (entry.format)
{
case Lucene45DocValuesConsumer.GCD_COMPRESSED:
entry.minValue = meta.ReadInt64();
entry.gcd = meta.ReadInt64();
break;
case Lucene45DocValuesConsumer.TABLE_COMPRESSED:
if (entry.Count > int.MaxValue)
{
throw new Exception("Cannot use TABLE_COMPRESSED with more than MAX_VALUE values, input=" + meta);
}
int uniqueValues = meta.ReadVInt32();
if (uniqueValues > 256)
{
throw new Exception("TABLE_COMPRESSED cannot have more than 256 distinct values, input=" + meta);
}
entry.table = new long[uniqueValues];
for (int i = 0; i < uniqueValues; ++i)
{
entry.table[i] = meta.ReadInt64();
}
break;
case Lucene45DocValuesConsumer.DELTA_COMPRESSED:
break;
default:
throw new Exception("Unknown format: " + entry.format + ", input=" + meta);
}
return entry;
}
internal static BinaryEntry ReadBinaryEntry(IndexInput meta)
{
BinaryEntry entry = new BinaryEntry();
entry.format = meta.ReadVInt32();
entry.missingOffset = meta.ReadInt64();
entry.minLength = meta.ReadVInt32();
entry.maxLength = meta.ReadVInt32();
entry.Count = meta.ReadVInt64();
entry.offset = meta.ReadInt64();
switch (entry.format)
{
case Lucene45DocValuesConsumer.BINARY_FIXED_UNCOMPRESSED:
break;
case Lucene45DocValuesConsumer.BINARY_PREFIX_COMPRESSED:
entry.AddressInterval = meta.ReadVInt32();
entry.AddressesOffset = meta.ReadInt64();
entry.PackedInt32sVersion = meta.ReadVInt32();
entry.BlockSize = meta.ReadVInt32();
break;
case Lucene45DocValuesConsumer.BINARY_VARIABLE_UNCOMPRESSED:
entry.AddressesOffset = meta.ReadInt64();
entry.PackedInt32sVersion = meta.ReadVInt32();
entry.BlockSize = meta.ReadVInt32();
break;
default:
throw new Exception("Unknown format: " + entry.format + ", input=" + meta);
}
return entry;
}
internal virtual SortedSetEntry ReadSortedSetEntry(IndexInput meta)
{
SortedSetEntry entry = new SortedSetEntry();
if (version >= Lucene45DocValuesFormat.VERSION_SORTED_SET_SINGLE_VALUE_OPTIMIZED)
{
entry.Format = meta.ReadVInt32();
}
else
{
entry.Format = Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES;
}
if (entry.Format != Lucene45DocValuesConsumer.SORTED_SET_SINGLE_VALUED_SORTED && entry.Format != Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES)
{
throw new Exception("Unknown format: " + entry.Format + ", input=" + meta);
}
return entry;
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
NumericEntry entry = numerics[field.Number];
return GetNumeric(entry);
}
public override long RamBytesUsed() => ramBytesUsed;
public override void CheckIntegrity()
{
if (version >= Lucene45DocValuesFormat.VERSION_CHECKSUM)
{
CodecUtil.ChecksumEntireFile(data);
}
}
internal virtual Int64Values GetNumeric(NumericEntry entry)
{
IndexInput data = (IndexInput)this.data.Clone();
data.Seek(entry.Offset);
switch (entry.format)
{
case Lucene45DocValuesConsumer.DELTA_COMPRESSED:
BlockPackedReader reader = new BlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, entry.Count, true);
return reader;
case Lucene45DocValuesConsumer.GCD_COMPRESSED:
long min = entry.minValue;
long mult = entry.gcd;
BlockPackedReader quotientReader = new BlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, entry.Count, true);
return new Int64ValuesAnonymousInnerClassHelper(this, min, mult, quotientReader);
case Lucene45DocValuesConsumer.TABLE_COMPRESSED:
long[] table = entry.table;
int bitsRequired = PackedInt32s.BitsRequired(table.Length - 1);
PackedInt32s.Reader ords = PackedInt32s.GetDirectReaderNoHeader(data, PackedInt32s.Format.PACKED, entry.PackedInt32sVersion, (int)entry.Count, bitsRequired);
return new Int64ValuesAnonymousInnerClassHelper2(this, table, ords);
default:
throw new Exception();
}
}
private class Int64ValuesAnonymousInnerClassHelper : Int64Values
{
private readonly Lucene45DocValuesProducer outerInstance;
private long min;
private long mult;
private BlockPackedReader quotientReader;
public Int64ValuesAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, long min, long mult, BlockPackedReader quotientReader)
{
this.outerInstance = outerInstance;
this.min = min;
this.mult = mult;
this.quotientReader = quotientReader;
}
public override long Get(long id)
{
return min + mult * quotientReader.Get(id);
}
}
private class Int64ValuesAnonymousInnerClassHelper2 : Int64Values
{
private readonly Lucene45DocValuesProducer outerInstance;
private long[] table;
private PackedInt32s.Reader ords;
public Int64ValuesAnonymousInnerClassHelper2(Lucene45DocValuesProducer outerInstance, long[] table, PackedInt32s.Reader ords)
{
this.outerInstance = outerInstance;
this.table = table;
this.ords = ords;
}
public override long Get(long id)
{
return table[(int)ords.Get((int)id)];
}
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
BinaryEntry bytes = binaries[field.Number];
switch (bytes.format)
{
case Lucene45DocValuesConsumer.BINARY_FIXED_UNCOMPRESSED:
return GetFixedBinary(field, bytes);
case Lucene45DocValuesConsumer.BINARY_VARIABLE_UNCOMPRESSED:
return GetVariableBinary(field, bytes);
case Lucene45DocValuesConsumer.BINARY_PREFIX_COMPRESSED:
return GetCompressedBinary(field, bytes);
default:
throw new Exception();
}
}
private BinaryDocValues GetFixedBinary(FieldInfo field, BinaryEntry bytes)
{
IndexInput data = (IndexInput)this.data.Clone();
return new Int64BinaryDocValuesAnonymousInnerClassHelper(this, bytes, data);
}
private class Int64BinaryDocValuesAnonymousInnerClassHelper : Int64BinaryDocValues
{
private readonly Lucene45DocValuesProducer outerInstance;
private Lucene45DocValuesProducer.BinaryEntry bytes;
private IndexInput data;
public Int64BinaryDocValuesAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, Lucene45DocValuesProducer.BinaryEntry bytes, IndexInput data)
{
this.outerInstance = outerInstance;
this.bytes = bytes;
this.data = data;
}
public override void Get(long id, BytesRef result)
{
long address = bytes.offset + id * bytes.maxLength;
try
{
data.Seek(address);
// NOTE: we could have one buffer, but various consumers (e.g. FieldComparerSource)
// assume "they" own the bytes after calling this!
var buffer = new byte[bytes.maxLength];
data.ReadBytes(buffer, 0, buffer.Length);
result.Bytes = buffer;
result.Offset = 0;
result.Length = buffer.Length;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
}
/// <summary>
/// Returns an address instance for variable-length binary values.
/// <para/>
/// @lucene.internal
/// </summary>
protected virtual MonotonicBlockPackedReader GetAddressInstance(IndexInput data, FieldInfo field, BinaryEntry bytes)
{
MonotonicBlockPackedReader addresses;
lock (addressInstances)
{
MonotonicBlockPackedReader addrInstance;
if (!addressInstances.TryGetValue(field.Number, out addrInstance) || addrInstance == null)
{
data.Seek(bytes.AddressesOffset);
addrInstance = new MonotonicBlockPackedReader(data, bytes.PackedInt32sVersion, bytes.BlockSize, bytes.Count, false);
addressInstances[field.Number] = addrInstance;
ramBytesUsed.AddAndGet(addrInstance.RamBytesUsed() + RamUsageEstimator.NUM_BYTES_INT32);
}
addresses = addrInstance;
}
return addresses;
}
private BinaryDocValues GetVariableBinary(FieldInfo field, BinaryEntry bytes)
{
IndexInput data = (IndexInput)this.data.Clone();
MonotonicBlockPackedReader addresses = GetAddressInstance(data, field, bytes);
return new Int64BinaryDocValuesAnonymousInnerClassHelper2(this, bytes, data, addresses);
}
private class Int64BinaryDocValuesAnonymousInnerClassHelper2 : Int64BinaryDocValues
{
private readonly Lucene45DocValuesProducer outerInstance;
private Lucene45DocValuesProducer.BinaryEntry bytes;
private IndexInput data;
private MonotonicBlockPackedReader addresses;
public Int64BinaryDocValuesAnonymousInnerClassHelper2(Lucene45DocValuesProducer outerInstance, Lucene45DocValuesProducer.BinaryEntry bytes, IndexInput data, MonotonicBlockPackedReader addresses)
{
this.outerInstance = outerInstance;
this.bytes = bytes;
this.data = data;
this.addresses = addresses;
}
public override void Get(long id, BytesRef result)
{
long startAddress = bytes.offset + (id == 0 ? 0 : addresses.Get(id - 1));
long endAddress = bytes.offset + addresses.Get(id);
int length = (int)(endAddress - startAddress);
try
{
data.Seek(startAddress);
// NOTE: we could have one buffer, but various consumers (e.g. FieldComparerSource)
// assume "they" own the bytes after calling this!
var buffer = new byte[length];
data.ReadBytes(buffer, 0, buffer.Length);
result.Bytes = buffer;
result.Offset = 0;
result.Length = length;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
}
/// <summary>
/// Returns an address instance for prefix-compressed binary values.
/// <para/>
/// @lucene.internal
/// </summary>
protected virtual MonotonicBlockPackedReader GetIntervalInstance(IndexInput data, FieldInfo field, BinaryEntry bytes)
{
MonotonicBlockPackedReader addresses;
long interval = bytes.AddressInterval;
lock (addressInstances)
{
MonotonicBlockPackedReader addrInstance;
if (!addressInstances.TryGetValue(field.Number, out addrInstance))
{
data.Seek(bytes.AddressesOffset);
long size;
if (bytes.Count % interval == 0)
{
size = bytes.Count / interval;
}
else
{
size = 1L + bytes.Count / interval;
}
addrInstance = new MonotonicBlockPackedReader(data, bytes.PackedInt32sVersion, bytes.BlockSize, size, false);
addressInstances[field.Number] = addrInstance;
ramBytesUsed.AddAndGet(addrInstance.RamBytesUsed() + RamUsageEstimator.NUM_BYTES_INT32);
}
addresses = addrInstance;
}
return addresses;
}
private BinaryDocValues GetCompressedBinary(FieldInfo field, BinaryEntry bytes)
{
IndexInput data = (IndexInput)this.data.Clone();
MonotonicBlockPackedReader addresses = GetIntervalInstance(data, field, bytes);
return new CompressedBinaryDocValues(bytes, addresses, data);
}
public override SortedDocValues GetSorted(FieldInfo field)
{
int valueCount = (int)binaries[field.Number].Count;
BinaryDocValues binary = GetBinary(field);
NumericEntry entry = ords[field.Number];
IndexInput data = (IndexInput)this.data.Clone();
data.Seek(entry.Offset);
BlockPackedReader ordinals = new BlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, entry.Count, true);
return new SortedDocValuesAnonymousInnerClassHelper(this, valueCount, binary, ordinals);
}
private class SortedDocValuesAnonymousInnerClassHelper : SortedDocValues
{
private readonly Lucene45DocValuesProducer outerInstance;
private int valueCount;
private BinaryDocValues binary;
private BlockPackedReader ordinals;
public SortedDocValuesAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, int valueCount, BinaryDocValues binary, BlockPackedReader ordinals)
{
this.outerInstance = outerInstance;
this.valueCount = valueCount;
this.binary = binary;
this.ordinals = ordinals;
}
public override int GetOrd(int docID)
{
return (int)ordinals.Get(docID);
}
public override void LookupOrd(int ord, BytesRef result)
{
binary.Get(ord, result);
}
public override int ValueCount => valueCount;
public override int LookupTerm(BytesRef key)
{
if (binary is CompressedBinaryDocValues)
{
return (int)((CompressedBinaryDocValues)binary).LookupTerm(key);
}
else
{
return base.LookupTerm(key);
}
}
public override TermsEnum GetTermsEnum()
{
if (binary is CompressedBinaryDocValues)
{
return ((CompressedBinaryDocValues)binary).GetTermsEnum();
}
else
{
return base.GetTermsEnum();
}
}
}
/// <summary>
/// Returns an address instance for sortedset ordinal lists.
/// <para/>
/// @lucene.internal
/// </summary>
protected virtual MonotonicBlockPackedReader GetOrdIndexInstance(IndexInput data, FieldInfo field, NumericEntry entry)
{
MonotonicBlockPackedReader ordIndex;
lock (ordIndexInstances)
{
MonotonicBlockPackedReader ordIndexInstance;
if (!ordIndexInstances.TryGetValue(field.Number, out ordIndexInstance))
{
data.Seek(entry.Offset);
ordIndexInstance = new MonotonicBlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, entry.Count, false);
ordIndexInstances[field.Number] = ordIndexInstance;
ramBytesUsed.AddAndGet(ordIndexInstance.RamBytesUsed() + RamUsageEstimator.NUM_BYTES_INT32);
}
ordIndex = ordIndexInstance;
}
return ordIndex;
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
SortedSetEntry ss = sortedSets[field.Number];
if (ss.Format == Lucene45DocValuesConsumer.SORTED_SET_SINGLE_VALUED_SORTED)
{
SortedDocValues values = GetSorted(field);
return DocValues.Singleton(values);
}
else if (ss.Format != Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES)
{
throw new Exception();
}
IndexInput data = (IndexInput)this.data.Clone();
long valueCount = binaries[field.Number].Count;
// we keep the byte[]s and list of ords on disk, these could be large
Int64BinaryDocValues binary = (Int64BinaryDocValues)GetBinary(field);
Int64Values ordinals = GetNumeric(ords[field.Number]);
// but the addresses to the ord stream are in RAM
MonotonicBlockPackedReader ordIndex = GetOrdIndexInstance(data, field, ordIndexes[field.Number]);
return new RandomAccessOrdsAnonymousInnerClassHelper(this, valueCount, binary, ordinals, ordIndex);
}
private class RandomAccessOrdsAnonymousInnerClassHelper : RandomAccessOrds
{
private readonly Lucene45DocValuesProducer outerInstance;
private long valueCount;
private Lucene45DocValuesProducer.Int64BinaryDocValues binary;
private Int64Values ordinals;
private MonotonicBlockPackedReader ordIndex;
public RandomAccessOrdsAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, long valueCount, Lucene45DocValuesProducer.Int64BinaryDocValues binary, Int64Values ordinals, MonotonicBlockPackedReader ordIndex)
{
this.outerInstance = outerInstance;
this.valueCount = valueCount;
this.binary = binary;
this.ordinals = ordinals;
this.ordIndex = ordIndex;
}
internal long startOffset;
internal long offset;
internal long endOffset;
public override long NextOrd()
{
if (offset == endOffset)
{
return NO_MORE_ORDS;
}
else
{
long ord = ordinals.Get(offset);
offset++;
return ord;
}
}
public override void SetDocument(int docID)
{
startOffset = offset = (docID == 0 ? 0 : ordIndex.Get(docID - 1));
endOffset = ordIndex.Get(docID);
}
public override void LookupOrd(long ord, BytesRef result)
{
binary.Get(ord, result);
}
public override long ValueCount => valueCount;
public override long LookupTerm(BytesRef key)
{
if (binary is CompressedBinaryDocValues)
{
return ((CompressedBinaryDocValues)binary).LookupTerm(key);
}
else
{
return base.LookupTerm(key);
}
}
public override TermsEnum GetTermsEnum()
{
if (binary is CompressedBinaryDocValues)
{
return ((CompressedBinaryDocValues)binary).GetTermsEnum();
}
else
{
return base.GetTermsEnum();
}
}
public override long OrdAt(int index)
{
return ordinals.Get(startOffset + index);
}
public override int Cardinality()
{
return (int)(endOffset - startOffset);
}
}
private IBits GetMissingBits(long offset)
{
if (offset == -1)
{
return new Bits.MatchAllBits(maxDoc);
}
else
{
IndexInput @in = (IndexInput)data.Clone();
return new BitsAnonymousInnerClassHelper(this, offset, @in);
}
}
private class BitsAnonymousInnerClassHelper : IBits
{
private readonly Lucene45DocValuesProducer outerInstance;
private long offset;
private IndexInput @in;
public BitsAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, long offset, IndexInput @in)
{
this.outerInstance = outerInstance;
this.offset = offset;
this.@in = @in;
}
public virtual bool Get(int index)
{
try
{
@in.Seek(offset + (index >> 3));
return (@in.ReadByte() & (1 << (index & 7))) != 0;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
public virtual int Length => outerInstance.maxDoc;
}
public override IBits GetDocsWithField(FieldInfo field)
{
switch (field.DocValuesType)
{
case DocValuesType.SORTED_SET:
return DocValues.DocsWithValue(GetSortedSet(field), maxDoc);
case DocValuesType.SORTED:
return DocValues.DocsWithValue(GetSorted(field), maxDoc);
case DocValuesType.BINARY:
BinaryEntry be = binaries[field.Number];
return GetMissingBits(be.missingOffset);
case DocValuesType.NUMERIC:
NumericEntry ne = numerics[field.Number];
return GetMissingBits(ne.missingOffset);
default:
throw new InvalidOperationException();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
data.Dispose();
}
/// <summary>
/// Metadata entry for a numeric docvalues field. </summary>
protected internal class NumericEntry
{
internal NumericEntry()
{
}
/// <summary>
/// Offset to the bitset representing docsWithField, or -1 if no documents have missing values. </summary>
internal long missingOffset;
/// <summary>
/// Offset to the actual numeric values. </summary>
public long Offset { get; set; }
internal int format;
/// <summary>
/// Packed <see cref="int"/>s version used to encode these numerics.
/// <para/>
/// NOTE: This was packedIntsVersion (field) in Lucene
/// </summary>
public int PackedInt32sVersion { get; set; }
/// <summary>
/// Count of values written. </summary>
public long Count { get; set; }
/// <summary>
/// Packed <see cref="int"/>s blocksize. </summary>
public int BlockSize { get; set; }
internal long minValue;
internal long gcd;
internal long[] table;
}
/// <summary>
/// Metadata entry for a binary docvalues field. </summary>
protected internal class BinaryEntry
{
internal BinaryEntry()
{
}
/// <summary>
/// Offset to the bitset representing docsWithField, or -1 if no documents have missing values. </summary>
internal long missingOffset;
/// <summary>
/// Offset to the actual binary values. </summary>
internal long offset;
internal int format;
/// <summary>
/// Count of values written. </summary>
public long Count { get; set; }
internal int minLength;
internal int maxLength;
/// <summary>
/// Offset to the addressing data that maps a value to its slice of the <see cref="T:byte[]"/>. </summary>
public long AddressesOffset { get; set; }
/// <summary>
/// Interval of shared prefix chunks (when using prefix-compressed binary). </summary>
public long AddressInterval { get; set; }
/// <summary>
/// Packed ints version used to encode addressing information.
/// <para/>
/// NOTE: This was packedIntsVersion (field) in Lucene.
/// </summary>
public int PackedInt32sVersion { get; set; }
/// <summary>
/// Packed ints blocksize. </summary>
public int BlockSize { get; set; }
}
/// <summary>
/// Metadata entry for a sorted-set docvalues field. </summary>
protected internal class SortedSetEntry
{
internal SortedSetEntry()
{
}
internal int Format { get; set; }
}
// internally we compose complex dv (sorted/sortedset) from other ones
/// <summary>
/// NOTE: This was LongBinaryDocValues in Lucene.
/// </summary>
internal abstract class Int64BinaryDocValues : BinaryDocValues
{
public override sealed void Get(int docID, BytesRef result)
{
Get((long)docID, result);
}
public abstract void Get(long id, BytesRef result);
}
// in the compressed case, we add a few additional operations for
// more efficient reverse lookup and enumeration
internal class CompressedBinaryDocValues : Int64BinaryDocValues
{
internal readonly BinaryEntry bytes;
internal readonly long interval;
internal readonly long numValues;
internal readonly long numIndexValues;
internal readonly MonotonicBlockPackedReader addresses;
internal readonly IndexInput data;
internal readonly TermsEnum termsEnum;
public CompressedBinaryDocValues(BinaryEntry bytes, MonotonicBlockPackedReader addresses, IndexInput data)
{
this.bytes = bytes;
this.interval = bytes.AddressInterval;
this.addresses = addresses;
this.data = data;
this.numValues = bytes.Count;
this.numIndexValues = addresses.Count;
this.termsEnum = GetTermsEnum(data);
}
public override void Get(long id, BytesRef result)
{
try
{
termsEnum.SeekExact(id);
BytesRef term = termsEnum.Term;
result.Bytes = term.Bytes;
result.Offset = term.Offset;
result.Length = term.Length;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
internal virtual long LookupTerm(BytesRef key)
{
try
{
TermsEnum.SeekStatus status = termsEnum.SeekCeil(key);
if (status == TermsEnum.SeekStatus.END)
{
return -numValues - 1;
}
else if (status == TermsEnum.SeekStatus.FOUND)
{
return termsEnum.Ord;
}
else
{
return -termsEnum.Ord - 1;
}
}
catch (IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
internal virtual TermsEnum GetTermsEnum()
{
try
{
return GetTermsEnum((IndexInput)data.Clone());
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
internal virtual TermsEnum GetTermsEnum(IndexInput input)
{
input.Seek(bytes.offset);
return new TermsEnumAnonymousInnerClassHelper(this, input);
}
private class TermsEnumAnonymousInnerClassHelper : TermsEnum
{
private readonly CompressedBinaryDocValues outerInstance;
private readonly IndexInput input;
public TermsEnumAnonymousInnerClassHelper(CompressedBinaryDocValues outerInstance, IndexInput input)
{
this.outerInstance = outerInstance;
this.input = input;
currentOrd = -1;
termBuffer = new BytesRef(outerInstance.bytes.maxLength < 0 ? 0 : outerInstance.bytes.maxLength);
term = new BytesRef();
}
private long currentOrd;
// TODO: maxLength is negative when all terms are merged away...
private readonly BytesRef termBuffer;
private readonly BytesRef term;
// LUCENENET specific - factored out DoNext() and made into MoveNext()
public override bool MoveNext()
{
if (++currentOrd >= outerInstance.numValues)
{
return false;
}
else
{
int start = input.ReadVInt32();
int suffix = input.ReadVInt32();
input.ReadBytes(termBuffer.Bytes, start, suffix);
termBuffer.Length = start + suffix;
SetTerm();
return true;
}
}
[Obsolete("Use MoveNext() and Term instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override BytesRef Next()
{
if (MoveNext())
return term;
return null;
}
public override TermsEnum.SeekStatus SeekCeil(BytesRef text)
{
// binary-search just the index values to find the block,
// then scan within the block
long low = 0;
long high = outerInstance.numIndexValues - 1;
while (low <= high)
{
long mid = (int)((uint)(low + high) >> 1);
DoSeek(mid * outerInstance.interval);
int cmp = termBuffer.CompareTo(text);
if (cmp < 0)
{
low = mid + 1;
}
else if (cmp > 0)
{
high = mid - 1;
}
else
{
// we got lucky, found an indexed term
SetTerm();
return TermsEnum.SeekStatus.FOUND;
}
}
if (outerInstance.numIndexValues == 0)
{
return TermsEnum.SeekStatus.END;
}
// block before insertion point
long block = low - 1;
DoSeek(block < 0 ? -1 : block * outerInstance.interval);
while (MoveNext())
{
int cmp = termBuffer.CompareTo(text);
if (cmp == 0)
{
SetTerm();
return TermsEnum.SeekStatus.FOUND;
}
else if (cmp > 0)
{
SetTerm();
return TermsEnum.SeekStatus.NOT_FOUND;
}
}
return TermsEnum.SeekStatus.END;
}
public override void SeekExact(long ord)
{
DoSeek(ord);
SetTerm();
}
private void DoSeek(long ord)
{
long block = ord / outerInstance.interval;
if (ord >= currentOrd && block == currentOrd / outerInstance.interval)
{
// seek within current block
}
else
{
// position before start of block
currentOrd = ord - ord % outerInstance.interval - 1;
input.Seek(outerInstance.bytes.offset + outerInstance.addresses.Get(block));
}
while (currentOrd < ord)
{
MoveNext();
}
}
private void SetTerm()
{
// TODO: is there a cleaner way
term.Bytes = new byte[termBuffer.Length];
term.Offset = 0;
term.CopyBytes(termBuffer);
}
public override BytesRef Term => term;
public override long Ord => currentOrd;
public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer;
public override int DocFreq => throw new NotSupportedException();
public override long TotalTermFreq => -1;
public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
throw new NotSupportedException();
}
public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
throw new NotSupportedException();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using Moritz.Xml;
namespace Moritz.Symbols
{
/// <summary>
/// Barlines maintain their line and drawObjects metrics separately.
/// The lines are drawn using implementations of an abstract function,
/// The drawObjects are drawn by calling BarlineDrawObjectsMetrics.WriteSVG().
/// </summary>
public abstract class Barline : AnchorageSymbol
{
protected Barline (Voice voice)
: base(voice)
{
}
/// <summary>
/// This function should not be called.
/// Call the other WriteSVG(...) function to write the barline's vertical line(s),
/// and WriteDrawObjectsSVG(...) to write any DrawObjects.
/// </summary>
public override void WriteSVG(SvgWriter w)
{
throw new ApplicationException();
}
public abstract void WriteSVG(SvgWriter w, float topStafflineY, float bottomStafflineY, bool isEndOfSystem);
public abstract void CreateMetrics(Graphics graphics);
protected void SetCommonMetrics(Graphics graphics, List<DrawObject> drawObjects)
{
StaffMetrics staffMetrics = Voice.Staff.Metrics;
foreach(DrawObject drawObject in DrawObjects)
{
if(drawObject is StaffNameText staffNameText)
{
CSSObjectClass staffClass = (Voice is InputVoice) ? CSSObjectClass.inputStaffName : CSSObjectClass.staffName;
StaffNameMetrics = new StaffNameMetrics(staffClass, graphics, staffNameText.TextInfo);
// move the staffname vertically to the middle of this staff
float staffheight = staffMetrics.StafflinesBottom - staffMetrics.StafflinesTop;
float dy = (staffheight * 0.5F) + (Gap * 0.8F);
StaffNameMetrics.Move(0F, dy);
}
if(drawObject is FramedBarNumberText framedBarNumberText)
{
BarnumberMetrics = new BarnumberMetrics(graphics, framedBarNumberText.TextInfo, framedBarNumberText.FrameInfo);
// move the bar number to its default (=lowest) position above this staff.
BarnumberMetrics.Move(0F, staffMetrics.StafflinesTop - BarnumberMetrics.Bottom - (Gap * 3));
}
}
}
public abstract void AddMetricsToEdge(HorizontalEdge horizontalEdge);
protected void AddBasicMetricsToEdge(HorizontalEdge horizontalEdge)
{
if(StaffNameMetrics != null)
{
horizontalEdge.Add(StaffNameMetrics);
}
if(BarnumberMetrics != null)
{
horizontalEdge.Add(BarnumberMetrics);
}
}
protected void MoveBarnumberAboveRegionBox(BarnumberMetrics barnumberMetrics, FramedRegionInfoMetrics regionInfoMetrics)
{
if(barnumberMetrics != null && regionInfoMetrics != null)
{
float padding = Gap * 1.5F;
float shift = barnumberMetrics.Bottom - regionInfoMetrics.Top + padding;
barnumberMetrics.Move(0, -shift);
}
}
protected void MoveFramedTextBottomToDefaultPosition(Metrics framedTextMetrics)
{
float staffTop = this.Voice.Staff.Metrics.StafflinesTop;
float defaultBottom = staffTop - (Gap * 3);
if(framedTextMetrics != null)
{
framedTextMetrics.Move(0, defaultBottom - framedTextMetrics.Bottom);
}
}
protected void MoveFramedTextAboveNoteObjects(Metrics framedTextMetrics, List<NoteObject> fixedNoteObjects)
{
if(framedTextMetrics != null)
{
float bottomPadding = Gap * 1.5F;
float xPadding = Gap * 4;
PaddedMetrics paddedMetrics = new PaddedMetrics(framedTextMetrics, 0F, xPadding, bottomPadding, xPadding);
foreach(NoteObject noteObject in fixedNoteObjects)
{
int overlaps = OverlapsHorizontally(paddedMetrics, noteObject);
if(overlaps == 0)
{
MovePaddedMetricsAboveNoteObject(paddedMetrics, noteObject);
}
else if(overlaps == 1) // noteObject is left of framedText
{
if(noteObject is ChordSymbol chordSymbol)
{
if(chordSymbol.Stem.Direction == VerticalDir.up && chordSymbol.BeamBlock != null)
{
MoveFramedTextAboveBeamBlock(framedTextMetrics, chordSymbol.BeamBlock);
}
else if(chordSymbol.ChordMetrics.NoteheadExtendersMetrics != null)
{
MoveFramedTextAboveNoteheadExtenders(framedTextMetrics, chordSymbol.ChordMetrics.NoteheadExtendersMetrics);
}
}
}
else if(overlaps == -1) // noteObject is right of framed text, so we need look no further in these noteObjects.
{
break;
}
}
}
}
/// <summary>
/// returns
/// -1 if metrics is entirely to the left of the fixedNoteObject;
/// 0 if metrics overlaps the fixedNoteObject;
/// 1 if metrics is entirely to the right of the fixedNoteObject;
/// </summary>
/// <returns></returns>
private int OverlapsHorizontally(Metrics metrics, NoteObject fixedNoteObject)
{
int rval = 0;
Metrics fixedMetrics = fixedNoteObject.Metrics;
if(metrics.Right < fixedMetrics.Left)
{
rval = -1;
}
else if(metrics.Left > fixedMetrics.Right)
{
rval = 1;
}
return rval;
}
/// <summary>
/// Move paddedMetrics above the fixedNoteObject if it is not already.
/// </summary>
private void MovePaddedMetricsAboveNoteObject(PaddedMetrics paddedMetrics, NoteObject fixedNoteObject)
{
float verticalOverlap = 0F;
if(fixedNoteObject.Metrics is ChordMetrics chordMetrics)
{
verticalOverlap = chordMetrics.OverlapHeight(paddedMetrics, 0F);
}
else if(fixedNoteObject.Metrics is RestMetrics restMetrics)
{
verticalOverlap = restMetrics.OverlapHeight(paddedMetrics, 0F);
}
else if(!(fixedNoteObject is Barline))
{
verticalOverlap = fixedNoteObject.Metrics.OverlapHeight(paddedMetrics, 0F);
}
if(verticalOverlap > 0)
{
verticalOverlap = (verticalOverlap > paddedMetrics.BottomPadding) ? verticalOverlap : paddedMetrics.BottomPadding;
paddedMetrics.Move(0F, -verticalOverlap);
}
}
private void MoveFramedTextAboveBeamBlock(Metrics framedTextMetrics, BeamBlock beamBlock)
{
float padding = Gap * 1.5F;
float verticalOverlap = beamBlock.OverlapHeight(framedTextMetrics, padding);
if(verticalOverlap > 0)
{
verticalOverlap = (verticalOverlap > padding) ? verticalOverlap : padding;
framedTextMetrics.Move(0F, -verticalOverlap );
}
}
private void MoveFramedTextAboveNoteheadExtenders(Metrics framedTextMetrics, List<NoteheadExtenderMetrics> noteheadExtendersMetrics)
{
float padding = Gap * 1.5F;
int indexOfTopExtender = 0;
for(int i = 1; i < noteheadExtendersMetrics.Count; ++i)
{
indexOfTopExtender = (noteheadExtendersMetrics[indexOfTopExtender].Top < noteheadExtendersMetrics[i].Top) ? indexOfTopExtender : i;
}
NoteheadExtenderMetrics topExtender = noteheadExtendersMetrics[indexOfTopExtender];
float verticalOverlap = topExtender.OverlapHeight(framedTextMetrics, padding);
if(verticalOverlap > 0)
{
verticalOverlap = (verticalOverlap > padding) ? verticalOverlap : padding;
framedTextMetrics.Move(0F, -(verticalOverlap));
}
}
/// <summary>
/// This virtual function writes the staff name and barnumber to the SVG file (if they are present).
/// Overrides write the region info (if present).
/// The barline itself is drawn when the system (and staff edges) is complete.
/// </summary>
public virtual void WriteDrawObjectsSVG(SvgWriter w)
{
if(StaffNameMetrics != null)
{
StaffNameMetrics.WriteSVG(w);
}
if(BarnumberMetrics != null)
{
BarnumberMetrics.WriteSVG(w);
}
}
protected void SetDrawObjects(List<DrawObject> drawObjects)
{
DrawObjects.Clear();
foreach(DrawObject drawObject in drawObjects)
{
drawObject.Container = this;
DrawObjects.Add(drawObject);
}
}
internal virtual void AddAncilliaryMetricsTo(StaffMetrics staffMetrics)
{
if(StaffNameMetrics != null)
{
staffMetrics.Add(StaffNameMetrics);
}
if(BarnumberMetrics != null)
{
staffMetrics.Add(BarnumberMetrics);
}
}
internal abstract void AlignFramedTextsXY(List<NoteObject> noteObjects0);
protected void AlignBarnumberX()
{
if(BarnumberMetrics != null)
{
BarnumberMetrics.Move(Barline_LineMetrics.OriginX - BarnumberMetrics.OriginX, 0);
}
}
public Metrics Barline_LineMetrics = null;
public StaffNameMetrics StaffNameMetrics = null;
public BarnumberMetrics BarnumberMetrics = null;
/// <summary>
/// Default is true
/// </summary>
public bool IsVisible = true;
private PageFormat PageFormat { get { return Voice.Staff.SVGSystem.Score.PageFormat; } }
protected float StafflineStrokeWidth { get { return PageFormat.StafflineStemStrokeWidth; } }
protected float ThinStrokeWidth { get { return PageFormat.ThinBarlineStrokeWidth; } }
protected float NormalStrokeWidth { get { return PageFormat.NormalBarlineStrokeWidth; } }
protected float ThickStrokeWidth { get { return PageFormat.ThickBarlineStrokeWidth; } }
protected float DoubleBarPadding { get { return PageFormat.ThickBarlineStrokeWidth * 0.75F; } }
protected float Gap { get { return PageFormat.Gap; } }
protected float TopY(float topStafflineY, bool isEndOfSystem)
{
float topY = topStafflineY;
if(isEndOfSystem)
{
float halfStafflineWidth = (StafflineStrokeWidth / 2);
topY -= halfStafflineWidth;
}
return topY;
}
protected float BottomY(float bottomStafflineY, bool isEndOfSystem)
{
float bottomY = bottomStafflineY;
if(isEndOfSystem)
{
float halfStafflineWidth = (StafflineStrokeWidth / 2);
bottomY += halfStafflineWidth;
}
return bottomY;
}
}
/// <summary>
/// A barline which is a single, thin line. OriginX is the line's x-coordinate.
/// </summary>
public class NormalBarline : Barline
{
public NormalBarline(Voice voice)
: base(voice)
{
}
/// <summary>
/// Writes out the barline's vertical line(s).
/// May be called twice per staff.barline:
/// 1. for the range between top and bottom stafflines (if Barline.Visible is true)
/// 2. for the range between the staff's lower edge and the next staff's upper edge
/// (if the staff's lower neighbour is in the same group)
/// </summary>
/// <param name="w"></param>
public override void WriteSVG(SvgWriter w, float topStafflineY, float bottomStafflineY, bool isEndOfSystem)
{
float topY = TopY(topStafflineY, isEndOfSystem);
float bottomY = BottomY(bottomStafflineY, isEndOfSystem);
w.SvgLine(CSSObjectClass.normalBarline, this.Barline_LineMetrics.OriginX, topY, this.Barline_LineMetrics.OriginX, bottomY);
}
public override string ToString()
{
return "normalBarline: ";
}
public override void AddMetricsToEdge(HorizontalEdge horizontalEdge)
{
AddBasicMetricsToEdge(horizontalEdge);
}
internal override void AlignFramedTextsXY(List<NoteObject> fixedNoteObjects)
{
#region alignX
base.AlignBarnumberX();
#endregion
MoveFramedTextAboveNoteObjects(BarnumberMetrics, fixedNoteObjects);
}
public override void CreateMetrics(Graphics graphics)
{
Barline_LineMetrics = new Barline_LineMetrics(-(NormalStrokeWidth / 2F), (NormalStrokeWidth / 2F));
SetCommonMetrics(graphics, DrawObjects);
}
internal override void AddAncilliaryMetricsTo(StaffMetrics metrics)
{
base.AddAncilliaryMetricsTo(metrics);
}
}
/// <summary>
/// A barline whose 2 lines are (left to right) thick then thin. OriginX is the thick line's x-coordinate.
/// </summary>
public class StartRegionBarline : Barline
{
public StartRegionBarline(Voice voice, List<DrawObject> drawObjects)
: base(voice)
{
SetDrawObjects(drawObjects);
}
/// <summary>
/// Writes out the barline's vertical line(s).
/// May be called twice per staff.barline:
/// 1. for the range between top and bottom stafflines (if Barline.Visible is true)
/// 2. for the range between the staff's lower edge and the next staff's upper edge
/// (if the staff's lower neighbour is in the same group)
/// </summary>
/// <param name="w"></param>
public override void WriteSVG(SvgWriter w, float topStafflineY, float bottomStafflineY, bool isEndOfSystem)
{
float topY = TopY(topStafflineY, isEndOfSystem);
float bottomY = BottomY(bottomStafflineY, isEndOfSystem);
float thickLeftLineOriginX = Barline_LineMetrics.OriginX;
w.SvgStartGroup(CSSObjectClass.startRegionBarline.ToString());
w.SvgLine(CSSObjectClass.thickBarline, thickLeftLineOriginX, topY, thickLeftLineOriginX, bottomY);
float thinRightLineOriginX = thickLeftLineOriginX + (ThickStrokeWidth / 2F) + DoubleBarPadding + (ThinStrokeWidth / 2F);
w.SvgLine(CSSObjectClass.thinBarline, thinRightLineOriginX, topY, thinRightLineOriginX, bottomY);
w.SvgEndGroup();
}
/// <summary>
/// This function writes the staff name, barnumber and region info to the SVG file (if they are present).
/// The barline itself is drawn when the system (and staff edges) is complete.
/// </summary>
public override void WriteDrawObjectsSVG(SvgWriter w)
{
base.WriteDrawObjectsSVG(w);
if(FramedRegionStartTextMetrics != null)
{
FramedRegionStartTextMetrics.WriteSVG(w);
}
}
public override void AddMetricsToEdge(HorizontalEdge horizontalEdge)
{
if(FramedRegionStartTextMetrics != null)
{
horizontalEdge.Add(FramedRegionStartTextMetrics);
}
AddBasicMetricsToEdge(horizontalEdge);
}
public override string ToString()
{
return "startRegionBarline: ";
}
internal override void AlignFramedTextsXY(List<NoteObject> fixedNoteObjects)
{
#region alignX
base.AlignBarnumberX();
float originX = Barline_LineMetrics.OriginX;
if(FramedRegionStartTextMetrics != null)
{
FramedRegionStartTextMetrics.Move(originX - FramedRegionStartTextMetrics.Left, 0);
}
#endregion
MoveFramedTextBottomToDefaultPosition(FramedRegionStartTextMetrics);
MoveFramedTextAboveNoteObjects(FramedRegionStartTextMetrics, fixedNoteObjects);
MoveFramedTextAboveNoteObjects(BarnumberMetrics, fixedNoteObjects);
MoveBarnumberAboveRegionBox(BarnumberMetrics, FramedRegionStartTextMetrics);
}
public override void CreateMetrics(Graphics graphics)
{
float leftEdge = -(ThickStrokeWidth / 2F);
float rightEdge = (ThickStrokeWidth / 2F) + DoubleBarPadding + ThinStrokeWidth;
Barline_LineMetrics = new Barline_LineMetrics(leftEdge, rightEdge, CSSObjectClass.thinBarline, CSSObjectClass.thickBarline);
SetCommonMetrics(graphics, DrawObjects);
foreach(DrawObject drawObject in DrawObjects)
{
if(drawObject is FramedRegionStartText frst)
{
FramedRegionStartTextMetrics = new FramedRegionInfoMetrics(graphics, frst.Texts, frst.FrameInfo);
break;
}
}
}
internal override void AddAncilliaryMetricsTo(StaffMetrics staffMetrics)
{
base.AddAncilliaryMetricsTo(staffMetrics);
if(FramedRegionStartTextMetrics != null)
{
staffMetrics.Add(FramedRegionStartTextMetrics);
}
}
public FramedRegionInfoMetrics FramedRegionStartTextMetrics = null;
}
/// <summary>
/// A barline whose 2 lines are (left to right) thin then thick. OriginX is the thick line's x-coordinate.
/// </summary>
public class EndRegionBarline : Barline
{
public EndRegionBarline(Voice voice, List<DrawObject> drawObjects)
: base(voice)
{
SetDrawObjects(drawObjects);
}
/// <summary>
/// Writes out the barline's vertical line(s).
/// May be called twice per staff.barline:
/// 1. for the range between top and bottom stafflines (if Barline.Visible is true)
/// 2. for the range between the staff's lower edge and the next staff's upper edge
/// (if the staff's lower neighbour is in the same group)
/// </summary>
/// <param name="w"></param>
public override void WriteSVG(SvgWriter w, float topStafflineY, float bottomStafflineY, bool isEndOfSystem)
{
float topY = TopY(topStafflineY, isEndOfSystem);
float bottomY = BottomY(bottomStafflineY, isEndOfSystem);
float thinLeftLineOriginX = Barline_LineMetrics.OriginX - (ThickStrokeWidth / 2) - DoubleBarPadding - (ThinStrokeWidth / 2F);
w.SvgStartGroup(CSSObjectClass.endRegionBarline.ToString());
w.SvgLine(CSSObjectClass.thinBarline, thinLeftLineOriginX, topY, thinLeftLineOriginX, bottomY);
float thickRightLineOriginX = Barline_LineMetrics.OriginX;
w.SvgLine(CSSObjectClass.thickBarline, thickRightLineOriginX, topY, thickRightLineOriginX, bottomY);
w.SvgEndGroup();
}
/// <summary>
/// This function writes the staff name, barnumber and region info to the SVG file (if they are present).
/// The barline itself is drawn when the system (and staff edges) is complete.
/// </summary>
public override void WriteDrawObjectsSVG(SvgWriter w)
{
base.WriteDrawObjectsSVG(w);
if(FramedRegionEndTextMetrics != null)
{
FramedRegionEndTextMetrics.WriteSVG(w);
}
}
public override void AddMetricsToEdge(HorizontalEdge horizontalEdge)
{
if(FramedRegionEndTextMetrics != null)
{
horizontalEdge.Add(FramedRegionEndTextMetrics);
}
AddBasicMetricsToEdge(horizontalEdge);
}
internal override void AlignFramedTextsXY(List<NoteObject> fixedNoteObjects)
{
#region alignX
base.AlignBarnumberX();
float originX = Barline_LineMetrics.OriginX;
if(FramedRegionEndTextMetrics != null)
{
FramedRegionEndTextMetrics.Move(originX - FramedRegionEndTextMetrics.Right, 0);
}
#endregion
MoveFramedTextBottomToDefaultPosition(FramedRegionEndTextMetrics);
MoveFramedTextAboveNoteObjects(FramedRegionEndTextMetrics, fixedNoteObjects);
MoveFramedTextAboveNoteObjects(BarnumberMetrics, fixedNoteObjects);
MoveBarnumberAboveRegionBox(BarnumberMetrics, FramedRegionEndTextMetrics);
}
internal override void AddAncilliaryMetricsTo(StaffMetrics staffMetrics)
{
base.AddAncilliaryMetricsTo(staffMetrics);
if(FramedRegionEndTextMetrics != null)
{
staffMetrics.Add(FramedRegionEndTextMetrics);
}
}
public override void CreateMetrics(Graphics graphics)
{
float leftEdge = -((ThickStrokeWidth / 2F) + DoubleBarPadding + ThinStrokeWidth);
float rightEdge = (ThickStrokeWidth / 2F);
Barline_LineMetrics = new Barline_LineMetrics(leftEdge, rightEdge, CSSObjectClass.thinBarline, CSSObjectClass.thickBarline);
SetCommonMetrics(graphics, DrawObjects);
foreach(DrawObject drawObject in DrawObjects)
{
if(drawObject is FramedRegionEndText frst)
{
FramedRegionEndTextMetrics = new FramedRegionInfoMetrics(graphics, frst.Texts, frst.FrameInfo);
break;
}
}
}
public override string ToString()
{
return "endRegionBarline: ";
}
public FramedRegionInfoMetrics FramedRegionEndTextMetrics = null;
}
/// <summary>_
/// A barline whose 3 lines are (left to right) thin, thick, thin. OriginX is the thick line's x-coordinate.
/// </summary>
public class EndAndStartRegionBarline : Barline
{
public EndAndStartRegionBarline(Voice voice, List<DrawObject> drawObjects)
: base(voice)
{
SetDrawObjects(drawObjects);
}
/// <summary>
/// Writes out the barline's vertical line(s).
/// May be called twice per staff.barline:
/// 1. for the range between top and bottom stafflines (if Barline.Visible is true)
/// 2. for the range between the staff's lower edge and the next staff's upper edge
/// (if the staff's lower neighbour is in the same group)
/// </summary>
/// <param name="w"></param>
public override void WriteSVG(SvgWriter w, float topStafflineY, float bottomStafflineY, bool isEndOfSystem)
{
float topY = TopY(topStafflineY, isEndOfSystem);
float bottomY = BottomY(bottomStafflineY, isEndOfSystem);
w.SvgStartGroup(CSSObjectClass.endAndStartRegionBarline.ToString());
float thinLeftLineOriginX = Barline_LineMetrics.OriginX - (ThickStrokeWidth / 2F) - DoubleBarPadding - (ThinStrokeWidth / 2F);
w.SvgLine(CSSObjectClass.thinBarline, thinLeftLineOriginX, topY, thinLeftLineOriginX, bottomY);
float thickCentreLineOriginX = Barline_LineMetrics.OriginX;
w.SvgLine(CSSObjectClass.thickBarline, thickCentreLineOriginX, topY, thickCentreLineOriginX, bottomY);
float thinRightLineOriginX = thickCentreLineOriginX + (ThickStrokeWidth / 2F) + DoubleBarPadding + (ThinStrokeWidth / 2F);
w.SvgLine(CSSObjectClass.thinBarline, thinRightLineOriginX, topY, thinRightLineOriginX, bottomY);
w.SvgEndGroup();
}
/// <summary>
/// This function writes the staff name, barnumber and region info to the SVG file (if they are present).
/// The barline itself is drawn when the system (and staff edges) is complete.
/// </summary>
public override void WriteDrawObjectsSVG(SvgWriter w)
{
base.WriteDrawObjectsSVG(w);
if(FramedRegionEndTextMetrics != null)
{
FramedRegionEndTextMetrics.WriteSVG(w);
}
if(FramedRegionStartTextMetrics != null)
{
FramedRegionStartTextMetrics.WriteSVG(w);
}
}
public override void AddMetricsToEdge(HorizontalEdge horizontalEdge)
{
if(FramedRegionEndTextMetrics != null)
{
horizontalEdge.Add(FramedRegionEndTextMetrics);
}
if(FramedRegionStartTextMetrics != null)
{
horizontalEdge.Add(FramedRegionStartTextMetrics);
}
AddBasicMetricsToEdge(horizontalEdge);
}
public override string ToString()
{
return "endAndStartRegionBarline: ";
}
internal override void AlignFramedTextsXY(List<NoteObject> fixedNoteObjects)
{
#region alignX
// An EndAndStartRegionBarline cannot be at the start of a system,
// so it can't have a barnumber, and there's no reason to call base.AlignBarnumberX();
Debug.Assert(BarnumberMetrics == null);
float originX = Barline_LineMetrics.OriginX;
if(FramedRegionEndTextMetrics != null)
{
FramedRegionEndTextMetrics.Move(originX - FramedRegionEndTextMetrics.Right, 0);
}
if(FramedRegionStartTextMetrics != null)
{
FramedRegionStartTextMetrics.Move(originX - FramedRegionStartTextMetrics.Left, 0);
}
#endregion
MoveFramedTextBottomToDefaultPosition(FramedRegionStartTextMetrics);
MoveFramedTextBottomToDefaultPosition(FramedRegionEndTextMetrics);
MoveFramedTextAboveNoteObjects(FramedRegionStartTextMetrics, fixedNoteObjects);
MoveFramedTextAboveNoteObjects(FramedRegionEndTextMetrics, fixedNoteObjects);
MoveFramedTextAboveNoteObjects(BarnumberMetrics, fixedNoteObjects);
}
public override void CreateMetrics(Graphics graphics)
{
float rightEdge = (ThickStrokeWidth / 2F) + DoubleBarPadding + ThinStrokeWidth;
float leftEdge = -rightEdge;
Barline_LineMetrics = new Barline_LineMetrics(leftEdge, rightEdge, CSSObjectClass.thinBarline, CSSObjectClass.thickBarline);
SetCommonMetrics(graphics, DrawObjects);
foreach(DrawObject drawObject in DrawObjects)
{
if(drawObject is FramedRegionStartText frst)
{
FramedRegionStartTextMetrics = new FramedRegionInfoMetrics(graphics, frst.Texts, frst.FrameInfo);
}
if(drawObject is FramedRegionEndText fret)
{
FramedRegionEndTextMetrics = new FramedRegionInfoMetrics(graphics, fret.Texts, fret.FrameInfo);
}
}
}
internal override void AddAncilliaryMetricsTo(StaffMetrics staffMetrics)
{
base.AddAncilliaryMetricsTo(staffMetrics);
if(FramedRegionStartTextMetrics != null)
{
staffMetrics.Add(FramedRegionStartTextMetrics);
}
if(FramedRegionEndTextMetrics != null)
{
staffMetrics.Add(FramedRegionEndTextMetrics);
}
}
public FramedRegionInfoMetrics FramedRegionStartTextMetrics = null;
public FramedRegionInfoMetrics FramedRegionEndTextMetrics = null;
}
/// <summary>
/// A barline whose 2 lines are (left to right) normal then thick. OriginX is the thick line's x-coordinate.
/// This barline type is always used for the final barline in a score. It can have FramedEndRegionInfo.
/// </summary>
public class EndOfScoreBarline : EndRegionBarline
{
public EndOfScoreBarline(Voice voice, List<DrawObject> drawObjects)
: base(voice, drawObjects)
{
}
/// <summary>
/// Writes out the barline's vertical line(s).
/// May be called twice per staff.barline:
/// 1. for the range between top and bottom stafflines (if Barline.Visible is true)
/// 2. for the range between the staff's lower edge and the next staff's upper edge
/// (if the staff's lower neighbour is in the same group)
/// </summary>
/// <param name="w"></param>
public override void WriteSVG(SvgWriter w, float topStafflineY, float bottomStafflineY, bool isEndOfSystem)
{
float topY = TopY(topStafflineY, isEndOfSystem);
float bottomY = BottomY(bottomStafflineY, isEndOfSystem);
float normalLeftLineOriginX = Barline_LineMetrics.OriginX - (ThickStrokeWidth / 2) - DoubleBarPadding - (NormalStrokeWidth / 2F);
w.SvgStartGroup(CSSObjectClass.endOfScoreBarline.ToString());
w.SvgLine(CSSObjectClass.normalBarline, normalLeftLineOriginX, topY, normalLeftLineOriginX, bottomY);
float thickRightLineOriginX = Barline_LineMetrics.OriginX;
w.SvgLine(CSSObjectClass.thickBarline, thickRightLineOriginX, topY, thickRightLineOriginX, bottomY);
w.SvgEndGroup();
}
// The following functions are inherited from EndRegionBarline.
// public override void WriteDrawObjectsSVG(SvgWriter w)
// public override void AddMetricsToEdge(HorizontalEdge horizontalEdge)
// internal override void AlignFramedTextsXY(List<NoteObject> fixedNoteObjects)
// internal override void AddAncilliaryMetricsTo(StaffMetrics staffMetrics)
public override void CreateMetrics(Graphics graphics)
{
float leftEdge = -((ThickStrokeWidth / 2F) + DoubleBarPadding + NormalStrokeWidth);
float rightEdge = (ThickStrokeWidth / 2F);
Barline_LineMetrics = new Barline_LineMetrics(leftEdge, rightEdge, CSSObjectClass.normalBarline, CSSObjectClass.thickBarline);
foreach(DrawObject drawObject in DrawObjects)
{
if(drawObject is FramedRegionEndText frst)
{
FramedRegionEndTextMetrics = new FramedRegionInfoMetrics(graphics, frst.Texts, frst.FrameInfo);
break;
}
}
}
public override string ToString() { return "endOfScoreBarline: "; }
}
}
| |
// 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 NUnit.Framework;
using osu.Framework.IO.Stores;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Tests.Beatmaps;
using osu.Game.Tests.Resources;
using static osu.Game.Skinning.SkinConfiguration;
namespace osu.Game.Tests.Gameplay
{
public class TestSceneHitObjectSamples : HitObjectSampleTest
{
protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
protected override IResourceStore<byte[]> RulesetResources => TestResources.GetStore();
/// <summary>
/// Tests that a hitobject which provides no custom sample set retrieves samples from the user skin.
/// </summary>
[Test]
public void TestDefaultSampleFromUserSkin()
{
const string expected_sample = "normal-hitnormal";
SetupSkins(expected_sample, expected_sample);
CreateTestWithBeatmap("hitobject-skin-sample.osu");
AssertUserLookup(expected_sample);
}
/// <summary>
/// Tests that a hitobject which provides a sample set of 1 retrieves samples from the beatmap skin.
/// </summary>
[Test]
public void TestDefaultSampleFromBeatmap()
{
const string expected_sample = "normal-hitnormal";
SetupSkins(expected_sample, expected_sample);
CreateTestWithBeatmap("hitobject-beatmap-sample.osu");
AssertBeatmapLookup(expected_sample);
}
/// <summary>
/// Tests that a hitobject which provides a sample set of 1 retrieves samples from the user skin when the beatmap does not contain the sample.
/// </summary>
[Test]
public void TestDefaultSampleFromUserSkinFallback()
{
const string expected_sample = "normal-hitnormal";
SetupSkins(null, expected_sample);
CreateTestWithBeatmap("hitobject-beatmap-sample.osu");
AssertUserLookup(expected_sample);
}
/// <summary>
/// Tests that a hitobject which provides a custom sample set of 2 retrieves the following samples from the beatmap skin:
/// normal-hitnormal2
/// normal-hitnormal
/// hitnormal
/// </summary>
[TestCase("normal-hitnormal2")]
[TestCase("normal-hitnormal")]
[TestCase("hitnormal")]
public void TestDefaultCustomSampleFromBeatmap(string expectedSample)
{
SetupSkins(expectedSample, expectedSample);
CreateTestWithBeatmap("hitobject-beatmap-custom-sample.osu");
AssertBeatmapLookup(expectedSample);
}
/// <summary>
/// Tests that a hitobject which provides a custom sample set of 2 retrieves the following samples from the user skin
/// (ignoring the custom sample set index) when the beatmap skin does not contain the sample:
/// normal-hitnormal
/// hitnormal
/// </summary>
[TestCase("normal-hitnormal")]
[TestCase("hitnormal")]
public void TestDefaultCustomSampleFromUserSkinFallback(string expectedSample)
{
SetupSkins(string.Empty, expectedSample);
CreateTestWithBeatmap("hitobject-beatmap-custom-sample.osu");
AssertUserLookup(expectedSample);
}
/// <summary>
/// Tests that a hitobject which provides a custom sample set of 2 does not retrieve a normal-hitnormal2 sample from the user skin
/// if the beatmap skin does not contain the sample.
/// User skins in stable ignore the custom sample set index when performing lookups.
/// </summary>
[Test]
public void TestUserSkinLookupIgnoresSampleBank()
{
const string unwanted_sample = "normal-hitnormal2";
SetupSkins(string.Empty, unwanted_sample);
CreateTestWithBeatmap("hitobject-beatmap-custom-sample.osu");
AssertNoLookup(unwanted_sample);
}
/// <summary>
/// Tests that a hitobject which provides a sample file retrieves the sample file from the beatmap skin.
/// </summary>
[Test]
public void TestFileSampleFromBeatmap()
{
const string expected_sample = "hit_1.wav";
SetupSkins(expected_sample, expected_sample);
CreateTestWithBeatmap("file-beatmap-sample.osu");
AssertBeatmapLookup(expected_sample);
}
/// <summary>
/// Tests that a default hitobject and control point causes <see cref="TestDefaultSampleFromUserSkin"/>.
/// </summary>
[Test]
public void TestControlPointSampleFromSkin()
{
const string expected_sample = "normal-hitnormal";
SetupSkins(expected_sample, expected_sample);
CreateTestWithBeatmap("controlpoint-skin-sample.osu");
AssertUserLookup(expected_sample);
}
/// <summary>
/// Tests that a control point that provides a custom sample set of 1 causes <see cref="TestDefaultSampleFromBeatmap"/>.
/// </summary>
[Test]
public void TestControlPointSampleFromBeatmap()
{
const string expected_sample = "normal-hitnormal";
SetupSkins(expected_sample, expected_sample);
CreateTestWithBeatmap("controlpoint-beatmap-sample.osu");
AssertBeatmapLookup(expected_sample);
}
/// <summary>
/// Tests that a control point that provides a custom sample of 2 causes <see cref="TestDefaultCustomSampleFromBeatmap"/>.
/// </summary>
[TestCase("normal-hitnormal2")]
[TestCase("normal-hitnormal")]
[TestCase("hitnormal")]
public void TestControlPointCustomSampleFromBeatmap(string sampleName)
{
SetupSkins(sampleName, sampleName);
CreateTestWithBeatmap("controlpoint-beatmap-custom-sample.osu");
AssertBeatmapLookup(sampleName);
}
/// <summary>
/// Tests that a hitobject's custom sample overrides the control point's.
/// </summary>
[Test]
public void TestHitObjectCustomSampleOverride()
{
const string expected_sample = "normal-hitnormal3";
SetupSkins(expected_sample, expected_sample);
CreateTestWithBeatmap("hitobject-beatmap-custom-sample-override.osu");
AssertBeatmapLookup(expected_sample);
}
/// <summary>
/// Tests that when a custom sample bank is used, both the normal and additional sounds will be looked up.
/// </summary>
[Test]
public void TestHitObjectCustomSampleBank()
{
string[] expectedSamples =
{
"normal-hitnormal2",
"normal-hitwhistle" // user skin lookups ignore custom sample set index
};
SetupSkins(expectedSamples[0], expectedSamples[1]);
CreateTestWithBeatmap("hitobject-beatmap-custom-sample-bank.osu");
AssertBeatmapLookup(expectedSamples[0]);
AssertUserLookup(expectedSamples[1]);
}
/// <summary>
/// Tests that when a custom sample bank is used, but <see cref="LegacySetting.LayeredHitSounds"/> is disabled,
/// only the additional sound will be looked up.
/// </summary>
[Test]
public void TestHitObjectCustomSampleBankWithoutLayered()
{
const string expected_sample = "normal-hitwhistle2";
const string unwanted_sample = "normal-hitnormal2";
SetupSkins(expected_sample, unwanted_sample);
disableLayeredHitSounds();
CreateTestWithBeatmap("hitobject-beatmap-custom-sample-bank.osu");
AssertBeatmapLookup(expected_sample);
AssertNoLookup(unwanted_sample);
}
/// <summary>
/// Tests that when a normal sample bank is used and <see cref="LegacySetting.LayeredHitSounds"/> is disabled,
/// the normal sound will be looked up anyway.
/// </summary>
[Test]
public void TestHitObjectNormalSampleBankWithoutLayered()
{
const string expected_sample = "normal-hitnormal";
SetupSkins(expected_sample, expected_sample);
disableLayeredHitSounds();
CreateTestWithBeatmap("hitobject-beatmap-sample.osu");
AssertBeatmapLookup(expected_sample);
}
private void disableLayeredHitSounds()
=> AddStep("set LayeredHitSounds to false", () => Skin.Configuration.ConfigDictionary[LegacySetting.LayeredHitSounds.ToString()] = "0");
}
}
| |
// 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.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class ProductInfoHeaderValueTest
{
[Fact]
public void Ctor_ProductOverload_MatchExpectation()
{
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue(new ProductHeaderValue("product"));
Assert.Equal(new ProductHeaderValue("product"), productInfo.Product);
Assert.Null(productInfo.Comment);
ProductHeaderValue input = null;
Assert.Throws<ArgumentNullException>(() => { new ProductInfoHeaderValue(input); });
}
[Fact]
public void Ctor_ProductStringOverload_MatchExpectation()
{
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("product", "1.0");
Assert.Equal(new ProductHeaderValue("product", "1.0"), productInfo.Product);
Assert.Null(productInfo.Comment);
}
[Fact]
public void Ctor_CommentOverload_MatchExpectation()
{
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("(this is a comment)");
Assert.Null(productInfo.Product);
Assert.Equal("(this is a comment)", productInfo.Comment);
AssertExtensions.Throws<ArgumentException>("comment", () => { new ProductInfoHeaderValue((string)null); });
Assert.Throws<FormatException>(() => { new ProductInfoHeaderValue("invalid comment"); });
Assert.Throws<FormatException>(() => { new ProductInfoHeaderValue(" (leading space)"); });
Assert.Throws<FormatException>(() => { new ProductInfoHeaderValue("(trailing space) "); });
}
[Fact]
public void ToString_UseDifferentProductInfos_AllSerializedCorrectly()
{
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("product", "1.0");
Assert.Equal("product/1.0", productInfo.ToString());
productInfo = new ProductInfoHeaderValue("(comment)");
Assert.Equal("(comment)", productInfo.ToString());
}
[Fact]
public void ToString_Aggregate_AllSerializedCorrectly()
{
HttpRequestMessage request = new HttpRequestMessage();
string input = string.Empty;
ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("product", "1.0");
Assert.Equal("product/1.0", productInfo.ToString());
input += productInfo.ToString();
request.Headers.UserAgent.Add(productInfo);
productInfo = new ProductInfoHeaderValue("(comment)");
Assert.Equal("(comment)", productInfo.ToString());
input += " " + productInfo.ToString(); // Space delineated
request.Headers.UserAgent.Add(productInfo);
Assert.Equal(input, request.Headers.UserAgent.ToString());
}
[Fact]
public void GetHashCode_UseSameAndDifferentProductInfos_SameOrDifferentHashCodes()
{
ProductInfoHeaderValue productInfo1 = new ProductInfoHeaderValue("product", "1.0");
ProductInfoHeaderValue productInfo2 = new ProductInfoHeaderValue(new ProductHeaderValue("product", "1.0"));
ProductInfoHeaderValue productInfo3 = new ProductInfoHeaderValue("(comment)");
ProductInfoHeaderValue productInfo4 = new ProductInfoHeaderValue("(COMMENT)");
Assert.Equal(productInfo1.GetHashCode(), productInfo2.GetHashCode());
Assert.NotEqual(productInfo1.GetHashCode(), productInfo3.GetHashCode());
Assert.NotEqual(productInfo3.GetHashCode(), productInfo4.GetHashCode());
}
[Fact]
public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions()
{
ProductInfoHeaderValue productInfo1 = new ProductInfoHeaderValue("product", "1.0");
ProductInfoHeaderValue productInfo2 = new ProductInfoHeaderValue(new ProductHeaderValue("product", "1.0"));
ProductInfoHeaderValue productInfo3 = new ProductInfoHeaderValue("(comment)");
ProductInfoHeaderValue productInfo4 = new ProductInfoHeaderValue("(COMMENT)");
Assert.False(productInfo1.Equals(null), "product/1.0 vs. <null>");
Assert.True(productInfo1.Equals(productInfo2), "product/1.0 vs. product/1.0");
Assert.False(productInfo1.Equals(productInfo3), "product/1.0 vs. (comment)");
Assert.False(productInfo3.Equals(productInfo4), "(comment) vs. (COMMENT)");
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
ProductInfoHeaderValue source = new ProductInfoHeaderValue("product", "1.0");
ProductInfoHeaderValue clone = (ProductInfoHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Product, clone.Product);
Assert.Null(clone.Comment);
source = new ProductInfoHeaderValue("(comment)");
clone = (ProductInfoHeaderValue)((ICloneable)source).Clone();
Assert.Null(clone.Product);
Assert.Equal(source.Comment, clone.Comment);
}
[Fact]
public void GetProductInfoLength_DifferentValidScenarios_AllReturnNonZero()
{
ProductInfoHeaderValue result = null;
CallGetProductInfoLength(" product / 1.0 ", 1, 14, out result);
Assert.Equal(new ProductHeaderValue("product", "1.0"), result.Product);
Assert.Null(result.Comment);
CallGetProductInfoLength("p/1.0", 0, 5, out result);
Assert.Equal(new ProductHeaderValue("p", "1.0"), result.Product);
Assert.Null(result.Comment);
CallGetProductInfoLength(" (this is a comment) , ", 1, 21, out result);
Assert.Null(result.Product);
Assert.Equal("(this is a comment)", result.Comment);
CallGetProductInfoLength("(c)", 0, 3, out result);
Assert.Null(result.Product);
Assert.Equal("(c)", result.Comment);
CallGetProductInfoLength("(comment/1.0)[", 0, 13, out result);
Assert.Null(result.Product);
Assert.Equal("(comment/1.0)", result.Comment);
}
[Fact]
public void GetRangeLength_DifferentInvalidScenarios_AllReturnZero()
{
CheckInvalidGetProductInfoLength(" p/1.0", 0); // no leading whitespace allowed
CheckInvalidGetProductInfoLength(" (c)", 0); // no leading whitespace allowed
CheckInvalidGetProductInfoLength("(invalid", 0);
CheckInvalidGetProductInfoLength("product/", 0);
CheckInvalidGetProductInfoLength("product/(1.0)", 0);
CheckInvalidGetProductInfoLength("", 0);
CheckInvalidGetProductInfoLength(null, 0);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidParse("product", new ProductInfoHeaderValue("product", null));
CheckValidParse(" product ", new ProductInfoHeaderValue("product", null));
CheckValidParse(" (comment) ", new ProductInfoHeaderValue("(comment)"));
CheckValidParse(" Mozilla/5.0 ", new ProductInfoHeaderValue("Mozilla", "5.0"));
CheckValidParse(" (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) ",
new ProductInfoHeaderValue("(compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse("p/1.0,");
CheckInvalidParse("p/1.0\r\n"); // for \r\n to be a valid whitespace, it must be followed by space/tab
CheckInvalidParse("p/1.0(comment)");
CheckInvalidParse("(comment)[");
CheckInvalidParse(" Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) ");
CheckInvalidParse("p/1.0 =");
// "User-Agent" and "Server" don't allow empty values (unlike most other headers supporting lists of values)
CheckInvalidParse(null);
CheckInvalidParse(string.Empty);
CheckInvalidParse(" ");
CheckInvalidParse("\t");
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidTryParse("product", new ProductInfoHeaderValue("product", null));
CheckValidTryParse(" product ", new ProductInfoHeaderValue("product", null));
CheckValidTryParse(" (comment) ", new ProductInfoHeaderValue("(comment)"));
CheckValidTryParse(" Mozilla/5.0 ", new ProductInfoHeaderValue("Mozilla", "5.0"));
CheckValidTryParse(" (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) ",
new ProductInfoHeaderValue("(compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse("p/1.0,");
CheckInvalidTryParse("p/1.0\r\n"); // for \r\n to be a valid whitespace, it must be followed by space/tab
CheckInvalidTryParse("p/1.0(comment)");
CheckInvalidTryParse("(comment)[");
CheckInvalidTryParse(" Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) ");
CheckInvalidTryParse("p/1.0 =");
// "User-Agent" and "Server" don't allow empty values (unlike most other headers supporting lists of values)
CheckInvalidTryParse(null);
CheckInvalidTryParse(string.Empty);
CheckInvalidTryParse(" ");
CheckInvalidTryParse("\t");
}
#region Helper methods
private void CheckValidParse(string input, ProductInfoHeaderValue expectedResult)
{
ProductInfoHeaderValue result = ProductInfoHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input)
{
Assert.Throws<FormatException>(() => { ProductInfoHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, ProductInfoHeaderValue expectedResult)
{
ProductInfoHeaderValue result = null;
Assert.True(ProductInfoHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input)
{
ProductInfoHeaderValue result = null;
Assert.False(ProductInfoHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
private static void CallGetProductInfoLength(string input, int startIndex, int expectedLength,
out ProductInfoHeaderValue result)
{
Assert.Equal(expectedLength, ProductInfoHeaderValue.GetProductInfoLength(input, startIndex, out result));
}
private static void CheckInvalidGetProductInfoLength(string input, int startIndex)
{
ProductInfoHeaderValue result = null;
Assert.Equal(0, ProductInfoHeaderValue.GetProductInfoLength(input, startIndex, out result));
Assert.Null(result);
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using L4p.Common.Extensions;
using L4p.Common.Json;
using L4p.Common.Loggers;
namespace L4p.Common.SystemEvents
{
public interface IMySystemEvents
{
void SystemIsBeingStarted(string moduleKey, params Assembly[] entryAssemblies);
void SystemIsBeingStopped();
void SetConsoleCtrlHandler();
event Action OnSystemStart;
event Action OnSystemExit;
}
public class MySystemEvents : IMySystemEvents
{
#region members
private readonly ILogFile _log;
private int _systemExitIsRaised;
private event Action _onSystemStart;
private event Action _onSystemExit;
#endregion
#region singleton
private static IMySystemEvents _instance;
public static IMySystemEvents Instance
{
get { return _instance; }
}
static MySystemEvents()
{
_instance = New();
}
#endregion
#region construction
static IMySystemEvents New()
{
return
new MySystemEvents();
}
private MySystemEvents()
{
_log = LogFile.New("bootstrap.log");
_systemExitIsRaised = 0;
AppDomain.CurrentDomain.ProcessExit +=
(sender, args) => raise_system_exit_once();
}
#endregion
#region private
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
private bool handle_win32_console_event(int eventType)
{
Console.Beep();
console_is_being_manually_closed();
return false;
}
private void console_is_being_manually_closed()
{
_log.Info("SystemEvents: Console application is being closed...");
raise_system_exit_once();
}
private void raise_event(Action action, string name)
{
if (action == null)
return;
try
{
action();
}
catch (Exception ex)
{
_log.Error(ex, "SystemEvents: failure during event '{0}'", name);
}
}
private void raise_system_exit_once()
{
if (Interlocked.Increment(ref _systemExitIsRaised) > 1)
return;
_log.Info("SystemEvents: system is being stopped");
raise_event(_onSystemExit, "on exit");
}
private void initialize_modules(string moduleKey, Assembly[] entryAssemblies)
{
var modules = MyModules.New(_log);
var types = modules.GetInitializersTypes(entryAssemblies);
_log.Trace("Initializers types: {0}", types.ToJson());
var initialzers =
modules.OrderInitializers(
modules.InstantiateInitializers(types));
var forLog =
from initializer in initialzers
select new {initializer.GetType().FullName, initializer.InitializationOrder};
_log.Trace("Initializers order: {0}", forLog.ToArray().ToJson());
var count = modules.CallInitializers(moduleKey, initialzers);
_log.Trace("Initializers: types: {0} instances: {1} initialized: {2}",
types.Length, initialzers.Length, count);
}
#endregion
#region interface
void IMySystemEvents.SystemIsBeingStarted(string moduleKey, Assembly[] entryAssemblies)
{
if (entryAssemblies.IsEmpty())
entryAssemblies = new[] { Assembly.GetEntryAssembly() };
var entryAssembly = entryAssemblies[0];
var entryName =
entryAssembly != null ? entryAssembly.GetName().Name : "unknown";
_log.Info("SystemEvents: system is starting (entry='{0}')", entryName);
try
{
initialize_modules(moduleKey, entryAssemblies);
_log.Info("SystemEvents: modules are initialized");
}
catch (Exception ex)
{
_log.Error(ex, "SystemEvents: failed to initialize modules");
}
raise_event(_onSystemStart, "on start");
}
void IMySystemEvents.SystemIsBeingStopped()
{
raise_system_exit_once();
}
void IMySystemEvents.SetConsoleCtrlHandler()
{
// seems to be not working but causing failures
return;
#pragma warning disable 162
var ok = SetConsoleCtrlHandler(handle_win32_console_event, true);
if (!ok)
{
_log.Warn("SystemEvents: failed to set ctrl-handler");
return;
}
_log.Info("SystemEvents: Console ctrl-handler is installed");
#pragma warning restore 162
}
event Action IMySystemEvents.OnSystemStart
{
add { _onSystemStart += value; }
remove { _onSystemStart -= value; }
}
event Action IMySystemEvents.OnSystemExit
{
add { _onSystemExit += value; }
remove { _onSystemExit -= value; }
}
#endregion
}
}
| |
/* ====================================================================
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.
==================================================================== */
namespace NPOI.XSSF.UserModel
{
using System;
using System.Collections.Generic;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.OpenXmlFormats.Dml.Spreadsheet;
using NPOI.OpenXmlFormats.Dml;
using System.Text;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.Util;
/**
* Represents a shape with a predefined geometry in a SpreadsheetML Drawing.
* Possible shape types are defined in {@link NPOI.SS.UserModel.ShapeTypes}
*/
public class XSSFSimpleShape : XSSFShape, IEnumerable<XSSFTextParagraph>
{ // TODO - instantiable superclass
/**
* List of the paragraphs that make up the text in this shape
*/
private List<XSSFTextParagraph> _paragraphs;
/**
* A default instance of CTShape used for creating new shapes.
*/
private static CT_Shape prototype = null;
/**
* Xml bean that stores properties of this shape
*/
private CT_Shape ctShape;
protected internal XSSFSimpleShape(XSSFDrawing Drawing, CT_Shape ctShape)
{
this.drawing = Drawing;
this.ctShape = ctShape;
_paragraphs = new List<XSSFTextParagraph>();
// Initialize any existing paragraphs - this will be the default body paragraph in a new shape,
// or existing paragraphs that have been loaded from the file
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_TextBody body = ctShape.txBody;
if (body != null)
{
for (int i = 0; i < body.SizeOfPArray(); i++)
{
_paragraphs.Add(new XSSFTextParagraph(body.GetPArray(i), ctShape));
}
}
}
/**
* Prototype with the default structure of a new auto-shape.
*/
protected internal static CT_Shape GetPrototype()
{
if (prototype == null)
{
CT_Shape shape = new CT_Shape();
CT_ShapeNonVisual nv = shape.AddNewNvSpPr();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_NonVisualDrawingProps nvp = nv.AddNewCNvPr();
nvp.id = (/*setter*/1);
nvp.name = (/*setter*/"Shape 1");
nv.AddNewCNvSpPr();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_ShapeProperties sp = shape.AddNewSpPr();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_Transform2D t2d = sp.AddNewXfrm();
CT_PositiveSize2D p1 = t2d.AddNewExt();
p1.cx = (/*setter*/0);
p1.cy = (/*setter*/0);
CT_Point2D p2 = t2d.AddNewOff();
p2.x = (/*setter*/0);
p2.y = (/*setter*/0);
CT_PresetGeometry2D geom = sp.AddNewPrstGeom();
geom.prst = (/*setter*/ST_ShapeType.rect);
geom.AddNewAvLst();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_TextBody body = shape.AddNewTxBody();
CT_TextBodyProperties bodypr = body.AddNewBodyPr();
bodypr.anchor = (/*setter*/ST_TextAnchoringType.t);
bodypr.rtlCol = (/*setter*/false);
CT_TextParagraph p = body.AddNewP();
p.AddNewPPr().algn = (/*setter*/ST_TextAlignType.l);
CT_TextCharacterProperties endPr = p.AddNewEndParaRPr();
endPr.lang = (/*setter*/"en-US");
endPr.sz = (/*setter*/1100);
CT_SolidColorFillProperties scfpr = endPr.AddNewSolidFill();
scfpr.AddNewSrgbClr().val = (/*setter*/new byte[] { 0, 0, 0 });
body.AddNewLstStyle();
prototype = shape;
}
return prototype;
}
public CT_Shape GetCTShape()
{
return ctShape;
}
public IEnumerator<XSSFTextParagraph> GetEnumerator()
{
return (IEnumerator<XSSFTextParagraph>)_paragraphs.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
/**
* Returns the text from all paragraphs in the shape. Paragraphs are Separated by new lines.
*
* @return text Contained within this shape or empty string
*/
public String Text
{
get
{
int MAX_LEVELS = 9;
StringBuilder out1 = new StringBuilder();
List<int> levelCount = new List<int>(MAX_LEVELS); // maximum 9 levels
XSSFTextParagraph p = null;
// Initialise the levelCount array - this maintains a record of the numbering to be used at each level
for (int k = 0; k < MAX_LEVELS; k++)
{
levelCount.Add(0);
}
for (int i = 0; i < _paragraphs.Count; i++)
{
if (out1.Length > 0) out1.Append('\n');
p = _paragraphs[(i)];
if (p.IsBullet && p.Text.Length > 0)
{
int level = Math.Min(p.Level, MAX_LEVELS - 1);
if (p.IsBulletAutoNumber)
{
i = ProcessAutoNumGroup(i, level, levelCount, out1);
}
else
{
// indent appropriately for the level
for (int j = 0; j < level; j++)
{
out1.Append('\t');
}
String character = p.BulletCharacter;
out1.Append(character.Length > 0 ? character + " " : "- ");
out1.Append(p.Text);
}
}
else
{
out1.Append(p.Text);
// this paragraph is not a bullet, so reset the count array
for (int k = 0; k < MAX_LEVELS; k++)
{
levelCount[k] = 0;
}
}
}
return out1.ToString();
}
}
/**
*
*/
private int ProcessAutoNumGroup(int index, int level, List<int> levelCount, StringBuilder out1)
{
XSSFTextParagraph p = null;
XSSFTextParagraph nextp = null;
ListAutoNumber scheme, nextScheme;
int startAt, nextStartAt;
p = _paragraphs[(index)];
// The rules for generating the auto numbers are as follows. If the following paragraph is also
// an auto-number, has the same type/scheme (and startAt if defined on this paragraph) then they are
// considered part of the same group. An empty bullet paragraph is counted as part of the same
// group but does not increment the count for the group. A change of type, startAt or the paragraph
// not being a bullet resets the count for that level to 1.
// first auto-number paragraph so Initialise to 1 or the bullets startAt if present
startAt = p.BulletAutoNumberStart;
scheme = p.BulletAutoNumberScheme;
if (levelCount[(level)] == 0)
{
levelCount[level] = startAt == 0 ? 1 : startAt;
}
// indent appropriately for the level
for (int j = 0; j < level; j++)
{
out1.Append('\t');
}
if (p.Text.Length > 0)
{
out1.Append(GetBulletPrefix(scheme, levelCount[level]));
out1.Append(p.Text);
}
while (true)
{
nextp = (index + 1) == _paragraphs.Count ? null : _paragraphs[(index + 1)];
if (nextp == null) break; // out of paragraphs
if (!(nextp.IsBullet && p.IsBulletAutoNumber)) break; // not an auto-number bullet
if (nextp.Level > level)
{
// recurse into the new level group
if (out1.Length > 0) out1.Append('\n');
index = ProcessAutoNumGroup(index + 1, nextp.Level, levelCount, out1);
continue; // restart the loop given the new index
}
else if (nextp.Level < level)
{
break; // Changed level
}
nextScheme = nextp.BulletAutoNumberScheme;
nextStartAt = nextp.BulletAutoNumberStart;
if (nextScheme == scheme && nextStartAt == startAt)
{
// bullet is valid, so increment i
++index;
if (out1.Length > 0) out1.Append('\n');
// indent for the level
for (int j = 0; j < level; j++)
{
out1.Append('\t');
}
// check for empty text - only output a bullet if there is text, but it is still part of the group
if (nextp.Text.Length > 0)
{
// increment the count for this level
levelCount[level] = levelCount[(level) + 1];
out1.Append(GetBulletPrefix(nextScheme, levelCount[(level)]));
out1.Append(nextp.Text);
}
}
else
{
// something doesn't match so stop
break;
}
}
// end of the group so reset the count for this level
levelCount[level] = 0;
return index;
}
/**
* Returns a string Containing an appropriate prefix for an auto-numbering bullet
* @param scheme the auto-numbering scheme used by the bullet
* @param value the value of the bullet
* @return appropriate prefix for an auto-numbering bullet
*/
private String GetBulletPrefix(ListAutoNumber scheme, int value)
{
StringBuilder out1 = new StringBuilder();
switch (scheme)
{
case ListAutoNumber.ALPHA_LC_PARENT_BOTH:
case ListAutoNumber.ALPHA_LC_PARENT_R:
if (scheme == ListAutoNumber.ALPHA_LC_PARENT_BOTH) out1.Append('(');
out1.Append(valueToAlpha(value).ToLower());
out1.Append(')');
break;
case ListAutoNumber.ALPHA_UC_PARENT_BOTH:
case ListAutoNumber.ALPHA_UC_PARENT_R:
if (scheme == ListAutoNumber.ALPHA_UC_PARENT_BOTH) out1.Append('(');
out1.Append(valueToAlpha(value));
out1.Append(')');
break;
case ListAutoNumber.ALPHA_LC_PERIOD:
out1.Append(valueToAlpha(value).ToLower());
out1.Append('.');
break;
case ListAutoNumber.ALPHA_UC_PERIOD:
out1.Append(valueToAlpha(value));
out1.Append('.');
break;
case ListAutoNumber.ARABIC_PARENT_BOTH:
case ListAutoNumber.ARABIC_PARENT_R:
if (scheme == ListAutoNumber.ARABIC_PARENT_BOTH) out1.Append('(');
out1.Append(value);
out1.Append(')');
break;
case ListAutoNumber.ARABIC_PERIOD:
out1.Append(value);
out1.Append('.');
break;
case ListAutoNumber.ARABIC_PLAIN:
out1.Append(value);
break;
case ListAutoNumber.ROMAN_LC_PARENT_BOTH:
case ListAutoNumber.ROMAN_LC_PARENT_R:
if (scheme == ListAutoNumber.ROMAN_LC_PARENT_BOTH) out1.Append('(');
out1.Append(valueToRoman(value).ToLower());
out1.Append(')');
break;
case ListAutoNumber.ROMAN_UC_PARENT_BOTH:
case ListAutoNumber.ROMAN_UC_PARENT_R:
if (scheme == ListAutoNumber.ROMAN_UC_PARENT_BOTH) out1.Append('(');
out1.Append(valueToRoman(value));
out1.Append(')');
break;
case ListAutoNumber.ROMAN_LC_PERIOD:
out1.Append(valueToRoman(value).ToLower());
out1.Append('.');
break;
case ListAutoNumber.ROMAN_UC_PERIOD:
out1.Append(valueToRoman(value));
out1.Append('.');
break;
default:
out1.Append('\u2022'); // can't Set the font to wingdings so use the default bullet character
break;
}
out1.Append(" ");
return out1.ToString();
}
/**
* Convert an integer to its alpha equivalent e.g. 1 = A, 2 = B, 27 = AA etc
*/
private String valueToAlpha(int value)
{
String alpha = "";
int modulo;
while (value > 0)
{
modulo = (value - 1) % 26;
alpha = (char)(65 + modulo) + alpha;
value = (value - modulo) / 26;
}
return alpha;
}
private static String[] _romanChars = new String[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
private static int[] _romanAlphaValues = new int[] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
/**
* Convert an integer to its roman equivalent e.g. 1 = I, 9 = IX etc
*/
private String valueToRoman(int value)
{
StringBuilder out1 = new StringBuilder();
for (int i = 0; value > 0 && i < _romanChars.Length; i++)
{
while (_romanAlphaValues[i] <= value)
{
out1.Append(_romanChars[i]);
value -= _romanAlphaValues[i];
}
}
return out1.ToString();
}
/**
* Clear all text from this shape
*/
public void ClearText()
{
_paragraphs.Clear();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_TextBody txBody = ctShape.txBody;
txBody.SetPArray(null); // remove any existing paragraphs
}
/**
* Set a single paragraph of text on the shape. Note this will replace all existing paragraphs Created on the shape.
* @param text string representing the paragraph text
*/
public void SetText(String text)
{
ClearText();
AddNewTextParagraph().AddNewTextRun().Text = (text);
}
/**
* Set a single paragraph of text on the shape. Note this will replace all existing paragraphs Created on the shape.
* @param str rich text string representing the paragraph text
*/
public void SetText(XSSFRichTextString str)
{
XSSFWorkbook wb = (XSSFWorkbook)GetDrawing().GetParent().GetParent();
str.SetStylesTableReference(wb.GetStylesSource());
CT_TextParagraph p = new CT_TextParagraph();
if (str.NumFormattingRuns == 0)
{
CT_RegularTextRun r = p.AddNewR();
CT_TextCharacterProperties rPr = r.AddNewRPr();
rPr.lang = (/*setter*/"en-US");
rPr.sz = (/*setter*/1100);
r.t = (/*setter*/str.String);
}
else
{
for (int i = 0; i < str.GetCTRst().SizeOfRArray(); i++)
{
CT_RElt lt = str.GetCTRst().GetRArray(i);
CT_RPrElt ltPr = lt.rPr;
if (ltPr == null) ltPr = lt.AddNewRPr();
CT_RegularTextRun r = p.AddNewR();
CT_TextCharacterProperties rPr = r.AddNewRPr();
rPr.lang = (/*setter*/"en-US");
ApplyAttributes(ltPr, rPr);
r.t = (/*setter*/lt.t);
}
}
ClearText();
ctShape.txBody.SetPArray(new CT_TextParagraph[] { p });
_paragraphs.Add(new XSSFTextParagraph(ctShape.txBody.GetPArray(0), ctShape));
}
/**
* Returns a collection of the XSSFTextParagraphs that are attached to this shape
*
* @return text paragraphs in this shape
*/
public List<XSSFTextParagraph> TextParagraphs
{
get
{
return _paragraphs;
}
}
/**
* Add a new paragraph run to this shape
*
* @return Created paragraph run
*/
public XSSFTextParagraph AddNewTextParagraph()
{
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_TextBody txBody = ctShape.txBody;
CT_TextParagraph p = txBody.AddNewP();
XSSFTextParagraph paragraph = new XSSFTextParagraph(p, ctShape);
_paragraphs.Add(paragraph);
return paragraph;
}
/**
* Add a new paragraph run to this shape, Set to the provided string
*
* @return Created paragraph run
*/
public XSSFTextParagraph AddNewTextParagraph(String text)
{
XSSFTextParagraph paragraph = AddNewTextParagraph();
paragraph.AddNewTextRun().Text=(text);
return paragraph;
}
/**
* Add a new paragraph run to this shape, Set to the provided rich text string
*
* @return Created paragraph run
*/
public XSSFTextParagraph AddNewTextParagraph(XSSFRichTextString str)
{
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_TextBody txBody = ctShape.txBody;
CT_TextParagraph p = txBody.AddNewP();
if (str.NumFormattingRuns == 0)
{
CT_RegularTextRun r = p.AddNewR();
CT_TextCharacterProperties rPr = r.AddNewRPr();
rPr.lang = (/*setter*/"en-US");
rPr.sz = (/*setter*/1100);
r.t = (/*setter*/str.String);
}
else
{
for (int i = 0; i < str.GetCTRst().SizeOfRArray(); i++)
{
CT_RElt lt = str.GetCTRst().GetRArray(i);
CT_RPrElt ltPr = lt.rPr;
if (ltPr == null) ltPr = lt.AddNewRPr();
CT_RegularTextRun r = p.AddNewR();
CT_TextCharacterProperties rPr = r.AddNewRPr();
rPr.lang = (/*setter*/"en-US");
ApplyAttributes(ltPr, rPr);
r.t = (/*setter*/lt.t);
}
}
// Note: the XSSFTextParagraph constructor will create its required XSSFTextRuns from the provided CTTextParagraph
XSSFTextParagraph paragraph = new XSSFTextParagraph(p, ctShape);
_paragraphs.Add(paragraph);
return paragraph;
}
/**
* Returns the type of horizontal overflow for the text.
*
* @return the type of horizontal overflow
*/
public TextHorizontalOverflow TextHorizontalOverflow
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetHorzOverflow())
{
return (TextHorizontalOverflow)((int)bodyPr.horzOverflow - 1);
}
}
return TextHorizontalOverflow.OVERFLOW;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (value == TextHorizontalOverflow.None)
{
if (bodyPr.IsSetHorzOverflow()) bodyPr.UnsetHorzOverflow();
}
else
{
bodyPr.horzOverflow = (/*setter*/(ST_TextHorzOverflowType)((int)value + 1));
}
}
}
}
/**
* Returns the type of vertical overflow for the text.
*
* @return the type of vertical overflow
*/
public TextVerticalOverflow TextVerticalOverflow
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetVertOverflow())
{
return (TextVerticalOverflow)((int)bodyPr.vertOverflow - 1);
}
}
return TextVerticalOverflow.OVERFLOW;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (value == TextVerticalOverflow.None)
{
if (bodyPr.IsSetVertOverflow()) bodyPr.UnsetVertOverflow();
}
else
{
bodyPr.vertOverflow = (/*setter*/(ST_TextVertOverflowType)((int)value + 1));
}
}
}
}
/**
* Returns the type of vertical alignment for the text within the shape.
*
* @return the type of vertical alignment
*/
public VerticalAlignment VerticalAlignment
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetAnchor())
{
return (VerticalAlignment)((int)bodyPr.anchor);
}
}
return VerticalAlignment.Top;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (value == VerticalAlignment.None)
{
if (bodyPr.IsSetAnchor()) bodyPr.UnsetAnchor();
}
else
{
bodyPr.anchor = (/*setter*/(ST_TextAnchoringType)((int)value));
}
}
}
}
/**
* Gets the vertical orientation of the text
*
* @return vertical orientation of the text
*/
public TextDirection TextDirection
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
ST_TextVerticalType val = bodyPr.vert;
if (val != ST_TextVerticalType.horz)
{
return (TextDirection)(val - 1);
}
}
return TextDirection.HORIZONTAL;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (value == TextDirection.None)
{
if (bodyPr.IsSetVert()) bodyPr.UnsetVert();
}
else
{
bodyPr.vert = (/*setter*/(ST_TextVerticalType)((int)value + 1));
}
}
}
}
/**
* Returns the distance (in points) between the bottom of the text frame
* and the bottom of the inscribed rectangle of the shape that Contains the text.
*
* @return the bottom inset in points
*/
public double BottomInset
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetBIns())
{
return Units.ToPoints(bodyPr.bIns);
}
}
// If this attribute is omitted, then a value of 0.05 inches is implied
return 3.6;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (value == -1)
{
if (bodyPr.IsSetBIns()) bodyPr.UnsetBIns();
}
else bodyPr.bIns = (/*setter*/Units.ToEMU(value));
}
}
}
/**
* Returns the distance (in points) between the left edge of the text frame
* and the left edge of the inscribed rectangle of the shape that Contains
* the text.
*
* @return the left inset in points
*/
public double LeftInset
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetLIns())
{
return Units.ToPoints(bodyPr.lIns);
}
}
// If this attribute is omitted, then a value of 0.05 inches is implied
return 3.6;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (value == -1)
{
if (bodyPr.IsSetLIns()) bodyPr.UnsetLIns();
}
else bodyPr.lIns = (/*setter*/Units.ToEMU(value));
}
}
}
/**
* Returns the distance (in points) between the right edge of the
* text frame and the right edge of the inscribed rectangle of the shape
* that Contains the text.
*
* @return the right inset in points
*/
public double RightInset
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetRIns())
{
return Units.ToPoints(bodyPr.rIns);
}
}
// If this attribute is omitted, then a value of 0.05 inches is implied
return 3.6;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (value == -1)
{
if (bodyPr.IsSetRIns()) bodyPr.UnsetRIns();
}
else bodyPr.rIns = (/*setter*/Units.ToEMU(value));
}
}
}
/**
* Returns the distance (in points) between the top of the text frame
* and the top of the inscribed rectangle of the shape that Contains the text.
*
* @return the top inset in points
*/
public double TopInset
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetTIns())
{
return Units.ToPoints(bodyPr.tIns);
}
}
// If this attribute is omitted, then a value of 0.05 inches is implied
return 3.6;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (value == -1)
{
if (bodyPr.IsSetTIns()) bodyPr.UnsetTIns();
}
else bodyPr.tIns = (/*setter*/Units.ToEMU(value));
}
}
}
/**
* @return whether to wrap words within the bounding rectangle
*/
public bool WordWrap
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetWrap())
{
return bodyPr.wrap == ST_TextWrappingType.square;
}
}
return true;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
bodyPr.wrap = (/*setter*/value ? ST_TextWrappingType.square : ST_TextWrappingType.none);
}
}
}
/**
*
* Specifies that a shape should be auto-fit to fully contain the text described within it.
* Auto-fitting is when text within a shape is scaled in order to contain all the text inside
*
* @param value type of autofit
* @return type of autofit
*/
public TextAutofit TextAutofit
{
get
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetNoAutofit()) return TextAutofit.NONE;
else if (bodyPr.IsSetNormAutofit()) return TextAutofit.NORMAL;
else if (bodyPr.IsSetSpAutoFit()) return TextAutofit.SHAPE;
}
return TextAutofit.NORMAL;
}
set
{
CT_TextBodyProperties bodyPr = ctShape.txBody.bodyPr;
if (bodyPr != null)
{
if (bodyPr.IsSetSpAutoFit()) bodyPr.UnsetSpAutoFit();
if (bodyPr.IsSetNoAutofit()) bodyPr.UnsetNoAutofit();
if (bodyPr.IsSetNormAutofit()) bodyPr.UnsetNormAutofit();
switch (value)
{
case TextAutofit.NONE: bodyPr.AddNewNoAutofit(); break;
case TextAutofit.NORMAL: bodyPr.AddNewNormAutofit(); break;
case TextAutofit.SHAPE: bodyPr.AddNewSpAutoFit(); break;
}
}
}
}
/**
* Gets the shape type, one of the constants defined in {@link NPOI.SS.UserModel.ShapeTypes}.
*
* @return the shape type
* @see NPOI.SS.UserModel.ShapeTypes
*/
public int ShapeType
{
get
{
return (int)ctShape.spPr.prstGeom.prst;
}
set
{
ctShape.spPr.prstGeom.prst = (/*setter*/(ST_ShapeType)(value));
}
}
protected internal override NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_ShapeProperties GetShapeProperties()
{
return ctShape.spPr;
}
/**
* org.Openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt to
* org.Openxmlformats.schemas.Drawingml.x2006.main.CTFont adapter
*/
private static void ApplyAttributes(CT_RPrElt pr, CT_TextCharacterProperties rPr)
{
if (pr.SizeOfBArray() > 0) rPr.b = (/*setter*/pr.GetBArray(0).val);
if (pr.SizeOfUArray() > 0)
{
ST_UnderlineValues u1 = pr.GetUArray(0).val;
if (u1 == ST_UnderlineValues.single) rPr.u = (/*setter*/ST_TextUnderlineType.sng);
else if (u1 == ST_UnderlineValues.@double) rPr.u = (/*setter*/ST_TextUnderlineType.dbl);
else if (u1 == ST_UnderlineValues.none) rPr.u = (/*setter*/ST_TextUnderlineType.none);
}
if (pr.SizeOfIArray() > 0) rPr.i = (/*setter*/pr.GetIArray(0).val);
if (pr.SizeOfRFontArray() > 0)
{
CT_TextFont rFont = rPr.IsSetLatin() ? rPr.latin : rPr.AddNewLatin();
rFont.typeface = (/*setter*/pr.GetRFontArray(0).val);
}
if (pr.SizeOfSzArray() > 0)
{
int sz = (int)(pr.GetSzArray(0).val * 100);
rPr.sz = (/*setter*/sz);
}
if (pr.SizeOfColorArray() > 0)
{
CT_SolidColorFillProperties fill = rPr.IsSetSolidFill() ? rPr.solidFill : rPr.AddNewSolidFill();
NPOI.OpenXmlFormats.Spreadsheet.CT_Color xlsColor = pr.GetColorArray(0);
if (xlsColor.IsSetRgb())
{
CT_SRgbColor clr = fill.IsSetSrgbClr() ? fill.srgbClr : fill.AddNewSrgbClr();
clr.val = (/*setter*/xlsColor.rgb);
}
else if (xlsColor.IsSetIndexed())
{
HSSFColor indexed = (HSSFColor)HSSFColor.GetIndexHash()[((int)xlsColor.indexed)];
if (indexed != null)
{
byte[] rgb = new byte[3];
rgb[0] = (byte)indexed.GetTriplet()[0];
rgb[1] = (byte)indexed.GetTriplet()[1];
rgb[2] = (byte)indexed.GetTriplet()[2];
CT_SRgbColor clr = fill.IsSetSrgbClr() ? fill.srgbClr : fill.AddNewSrgbClr();
clr.val = (/*setter*/rgb);
}
}
}
}
}
}
| |
using UnityEngine;
using System.Collections;
public class PaddleNames : MonoBehaviour {
public static string[] Names = new string[] {"gregmusick",
"OUYAWebStore",
"da_pierce",
"nickd3000",
"Farrahjmiq",
"lixelart",
"MarketingNinjas",
"Meaganskql",
"OwnerDirect",
"Netstars",
"Farmergnome",
"EmilyClaireAfan",
"KateKligman",
"SuperFaytality",
"Symform",
"GamesbyMiLu",
"thagomizer_rb",
"rexxar7227",
"2TonStudios",
"Jesse_504",
"Jesse111",
"martindoolittle",
"VSPInteractive",
"Burger_King007",
"brandondelili",
"yngar",
"AdamSingle",
"IMPULSEthegame",
"LiamReddington",
"_james_h",
"YoutubeMargaret",
"SproutGame",
"OUYAgamesource",
"christinawight",
"ViWalls",
"jasonrwalters",
"stevensaysyes",
"ouyaman3",
"Mose79",
"asindu9",
"TyrusPeace",
"candacecline07",
"psysal",
"getluky",
"Deaker39",
"leegoesplaces",
"OuyaCrazy",
"wheatcreative",
"KintoGames",
"beausimensen",
"rubendhoyosu",
"DesignMunchies",
"AnthonyBuchalka",
"ThatGameDevMuso",
"burnettedmond",
"TerraMeliorRPG",
"ruthlessby",
"bbqchiu",
"anotheruiguy",
"daliful",
"rrza",
"VwFrmMyLkUp",
"ArtfulGamer",
"gamecook",
"heathrmoor",
"AdenHumbert",
"TheSiegeBreaker",
"CodeSavage",
"jamolnng",
"poe__",
"Slushy_",
"alasdair333",
"Amidos2006",
"daevox",
"plixiplix",
"GMShivers",
"Jon_Dog",
"chemicaljeffrey",
"GreenhillGames",
"DarkestKale",
"NightLightGames",
"DemonStudios",
"SteveKovalesky",
"thepelkus",
"Cat_Musgrove",
"FirstConTactics",
"createdevlist",
"CrazyMaul",
"akaButters",
"Seantron",
"ThinkingFungus",
"JamesACoote",
"TornadoTwins",
"rhysdee",
"stuntaneous",
"STINGOUT",
"Poxican",
"robynalley",
"protectedstatic",
"pkamb",
"ArmyOfMeat",
"TeamOuya",
"ouyareviews",
"Megapont",
"AdeptPsyker",
"billwiens",
"Alex_Connolly",
"BenKuchera",
"dedhedzed",
"ThomasNoppers",
"art_control",
"Leiralei",
"ThePixelIdea",
"Cimendere",
"Dapsquatch",
"MedicaliPhone",
"RobotLovesKitty",
"AfterInsanity",
"Attrition0",
"McFunkypants",
"firepunchd",
"CanonSeattle",
"gloomypunk87415",
"happionlabs",
"DanMiller08",
"gpalaio",
"GameIcons",
"joshlarosee",
"lundstroem",
"johnnyybarra92",
"Treleus",
"SounderExchange",
"tigervirgo",
"JonahLupton",
"Iornoq",
"Hotadesu",
"SiegertNica",
"pyrotechnick",
"jshou",
"koiaplays",
"lucysemorocker",
"HybridVigorFilm",
"luciangames",
"Infosec_skills",
"dx0ne",
"emaland",
"barmaki_zineb",
"Plzbanme",
"TheHorribleLamb",
"CbkbadassCory",
"nparekh00",
"squidlarkin",
"auxiliaryZaphos",
"Flying_wing581",
"BramStolk",
"dekdev",
"LittleForestG",
"sparsevector",
"hajpoj",
"JJRTaylor",
"pigeonwisdom",
"missnmaddox",
"cascadiaruby",
"YuzuTenCo",
"roberte3",
"MiamiTechsperts",
"shacker",
"MrAuntJemima",
"Worthless_Bums",
"bluecollarart",
"BrandonSPX",
"MarkehMe",
"shawnscode",
"cadin",
"LUREKILL",
"mikethegreen",
"PacifistGames",
"10WonXero10",
"AntEyeGames",
"anthonyl_tweet",
"racheleggers",
"cirolve",
"rickumali",
"JacksonLango",
"Milo77710",
"drydockaudio",
"RevFry",
"CarterRabasa",
"RexVelvet",
"mcclure111",
"mattrudder",
"jeffybrite",
"Chinos_Seattle",
"trafficone",
"yby010",
"tyvk_Leeticiap",
"mrlerner",
"terrose",
"SouciantRich",
"TJMcCue",
"btfriar",
"ABaumeier",
"topfunky",
"geer68108010",
"ogbog",
"jseattle",
"emilychen",
"DirtyRapscal",
"steamersonwater",
"TheJubberman",
"MonkeyNumberOne",
"sithdown",
"ArcadeChaser",
"atomswitch",
"bittermang",
"neworb",
"shaundern",
"RasoolsTavern",
"Erifdex",
"copperLander",
"Nimble_Monkeys",
"Dayanaara5n51tn",
"melgray",
"EINTechNews",
"JaredMonkey",
"Taunyakij",
"S1mplyRed",
"rlyle78",
"tangosource",
"EFOULI123",
"beercodeseattle",
"computer_paul",
"EssyZ",
"kingtoten",
"BlogChalant",
"TechContractors",
"RatManTheSeries",
"BeavisPunk1",
"johntrahan3",
"mandoescamilla",
"cnunciato",
"mkornblum",
"bionicpill",
"deanero",
"dmontalbano",
"jamsajones",
"TrevorBramble",
"MouseTrapMusic",
"troyd",
"ivanoats",
"rubyandwaffles",
"l4rk",
"OMGst",
"congition_mind",
"Matt_Scarpelli",
"DirectTechSEA",
"blargrist",
"TheDahv",
"mjveed",
"franklinwebber",
"compay",
"SlyClay117",
"davigoli",
"jdsboston",
"zaeyagonewild",
"re5et",
"brattymaddy81",
"eagsalazar",
"LeonardGFish",
"bparfitt",
"ltackett",
"omarqdev",
"wes",
"faloonatic",
"murder_snake",
"ryansobol",
"jmbroad",
"pete_higgins",
"RobinClowers",
"folktrash",
"pete_thedevguy",
"joshpuetz",
"madsimian",
"smoakin",
"Dittitdotcom",
"esalazarrivas",
"dustinvenegas",
"TBMQ",
"radamant",
"JonBHamilton",
"elijahgallegos",
"planetjoker",
"mattfromseattle",
"codebutler",
"rohan_kini",
"crystaldoorknob",
"diamondscribe",
"BFWCMB",
"Carnette88",
"ActionFigures",
"mzgubin",
"JAMMINMUSICMAN1",
"TroyEdwards",
"aaronjensen",
"adamhjk",
"BioCellGames",
"philipsampaio",
"bobdutcheshen",
"bo_yousi",
"i_shot_first",
"Bobby_Ocean",
"crayzkane831",
"Odeyin",
"bRiTtSpAn55",
"Angeleyes401970",
"Atsonios98",
"vanyavasilika",
"abelmartin",
"mforg85",
"nataliejane2",
"GetYr360Elite",
"InvestigateNow",
"WallasJammu",
"geordieromer",
"irinairapolo",
"sunmis",
"JTLaw200",
"mechalurker",
"wwcnd74",
"Mr_Halford",
"jimeh",
"WatchCarsWork",
"HaulkM",
"Swog_19",
"UltimatePsycho",
"GrumpyPanda",
"getadviceat",
"sexyDewdrop60",
"pizzachefs",
"Substantial",
"BigOrangeJenn",
"1GrossThingADay",
"Ifollowmikes",
"metaljohnradio",
"BusinessBeck",
"davidmfoley",
"shesoul4real",
"aclemen18",
"iamdonte",
"supremepizzaman",
"shwanton",
"activebob",
"oboxodo",
"minty985",
"artzt",
"RealEstate3",
"andrewhopper",
"petranorris",
"VacationHmQueen",
"trevorrowe",
"gpbarnett",
"BarackObama",
"TwitPic",
"mamastony",
"joan_holloway",
"iheartbunnies",
"tawnyarocks",
"cdterrie",
"heyIMthatguy",
"thugkid",
"djambazov",
"Cabeza79",
"AlexMason2",
"LemonLaww",
"megustathc",
"OwenRaun",
"Luniar9000",
"JeffX",
"timu_matt",
"ROBERTSKENNETH",
"BLandCrew",
"kimberlyebailey",
"jaredschmidt13",
"minecart",
"ArcticLeo",
"aperock",
"Kiryuu",
"sciencehlogic",
"sxtxixtxcxh",
"LankaKitten"};
public static string Random {
get { return Names[UnityEngine.Random.Range(0, Names.Length)]; }
}
}
| |
// 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.Linq.Expressions;
using Xunit;
namespace System.Linq.Tests
{
public class MinTests : EnumerableBasedTests
{
[Fact]
public void EmptyInt32Source()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().AsQueryable().Min());
}
[Fact]
public void NullInt32Source()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int>)null).Min());
}
[Fact]
public void Int32MinimumRepeated()
{
int[] source = { 6, 0, 9, 0, 10, 0 };
Assert.Equal(0, source.AsQueryable().Min());
}
[Fact]
public void EmptyInt64Source()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().AsQueryable().Min());
}
[Fact]
public void NullInt64Source()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long>)null).Min());
}
[Fact]
public void Int64MinimumRepeated()
{
long[] source = { 6, -5, 9, -5, 10, -5 };
Assert.Equal(-5, source.AsQueryable().Min());
}
[Fact]
public void NullSingleSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<float>)null).Min());
}
[Fact]
public void EmptySingle()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().AsQueryable().Min());
}
[Fact]
public void SingleMinimumRepeated()
{
float[] source = { -5.5f, float.NegativeInfinity, 9.9f, float.NegativeInfinity };
Assert.True(float.IsNegativeInfinity(source.AsQueryable().Min()));
}
[Fact]
public void EmptyDoubleSource()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().AsQueryable().Min());
}
[Fact]
public void NullDoubleSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double>)null).Min());
}
[Fact]
public void DoubleMinimumRepeated()
{
double[] source = { -5.5, double.NegativeInfinity, 9.9, double.NegativeInfinity };
Assert.True(double.IsNegativeInfinity(source.AsQueryable().Min()));
}
[Fact]
public void EmptyDecimalSource()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().AsQueryable().Min());
}
[Fact]
public void NullDecimalSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal>)null).Min());
}
[Fact]
public void DecimalMinimumRepeated()
{
decimal[] source = { -5.5m, 0m, 9.9m, -5.5m, 5m };
Assert.Equal(-5.5m, source.AsQueryable().Min());
}
[Fact]
public void EmptyNullableInt32Source()
{
Assert.Null(Enumerable.Empty<int?>().AsQueryable().Min());
}
[Fact]
public void NullableInt32MinimumRepeated()
{
int?[] source = { 6, null, null, 0, 9, 0, 10, 0 };
Assert.Equal(0, source.AsQueryable().Min());
}
[Fact]
public void EmptyNullableInt64Source()
{
Assert.Null(Enumerable.Empty<long?>().AsQueryable().Min());
}
[Fact]
public void NullNullableInt64Source()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long?>)null).Min());
}
[Fact]
public void NullableInt64MinimumRepeated()
{
long?[] source = { 6, null, null, 0, 9, 0, 10, 0 };
Assert.Equal(0, source.AsQueryable().Min());
}
[Fact]
public void EmptyNullableSingleSource()
{
Assert.Null(Enumerable.Empty<float?>().AsQueryable().Min());
}
[Fact]
public void NullableSingleMinimumRepated()
{
float?[] source = { 6.4f, null, null, -0.5f, 9.4f, -0.5f, 10.9f, -0.5f };
Assert.Equal(-0.5f, source.AsQueryable().Min());
}
[Fact]
public void EmptyNullableDoubleSource()
{
Assert.Null(Enumerable.Empty<double?>().AsQueryable().Min());
}
[Fact]
public void NullNullableDoubleSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double?>)null).Min());
}
[Fact]
public void NullableDoubleMinimumRepeated()
{
double?[] source = { 6.4, null, null, -0.5, 9.4, -0.5, 10.9, -0.5 };
Assert.Equal(-0.5, source.AsQueryable().Min());
}
[Fact]
public void NullableDoubleNaNThenNulls()
{
double?[] source = { double.NaN, null, null, null };
Assert.True(double.IsNaN(source.Min().Value));
}
[Fact]
public void NullableDoubleNullsThenNaN()
{
double?[] source = { null, null, null, double.NaN };
Assert.True(double.IsNaN(source.Min().Value));
}
[Fact]
public void EmptyNullableDecimalSource()
{
Assert.Null(Enumerable.Empty<decimal?>().AsQueryable().Min());
}
[Fact]
public void NullNullableDecimalSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal?>)null).Min());
}
[Fact]
public void NullableDecimalMinimumRepeated()
{
decimal?[] source = { 6.4m, null, null, decimal.MinValue, 9.4m, decimal.MinValue, 10.9m, decimal.MinValue };
Assert.Equal(decimal.MinValue, source.AsQueryable().Min());
}
[Fact]
public void EmptyDateTimeSource()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().AsQueryable().Min());
}
[Fact]
public void NullNullableDateTimeSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<DateTime>)null).Min());
}
[Fact]
public void EmptyStringSource()
{
Assert.Null(Enumerable.Empty<string>().AsQueryable().Min());
}
[Fact]
public void NullStringSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<string>)null).Min());
}
[Fact]
public void StringMinimumRepeated()
{
string[] source = { "ooo", "www", "www", "ooo", "ooo", "ppp" };
Assert.Equal("ooo", source.AsQueryable().Min());
}
[Fact]
public void MinInt32WithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=10 },
new { name="John", num=-105 },
new { name="Bob", num=-30 }
};
Assert.Equal(-105, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void EmptyInt32WithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().AsQueryable().Min(x => x));
}
[Fact]
public void NullInt32SourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int>)null).Min(i => i));
}
[Fact]
public void Int32SourceWithNullSelector()
{
Expression<Func<int, int>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int>().AsQueryable().Min(selector));
}
[Fact]
public void MinInt64WithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=10L },
new { name="John", num=long.MinValue },
new { name="Bob", num=-10L }
};
Assert.Equal(long.MinValue, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void EmptyInt64WithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().AsQueryable().Min(x => x));
}
[Fact]
public void NullInt64SourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long>)null).Min(i => i));
}
[Fact]
public void Int64SourceWithNullSelector()
{
Expression<Func<long, long>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long>().AsQueryable().Min(selector));
}
[Fact]
public void EmptySingleWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().AsQueryable().Min(x => x));
}
[Fact]
public void NullSingleSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<float>)null).Min(i => i));
}
[Fact]
public void MinSingleWithSelectorAccessingProperty()
{
var source = new []{
new { name="Tim", num=-45.5f },
new { name="John", num=-132.5f },
new { name="Bob", num=20.45f }
};
Assert.Equal(-132.5f, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void MinDoubleWithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=-45.5 },
new { name="John", num=-132.5 },
new { name="Bob", num=20.45 }
};
Assert.Equal(-132.5, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void EmptyDoubleWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().AsQueryable().Min(x => x));
}
[Fact]
public void NullDoubleSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double>)null).Min(i => i));
}
[Fact]
public void DoubleSourceWithNullSelector()
{
Expression<Func<double, double>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double>().AsQueryable().Min(selector));
}
[Fact]
public void MinDecimalWithSelectorAccessingProperty()
{
var source = new[]{
new {name="Tim", num=100.45m},
new {name="John", num=10.5m},
new {name="Bob", num=0.05m}
};
Assert.Equal(0.05m, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void EmptyDecimalWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().AsQueryable().Min(x => x));
}
[Fact]
public void NullDecimalSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal>)null).Min(i => i));
}
[Fact]
public void DecimalSourceWithNullSelector()
{
Expression<Func<decimal, decimal>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal>().AsQueryable().Min(selector));
}
[Fact]
public void MinNullableInt32WithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=(int?)10 },
new { name="John", num=default(int?) },
new { name="Bob", num=(int?)-30 }
};
Assert.Equal(-30, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void NullNullableInt32SourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int?>)null).Min(i => i));
}
[Fact]
public void NullableInt32SourceWithNullSelector()
{
Expression<Func<int?, int?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int?>().AsQueryable().Min(selector));
}
[Fact]
public void MinNullableInt64WithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=default(long?) },
new { name="John", num=(long?)long.MinValue },
new { name="Bob", num=(long?)-10L }
};
Assert.Equal(long.MinValue, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void NullNullableInt64SourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long?>)null).Min(i => i));
}
[Fact]
public void NullableInt64SourceWithNullSelector()
{
Expression<Func<long?, long?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long?>().AsQueryable().Min(selector));
}
[Fact]
public void MinNullableSingleWithSelectorAccessingProperty()
{
var source = new[]{
new {name="Tim", num=(float?)-45.5f},
new {name="John", num=(float?)-132.5f},
new {name="Bob", num=default(float?)}
};
Assert.Equal(-132.5f, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void NullNullableSingleSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<float?>)null).Min(i => i));
}
[Fact]
public void NullableSingleSourceWithNullSelector()
{
Expression<Func<float?, float?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float?>().AsQueryable().Min(selector));
}
[Fact]
public void MinNullableDoubleWithSelectorAccessingProperty()
{
var source = new[] {
new { name="Tim", num=(double?)-45.5 },
new { name="John", num=(double?)-132.5 },
new { name="Bob", num=default(double?) }
};
Assert.Equal(-132.5, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void NullNullableDoubleSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double?>)null).Min(i => i));
}
[Fact]
public void NullableDoubleSourceWithNullSelector()
{
Expression<Func<double?, double?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double?>().AsQueryable().Min(selector));
}
[Fact]
public void MinNullableDecimalWithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=(decimal?)100.45m },
new { name="John", num=(decimal?)10.5m },
new { name="Bob", num=default(decimal?) }
};
Assert.Equal(10.5m, source.AsQueryable().Min(e => e.num));
}
[Fact]
public void NullNullableDecimalSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal?>)null).Min(i => i));
}
[Fact]
public void NullableDecimalSourceWithNullSelector()
{
Expression<Func<decimal?, decimal?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal?>().AsQueryable().Min(selector));
}
[Fact]
public void EmptyDateTimeWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().AsQueryable().Min(x => x));
}
[Fact]
public void NullDateTimeSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<DateTime>)null).Min(i => i));
}
[Fact]
public void DateTimeSourceWithNullSelector()
{
Expression<Func<DateTime, DateTime>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<DateTime>().AsQueryable().Min(selector));
}
[Fact]
public void MinStringWitSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=100.45m },
new { name="John", num=10.5m },
new { name="Bob", num=0.05m }
};
Assert.Equal("Bob", source.AsQueryable().Min(e => e.name));
}
[Fact]
public void NullStringSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<string>)null).Min(i => i));
}
[Fact]
public void StringSourceWithNullSelector()
{
Expression<Func<string, string>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<string>().AsQueryable().Min(selector));
}
[Fact]
public void EmptyBooleanSource()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<bool>().AsQueryable().Min());
}
[Fact]
public void Min1()
{
var val = (new int[] { 0, 2, 1 }).AsQueryable().Min();
Assert.Equal(0, val);
}
[Fact]
public void Min2()
{
var val = (new int[] { 0, 2, 1 }).AsQueryable().Min(n => n);
Assert.Equal(0, val);
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using IO;
using Nancy.Extensions;
using Session;
/// <summary>
/// Encapsulates HTTP-request information to an Nancy application.
/// </summary>
public class Request : IDisposable
{
private readonly List<HttpFile> files = new List<HttpFile>();
private dynamic form = new DynamicDictionary();
private IDictionary<string, string> cookies;
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="path">The path of the requested resource, relative to the "Nancy root". This shold not not include the scheme, host name, or query portion of the URI.</param>
/// <param name="scheme">The HTTP protocol that was used by the client.</param>
public Request(string method, string path, string scheme)
: this(method, new Url { Path = path, Scheme = scheme })
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="url">The <see cref="Url"/>url of the requested resource</param>
/// <param name="headers">The headers that was passed in by the client.</param>
/// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param>
/// <param name="ip">The client's IP address</param>
/// <param name="certificate">The client's certificate when present.</param>
public Request(string method, Url url, RequestStream body = null, IDictionary<string, IEnumerable<string>> headers = null, string ip = null, byte[] certificate = null)
{
if (String.IsNullOrEmpty(method))
{
throw new ArgumentOutOfRangeException("method");
}
if (url == null)
{
throw new ArgumentNullException("url");
}
if (url.Path == null)
{
throw new ArgumentNullException("url.Path");
}
if (String.IsNullOrEmpty(url.Scheme))
{
throw new ArgumentOutOfRangeException("url.Scheme");
}
this.UserHostAddress = ip;
this.Url = url;
this.Method = method;
this.Query = url.Query.AsQueryDictionary();
this.Body = body ?? RequestStream.FromStream(new MemoryStream());
this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>());
this.Session = new NullSessionProvider();
if (certificate != null && certificate.Length != 0)
{
this.ClientCertificate = new X509Certificate2(certificate);
}
if (String.IsNullOrEmpty(this.Url.Path))
{
this.Url.Path = "/";
}
this.ParseFormData();
this.RewriteMethod();
}
/// <summary>
/// Gets the certificate sent by the client.
/// </summary>
public X509Certificate ClientCertificate { get; private set; }
/// <summary>
/// Gets the IP address of the client
/// </summary>
public string UserHostAddress { get; private set; }
/// <summary>
/// Gets or sets the HTTP data transfer method used by the client.
/// </summary>
/// <value>The method.</value>
public string Method { get; private set; }
/// <summary>
/// Gets the url
/// </summary>
public Url Url { get; private set; }
/// <summary>
/// Gets the request path, relative to the base path.
/// Used for route matching etc.
/// </summary>
public string Path
{
get
{
return this.Url.Path;
}
}
/// <summary>
/// Gets the querystring data of the requested resource.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of querystring data.</value>
public dynamic Query { get; set; }
/// <summary>
/// Gets a <see cref="RequestStream"/> that can be used to read the incoming HTTP body
/// </summary>
/// <value>A <see cref="RequestStream"/> object representing the incoming HTTP body.</value>
public RequestStream Body { get; private set; }
/// <summary>
/// Gets the request cookies.
/// </summary>
public IDictionary<string, string> Cookies
{
get { return this.cookies ?? (this.cookies = this.GetCookieData()); }
}
/// <summary>
/// Gets the current session.
/// </summary>
public ISession Session { get; set; }
/// <summary>
/// Gets the cookie data from the request header if it exists
/// </summary>
/// <returns>Cookies dictionary</returns>
private IDictionary<string, string> GetCookieData()
{
var cookieDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (!this.Headers.Cookie.Any())
{
return cookieDictionary;
}
var values = this.Headers["cookie"].First().TrimEnd(';').Split(';');
foreach (var parts in values.Select(c => c.Split(new[] { '=' }, 2)))
{
var cookieName = parts[0].Trim();
if (parts.Length == 1)
{
if (cookieName.Equals("HttpOnly", StringComparison.InvariantCultureIgnoreCase) ||
cookieName.Equals("Secure", StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
}
cookieDictionary[cookieName] = parts[1];
}
return cookieDictionary;
}
/// <summary>
/// Gets a collection of files sent by the client-
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> instance, containing an <see cref="HttpFile"/> instance for each uploaded file.</value>
public IEnumerable<HttpFile> Files
{
get { return this.files; }
}
/// <summary>
/// Gets the form data of the request.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of form data.</value>
/// <remarks>Currently Nancy will only parse form data sent using the application/x-www-url-encoded mime-type.</remarks>
public dynamic Form
{
get { return this.form; }
}
/// <summary>
/// Gets the HTTP headers sent by the client.
/// </summary>
/// <value>An <see cref="IDictionary{TKey,TValue}"/> containing the name and values of the headers.</value>
/// <remarks>The values are stored in an <see cref="IEnumerable{T}"/> of string to be compliant with multi-value headers.</remarks>
public RequestHeaders Headers { get; private set; }
public void Dispose()
{
((IDisposable)this.Body).Dispose();
}
private void ParseFormData()
{
if (string.IsNullOrEmpty(this.Headers.ContentType))
{
return;
}
var contentType = this.Headers["content-type"].First();
var mimeType = contentType.Split(';').First();
if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
{
var reader = new StreamReader(this.Body);
this.form = reader.ReadToEnd().AsQueryDictionary();
this.Body.Position = 0;
}
if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
{
return;
}
var boundary = Regex.Match(contentType, @"boundary=""?(?<token>[^\n\;\"" ]*)").Groups["token"].Value;
var multipart = new HttpMultipart(this.Body, boundary);
var formValues =
new NameValueCollection(StaticConfiguration.CaseSensitive ? StringComparer.InvariantCulture : StringComparer.InvariantCultureIgnoreCase);
foreach (var httpMultipartBoundary in multipart.GetBoundaries())
{
if (string.IsNullOrEmpty(httpMultipartBoundary.Filename))
{
var reader =
new StreamReader(httpMultipartBoundary.Value);
formValues.Add(httpMultipartBoundary.Name, reader.ReadToEnd());
}
else
{
this.files.Add(new HttpFile(httpMultipartBoundary));
}
}
foreach (var key in formValues.AllKeys.Where(key => key != null))
{
this.form[key] = formValues[key];
}
this.Body.Position = 0;
}
private void RewriteMethod()
{
if (!this.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
{
return;
}
var overrides =
new List<Tuple<string, string>>
{
Tuple.Create("_method form input element", (string)this.Form["_method"]),
Tuple.Create("X-HTTP-Method-Override form input element", (string)this.Form["X-HTTP-Method-Override"]),
Tuple.Create("X-HTTP-Method-Override header", this.Headers["X-HTTP-Method-Override"].FirstOrDefault())
};
var providedOverride =
overrides.Where(x => !string.IsNullOrEmpty(x.Item2));
if (!providedOverride.Any())
{
return;
}
if (providedOverride.Count() > 1)
{
var overrideSources =
string.Join(", ", providedOverride);
var errorMessage =
string.Format("More than one HTTP method override was provided. The provided values where: {0}", overrideSources);
throw new InvalidOperationException(errorMessage);
}
this.Method = providedOverride.Single().Item2;
}
}
}
| |
using System;
using AppKit;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
namespace Airbnb.Lottie
{
// @interface LOTComposition : NSObject
[BaseType (typeof(NSObject))]
interface LOTComposition
{
// +(instancetype _Nullable)animationNamed:(NSString * _Nonnull)animationName;
[Static]
[Export ("animationNamed:")]
[return: NullAllowed]
LOTComposition AnimationNamed (string animationName);
// +(instancetype _Nullable)animationNamed:(NSString * _Nonnull)animationName inBundle:(NSBundle * _Nonnull)bundle;
[Static]
[Export ("animationNamed:inBundle:")]
[return: NullAllowed]
LOTComposition AnimationNamed (string animationName, NSBundle bundle);
// +(instancetype _Nullable)animationWithFilePath:(NSString * _Nonnull)filePath;
[Static]
[Export ("animationWithFilePath:")]
[return: NullAllowed]
LOTComposition AnimationWithFilePath (string filePath);
// +(instancetype _Nonnull)animationFromJSON:(NSDictionary * _Nonnull)animationJSON;
[Static]
[Export ("animationFromJSON:")]
LOTComposition AnimationFromJSON (NSDictionary animationJSON);
// +(instancetype _Nonnull)animationFromJSON:(NSDictionary * _Nullable)animationJSON inBundle:(NSBundle * _Nullable)bundle;
[Static]
[Export ("animationFromJSON:inBundle:")]
LOTComposition AnimationFromJSON ([NullAllowed] NSDictionary animationJSON, [NullAllowed] NSBundle bundle);
// -(instancetype _Nonnull)initWithJSON:(NSDictionary * _Nullable)jsonDictionary withAssetBundle:(NSBundle * _Nullable)bundle;
[Export ("initWithJSON:withAssetBundle:")]
IntPtr Constructor ([NullAllowed] NSDictionary jsonDictionary, [NullAllowed] NSBundle bundle);
// @property (readonly, nonatomic) CGRect compBounds;
[Export ("compBounds")]
CGRect CompBounds { get; }
// @property (readonly, nonatomic) NSNumber * _Nullable startFrame;
[NullAllowed, Export ("startFrame")]
NSNumber StartFrame { get; }
// @property (readonly, nonatomic) NSNumber * _Nullable endFrame;
[NullAllowed, Export ("endFrame")]
NSNumber EndFrame { get; }
// @property (readonly, nonatomic) NSNumber * _Nullable framerate;
[NullAllowed, Export ("framerate")]
NSNumber Framerate { get; }
// @property (readonly, nonatomic) NSTimeInterval timeDuration;
[Export ("timeDuration")]
double TimeDuration { get; }
// @property (readonly, nonatomic) LOTLayerGroup * _Nullable layerGroup;
//[NullAllowed, Export ("layerGroup")]
//LOTLayerGroup LayerGroup { get; }
// @property (readonly, nonatomic) LOTAssetGroup * _Nullable assetGroup;
//[NullAllowed, Export ("assetGroup")]
//LOTAssetGroup AssetGroup { get; }
// @property (readwrite, nonatomic) NSString * _Nullable rootDirectory;
[NullAllowed, Export ("rootDirectory")]
string RootDirectory { get; set; }
// @property (readonly, nonatomic) NSBundle * _Nullable assetBundle;
[NullAllowed, Export ("assetBundle")]
NSBundle AssetBundle { get; }
// @property (copy, nonatomic) NSString * _Nullable cacheKey;
[NullAllowed, Export ("cacheKey")]
string CacheKey { get; set; }
}
// @interface LOTKeypath : NSObject
[BaseType (typeof(NSObject))]
interface LOTKeypath
{
// +(LOTKeypath * _Nonnull)keypathWithString:(NSString * _Nonnull)keypath;
[Static]
[Export ("keypathWithString:")]
LOTKeypath KeypathWithString (string keypath);
// +(LOTKeypath * _Nonnull)keypathWithKeys:(NSString * _Nonnull)firstKey, ... __attribute__((sentinel(0, 1)));
[Static, Internal]
[Export ("keypathWithKeys:", IsVariadic = true)]
LOTKeypath KeypathWithKeys (string firstKey, IntPtr varArgs);
// @property (readonly, nonatomic) NSString * _Nonnull absoluteKeypath;
[Export ("absoluteKeypath")]
string AbsoluteKeypath { get; }
// @property (readonly, nonatomic) NSString * _Nonnull currentKey;
[Export ("currentKey")]
string CurrentKey { get; }
// @property (readonly, nonatomic) NSString * _Nonnull currentKeyPath;
[Export ("currentKeyPath")]
string CurrentKeyPath { get; }
// @property (readonly, nonatomic) NSDictionary * _Nonnull searchResults;
[Export ("searchResults")]
NSDictionary SearchResults { get; }
// @property (readonly, nonatomic) BOOL hasFuzzyWildcard;
[Export ("hasFuzzyWildcard")]
bool HasFuzzyWildcard { get; }
// @property (readonly, nonatomic) BOOL hasWildcard;
[Export ("hasWildcard")]
bool HasWildcard { get; }
// @property (readonly, nonatomic) BOOL endOfKeypath;
[Export ("endOfKeypath")]
bool EndOfKeypath { get; }
// -(BOOL)pushKey:(NSString * _Nonnull)key;
[Export ("pushKey:")]
bool PushKey (string key);
// -(void)popKey;
[Export ("popKey")]
void PopKey ();
// -(void)popToRootKey;
[Export ("popToRootKey")]
void PopToRootKey ();
// -(void)addSearchResultForCurrentPath:(id _Nonnull)result;
[Export ("addSearchResultForCurrentPath:")]
void AddSearchResultForCurrentPath (NSObject result);
}
// @protocol LOTValueDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface LOTValueDelegate
{
}
// @protocol LOTColorValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTColorValueDelegate
{
// @required -(CGColorRef)colorForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress startColor:(CGColorRef)startColor endColor:(CGColorRef)endColor currentColor:(CGColorRef)interpolatedColor;
[Abstract]
[Export ("colorForFrame:startKeyframe:endKeyframe:interpolatedProgress:startColor:endColor:currentColor:")]
unsafe CGColor StartKeyframe (nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress, CGColor startColor, CGColor endColor, CGColor interpolatedColor);
}
// @protocol LOTNumberValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTNumberValueDelegate
{
// @required -(CGFloat)floatValueForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress startValue:(CGFloat)startValue endValue:(CGFloat)endValue currentValue:(CGFloat)interpolatedValue;
[Abstract]
[Export ("floatValueForFrame:startKeyframe:endKeyframe:interpolatedProgress:startValue:endValue:currentValue:")]
nfloat StartKeyframe (nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress, nfloat startValue, nfloat endValue, nfloat interpolatedValue);
}
// @protocol LOTPointValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTPointValueDelegate
{
// @required -(CGPoint)pointForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint currentPoint:(CGPoint)interpolatedPoint;
[Abstract]
[Export ("pointForFrame:startKeyframe:endKeyframe:interpolatedProgress:startPoint:endPoint:currentPoint:")]
CGPoint StartKeyframe (nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress, CGPoint startPoint, CGPoint endPoint, CGPoint interpolatedPoint);
}
// @protocol LOTSizeValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTSizeValueDelegate
{
// @required -(CGSize)sizeForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress startSize:(CGSize)startSize endSize:(CGSize)endSize currentSize:(CGSize)interpolatedSize;
[Abstract]
[Export ("sizeForFrame:startKeyframe:endKeyframe:interpolatedProgress:startSize:endSize:currentSize:")]
CGSize StartKeyframe (nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress, CGSize startSize, CGSize endSize, CGSize interpolatedSize);
}
// @protocol LOTPathValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTPathValueDelegate
{
// @required -(CGPathRef)pathForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress;
[Abstract]
[Export ("pathForFrame:startKeyframe:endKeyframe:interpolatedProgress:")]
unsafe CGPath StartKeyframe (nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress);
}
// typedef void (^LOTAnimationCompletionBlock)(BOOL);
delegate void LOTAnimationCompletionBlock (bool animationFinished);
// @interface LOTAnimationView : NSView
[BaseType (typeof(NSView))]
interface LOTAnimationView
{
// +(instancetype _Nonnull)animationNamed:(NSString * _Nonnull)animationName;
[Static]
[Export ("animationNamed:")]
LOTAnimationView AnimationNamed (string animationName);
// +(instancetype _Nonnull)animationNamed:(NSString * _Nonnull)animationName inBundle:(NSBundle * _Nonnull)bundle;
[Static]
[Export ("animationNamed:inBundle:")]
LOTAnimationView AnimationNamed (string animationName, NSBundle bundle);
// +(instancetype _Nonnull)animationFromJSON:(NSDictionary * _Nonnull)animationJSON;
[Static]
[Export ("animationFromJSON:")]
LOTAnimationView AnimationFromJSON (NSDictionary animationJSON);
// +(instancetype _Nonnull)animationWithFilePath:(NSString * _Nonnull)filePath;
[Static]
[Export ("animationWithFilePath:")]
LOTAnimationView AnimationWithFilePath (string filePath);
// +(instancetype _Nonnull)animationFromJSON:(NSDictionary * _Nullable)animationJSON inBundle:(NSBundle * _Nullable)bundle;
[Static]
[Export ("animationFromJSON:inBundle:")]
LOTAnimationView AnimationFromJSON ([NullAllowed] NSDictionary animationJSON, [NullAllowed] NSBundle bundle);
// -(instancetype _Nonnull)initWithModel:(LOTComposition * _Nullable)model inBundle:(NSBundle * _Nullable)bundle;
[Export ("initWithModel:inBundle:")]
IntPtr Constructor ([NullAllowed] LOTComposition model, [NullAllowed] NSBundle bundle);
// -(instancetype _Nonnull)initWithContentsOfURL:(NSURL * _Nonnull)url;
[Export ("initWithContentsOfURL:")]
IntPtr Constructor (NSUrl url);
// -(void)setAnimationNamed:(NSString * _Nonnull)animationName;
[Export ("setAnimationNamed:")]
void SetAnimationNamed (string animationName);
// @property (readonly, nonatomic) BOOL isAnimationPlaying;
[Export ("isAnimationPlaying")]
bool IsAnimationPlaying { get; }
// @property (assign, nonatomic) BOOL loopAnimation;
[Export ("loopAnimation")]
bool LoopAnimation { get; set; }
// @property (assign, nonatomic) BOOL autoReverseAnimation;
[Export ("autoReverseAnimation")]
bool AutoReverseAnimation { get; set; }
// @property (assign, nonatomic) CGFloat animationProgress;
[Export ("animationProgress")]
nfloat AnimationProgress { get; set; }
// @property (assign, nonatomic) CGFloat animationSpeed;
[Export ("animationSpeed")]
nfloat AnimationSpeed { get; set; }
// @property (readonly, nonatomic) CGFloat animationDuration;
[Export ("animationDuration")]
nfloat AnimationDuration { get; }
// @property (assign, nonatomic) BOOL cacheEnable;
[Export ("cacheEnable")]
bool CacheEnable { get; set; }
// @property (assign, nonatomic) BOOL shouldRasterizeWhenIdle;
[Export("shouldRasterizeWhenIdle")]
bool ShouldRasterizeWhenIdle { get; set; }
// @property (copy, nonatomic) LOTAnimationCompletionBlock _Nullable completionBlock;
[NullAllowed, Export ("completionBlock", ArgumentSemantic.Copy)]
LOTAnimationCompletionBlock CompletionBlock { get; set; }
// @property (nonatomic, strong) LOTComposition * _Nullable sceneModel;
[NullAllowed, Export ("sceneModel", ArgumentSemantic.Strong)]
LOTComposition SceneModel { get; set; }
// -(void)playToProgress:(CGFloat)toProgress withCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export ("playToProgress:withCompletion:")]
void PlayToProgress (nfloat toProgress, [NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)playFromProgress:(CGFloat)fromStartProgress toProgress:(CGFloat)toEndProgress withCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export ("playFromProgress:toProgress:withCompletion:")]
void PlayFromProgress (nfloat fromStartProgress, nfloat toEndProgress, [NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)playToFrame:(NSNumber * _Nonnull)toFrame withCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export ("playToFrame:withCompletion:")]
void PlayToFrame (NSNumber toFrame, [NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)playFromFrame:(NSNumber * _Nonnull)fromStartFrame toFrame:(NSNumber * _Nonnull)toEndFrame withCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export ("playFromFrame:toFrame:withCompletion:")]
void PlayFromFrame (NSNumber fromStartFrame, NSNumber toEndFrame, [NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)playWithCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export ("playWithCompletion:")]
void PlayWithCompletion ([NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)play;
[Export ("play")]
void Play ();
// -(void)pause;
[Export ("pause")]
void Pause ();
// -(void)stop;
[Export ("stop")]
void Stop ();
// -(void)setProgressWithFrame:(NSNumber * _Nonnull)currentFrame;
[Export ("setProgressWithFrame:")]
void SetProgressWithFrame (NSNumber currentFrame);
// -(void)forceDrawingUpdate;
[Export ("forceDrawingUpdate")]
void ForceDrawingUpdate ();
// -(void)logHierarchyKeypaths;
[Export ("logHierarchyKeypaths")]
void LogHierarchyKeypaths ();
// -(void)setValueDelegate:(id<LOTValueDelegate> _Nonnull)delegates forKeypath:(LOTKeypath * _Nonnull)keypath;
[Export ("setValueDelegate:forKeypath:")]
void SetValueDelegate (NSObject delegates, LOTKeypath keypath);
// -(NSArray * _Nullable)keysForKeyPath:(LOTKeypath * _Nonnull)keypath;
[Export ("keysForKeyPath:")]
[return: NullAllowed]
LOTKeypath[] KeysForKeyPath (LOTKeypath keypath);
// -(CGPoint)convertPoint:(CGPoint)point toKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export ("convertPoint:toKeypathLayer:")]
CGPoint ConvertPointToKeypath (CGPoint point, LOTKeypath keypath);
// -(CGRect)convertRect:(CGRect)rect toKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export ("convertRect:toKeypathLayer:")]
CGRect ConvertRectToKeypath (CGRect rect, LOTKeypath keypath);
// -(CGPoint)convertPoint:(CGPoint)point fromKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export ("convertPoint:fromKeypathLayer:")]
CGPoint ConvertPointFromKeypath (CGPoint point, LOTKeypath keypath);
// -(CGRect)convertRect:(CGRect)rect fromKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export ("convertRect:fromKeypathLayer:")]
CGRect ConvertRectFromKeypath (CGRect rect, LOTKeypath keypath);
// -(void)addSubview:(NSView * _Nonnull)view toKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export ("addSubview:toKeypathLayer:")]
void AddSubview (NSView view, LOTKeypath keypath);
// -(void)maskSubview:(NSView * _Nonnull)view toKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export ("maskSubview:toKeypathLayer:")]
void MaskSubview (NSView view, LOTKeypath keypath);
// @property (nonatomic) LOTViewContentMode contentMode;
[Export ("contentMode", ArgumentSemantic.Assign)]
LOTViewContentMode ContentMode { get; set; }
// -(void)setValue:(id _Nonnull)value forKeypath:(NSString * _Nonnull)keypath atFrame:(NSNumber * _Nullable)frame __attribute__((deprecated("")));
[Export ("setValue:forKeypath:atFrame:")]
void SetValue (NSObject value, string keypath, [NullAllowed] NSNumber frame);
// -(void)addSubview:(NSView * _Nonnull)view toLayerNamed:(NSString * _Nonnull)layer applyTransform:(BOOL)applyTransform __attribute__((deprecated("")));
[Export ("addSubview:toLayerNamed:applyTransform:")]
void AddSubview (NSView view, string layer, bool applyTransform);
// -(CGRect)convertRect:(CGRect)rect toLayerNamed:(NSString * _Nullable)layerName __attribute__((deprecated("")));
[Export ("convertRect:toLayerNamed:")]
CGRect ConvertRect (CGRect rect, [NullAllowed] string layerName);
}
// @interface LOTAnimationCache : NSObject
[BaseType (typeof(NSObject))]
interface LOTAnimationCache
{
// +(instancetype _Nonnull)sharedCache;
[Static]
[Export ("sharedCache")]
LOTAnimationCache SharedCache ();
// -(void)addAnimation:(LOTComposition * _Nonnull)animation forKey:(NSString * _Nonnull)key;
[Export ("addAnimation:forKey:")]
void AddAnimation (LOTComposition animation, string key);
// -(LOTComposition * _Nullable)animationForKey:(NSString * _Nonnull)key;
[Export ("animationForKey:")]
[return: NullAllowed]
LOTComposition AnimationForKey (string key);
// -(void)removeAnimationForKey:(NSString * _Nonnull)key;
[Export ("removeAnimationForKey:")]
void RemoveAnimationForKey (string key);
// -(void)clearCache;
[Export ("clearCache")]
void ClearCache ();
// -(void)disableCaching;
[Export ("disableCaching")]
void DisableCaching ();
}
// typedef CGColorRef _Nonnull (^LOTColorValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat, CGColorRef _Nullable, CGColorRef _Nullable, CGColorRef _Nullable);
unsafe delegate CGColor LOTColorValueCallbackBlock (nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress, [NullAllowed] CGColor startColor, [NullAllowed] CGColor endColor, [NullAllowed] CGColor interpolatedColor);
// typedef CGFloat (^LOTNumberValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat, CGFloat, CGFloat, CGFloat);
delegate nfloat LOTNumberValueCallbackBlock (nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress, nfloat startValue, nfloat endValue, nfloat interpolatedValue);
// typedef CGPoint (^LOTPointValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat, CGPoint, CGPoint, CGPoint);
delegate CGPoint LOTPointValueCallbackBlock (nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress, CGPoint startPoint, CGPoint endPoint, CGPoint interpolatedPoint);
// typedef CGSize (^LOTSizeValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat, CGSize, CGSize, CGSize);
delegate CGSize LOTSizeValueCallbackBlock (nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress, CGSize startSize, CGSize endSize, CGSize interpolatedSize);
// typedef CGPathRef _Nonnull (^LOTPathValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat);
unsafe delegate CGPath LOTPathValueCallbackBlock (nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress);
// @interface LOTColorBlockCallback : NSObject <LOTColorValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTColorBlockCallback : LOTColorValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTColorValueCallbackBlock _Nonnull)block;
[Static]
[Export ("withBlock:")]
LOTColorBlockCallback WithBlock (LOTColorValueCallbackBlock block);
// @property (copy, nonatomic) LOTColorValueCallbackBlock _Nonnull callback;
[Export ("callback", ArgumentSemantic.Copy)]
LOTColorValueCallbackBlock Callback { get; set; }
}
// @interface LOTNumberBlockCallback : NSObject <LOTNumberValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTNumberBlockCallback : LOTNumberValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTNumberValueCallbackBlock _Nonnull)block;
[Static]
[Export ("withBlock:")]
LOTNumberBlockCallback WithBlock (LOTNumberValueCallbackBlock block);
// @property (copy, nonatomic) LOTNumberValueCallbackBlock _Nonnull callback;
[Export ("callback", ArgumentSemantic.Copy)]
LOTNumberValueCallbackBlock Callback { get; set; }
}
// @interface LOTPointBlockCallback : NSObject <LOTPointValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTPointBlockCallback : LOTPointValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTPointValueCallbackBlock _Nonnull)block;
[Static]
[Export ("withBlock:")]
LOTPointBlockCallback WithBlock (LOTPointValueCallbackBlock block);
// @property (copy, nonatomic) LOTPointValueCallbackBlock _Nonnull callback;
[Export ("callback", ArgumentSemantic.Copy)]
LOTPointValueCallbackBlock Callback { get; set; }
}
// @interface LOTSizeBlockCallback : NSObject <LOTSizeValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTSizeBlockCallback : LOTSizeValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTSizeValueCallbackBlock _Nonnull)block;
[Static]
[Export ("withBlock:")]
LOTSizeBlockCallback WithBlock (LOTSizeValueCallbackBlock block);
// @property (copy, nonatomic) LOTSizeValueCallbackBlock _Nonnull callback;
[Export ("callback", ArgumentSemantic.Copy)]
LOTSizeValueCallbackBlock Callback { get; set; }
}
// @interface LOTPathBlockCallback : NSObject <LOTPathValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTPathBlockCallback : LOTPathValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTPathValueCallbackBlock _Nonnull)block;
[Static]
[Export ("withBlock:")]
LOTPathBlockCallback WithBlock (LOTPathValueCallbackBlock block);
// @property (copy, nonatomic) LOTPathValueCallbackBlock _Nonnull callback;
[Export ("callback", ArgumentSemantic.Copy)]
LOTPathValueCallbackBlock Callback { get; set; }
}
// @interface LOTPointInterpolatorCallback : NSObject <LOTPointValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTPointInterpolatorCallback : LOTPointValueDelegate
{
// +(instancetype _Nonnull)withFromPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint;
[Static]
[Export ("withFromPoint:toPoint:")]
LOTPointInterpolatorCallback WithFromPoint (CGPoint fromPoint, CGPoint toPoint);
// @property (nonatomic) CGPoint fromPoint;
[Export ("fromPoint", ArgumentSemantic.Assign)]
CGPoint FromPoint { get; set; }
// @property (nonatomic) CGPoint toPoint;
[Export ("toPoint", ArgumentSemantic.Assign)]
CGPoint ToPoint { get; set; }
// @property (assign, nonatomic) CGFloat currentProgress;
[Export ("currentProgress")]
nfloat CurrentProgress { get; set; }
}
// @interface LOTSizeInterpolatorCallback : NSObject <LOTSizeValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTSizeInterpolatorCallback : LOTSizeValueDelegate
{
// +(instancetype _Nonnull)withFromSize:(CGSize)fromSize toSize:(CGSize)toSize;
[Static]
[Export ("withFromSize:toSize:")]
LOTSizeInterpolatorCallback WithFromSize (CGSize fromSize, CGSize toSize);
// @property (nonatomic) CGSize fromSize;
[Export ("fromSize", ArgumentSemantic.Assign)]
CGSize FromSize { get; set; }
// @property (nonatomic) CGSize toSize;
[Export ("toSize", ArgumentSemantic.Assign)]
CGSize ToSize { get; set; }
// @property (assign, nonatomic) CGFloat currentProgress;
[Export ("currentProgress")]
nfloat CurrentProgress { get; set; }
}
// @interface LOTFloatInterpolatorCallback : NSObject <LOTNumberValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTFloatInterpolatorCallback : LOTNumberValueDelegate
{
// +(instancetype _Nonnull)withFromFloat:(CGFloat)fromFloat toFloat:(CGFloat)toFloat;
[Static]
[Export ("withFromFloat:toFloat:")]
LOTFloatInterpolatorCallback WithFromFloat (nfloat fromFloat, nfloat toFloat);
// @property (nonatomic) CGFloat fromFloat;
[Export ("fromFloat")]
nfloat FromFloat { get; set; }
// @property (nonatomic) CGFloat toFloat;
[Export ("toFloat")]
nfloat ToFloat { get; set; }
// @property (assign, nonatomic) CGFloat currentProgress;
[Export ("currentProgress")]
nfloat CurrentProgress { get; set; }
}
// @interface LOTColorValueCallback : NSObject <LOTColorValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTColorValueCallback : LOTColorValueDelegate
{
// +(instancetype _Nonnull)withCGColor:(CGColorRef _Nonnull)color;
[Static]
[Export ("withCGColor:")]
unsafe LOTColorValueCallback WithCGColor (CGColor color);
// @property (nonatomic) CGColorRef _Nonnull colorValue;
[Export ("colorValue", ArgumentSemantic.Assign)]
unsafe CGColor ColorValue { get; set; }
}
// @interface LOTNumberValueCallback : NSObject <LOTNumberValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTNumberValueCallback : LOTNumberValueDelegate
{
// +(instancetype _Nonnull)withFloatValue:(CGFloat)numberValue;
[Static]
[Export ("withFloatValue:")]
LOTNumberValueCallback WithFloatValue (nfloat numberValue);
// @property (assign, nonatomic) CGFloat numberValue;
[Export ("numberValue")]
nfloat NumberValue { get; set; }
}
// @interface LOTPointValueCallback : NSObject <LOTPointValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTPointValueCallback : LOTPointValueDelegate
{
// +(instancetype _Nonnull)withPointValue:(CGPoint)pointValue;
[Static]
[Export ("withPointValue:")]
LOTPointValueCallback WithPointValue (CGPoint pointValue);
// @property (assign, nonatomic) CGPoint pointValue;
[Export ("pointValue", ArgumentSemantic.Assign)]
CGPoint PointValue { get; set; }
}
// @interface LOTSizeValueCallback : NSObject <LOTSizeValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTSizeValueCallback : LOTSizeValueDelegate
{
// +(instancetype _Nonnull)withPointValue:(CGSize)sizeValue;
[Static]
[Export ("withPointValue:")]
LOTSizeValueCallback WithPointValue (CGSize sizeValue);
// @property (assign, nonatomic) CGSize sizeValue;
[Export ("sizeValue", ArgumentSemantic.Assign)]
CGSize SizeValue { get; set; }
}
// @interface LOTPathValueCallback : NSObject <LOTPathValueDelegate>
[BaseType (typeof(NSObject))]
interface LOTPathValueCallback : LOTPathValueDelegate
{
// +(instancetype _Nonnull)withCGPath:(CGPathRef _Nonnull)path;
[Static]
[Export ("withCGPath:")]
unsafe LOTPathValueCallback WithCGPath (CGPath path);
// @property (nonatomic) CGPathRef _Nonnull pathValue;
[Export ("pathValue", ArgumentSemantic.Assign)]
unsafe CGPath PathValue { get; set; }
}
}
| |
using System;
using System.Linq;
namespace CapnProto.Schema.Parser
{
class CapnpVisitor
{
protected Boolean mEnableNestedType = true;
protected CapnpModule mActiveModule;
protected void EnableNestedType()
{
mEnableNestedType = true;
}
protected void DisableNestedType()
{
mEnableNestedType = false;
}
public virtual CapnpType Visit(CapnpType target)
{
if (target == null) return null;
return target.Accept(this);
}
protected internal virtual CapnpType VisitPrimitive(CapnpPrimitive primitive)
{
return primitive;
}
protected internal virtual CapnpType VisitList(CapnpList list)
{
list.Parameter = Visit(list.Parameter);
return list;
}
protected internal virtual Value VisitValue(Value value)
{
return value;
}
protected internal virtual CapnpModule VisitModule(CapnpModule module)
{
// An imported module has already been processed.
if (mActiveModule != null && mActiveModule != module) return module;
mActiveModule = module;
module.Structs = module.Structs.Select(s => VisitStruct(s)).ToArray();
module.Interfaces = module.Interfaces.Select(i => VisitInterface(i)).ToArray();
module.Constants = module.Constants.Select(c => VisitConst(c)).ToArray();
module.Enumerations = module.Enumerations.Select(e => VisitEnum(e)).ToArray();
module.AnnotationDefs = module.AnnotationDefs.Select(a => VisitAnnotationDecl(a)).ToArray();
module.Usings = module.Usings.Select(u => VisitUsing(u)).ToArray();
module.Annotations = module.Annotations.Select(a => VisitAnnotation(a)).ToArray();
return module;
}
protected internal virtual Annotation VisitAnnotation(Annotation annotation)
{
if (annotation == null) return null;
annotation.Declaration = Visit(annotation.Declaration);
annotation.Argument = VisitValue(annotation.Argument);
return annotation;
}
protected internal virtual CapnpStruct VisitStruct(CapnpStruct @struct)
{
if (!mEnableNestedType) return @struct;
@struct.Structs = @struct.Structs.Select(s => VisitStruct(s)).ToArray();
@struct.Interfaces = @struct.Interfaces.Select(i => VisitInterface(i)).ToArray();
DisableNestedType();
@struct.Enumerations = @struct.Enumerations.Select(e => VisitEnum(e)).ToArray();
@struct.Fields = @struct.Fields.Select(f => VisitField(f)).ToArray();
@struct.AnnotationDefs = @struct.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray();
@struct.Annotations = @struct.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@struct.Usings = @struct.Usings.Select(u => VisitUsing(u)).ToArray();
@struct.Constants = @struct.Constants.Select(c => VisitConst(c)).ToArray();
EnableNestedType();
return @struct;
}
protected internal virtual CapnpInterface VisitInterface(CapnpInterface @interface)
{
if (!mEnableNestedType) return @interface;
@interface.Structs = @interface.Structs.Select(s => VisitStruct(s)).ToArray();
@interface.Interfaces = @interface.Interfaces.Select(i => VisitInterface(i)).ToArray();
DisableNestedType();
@interface.Enumerations = @interface.Enumerations.Select(e => VisitEnum(e)).ToArray();
@interface.BaseInterfaces = @interface.BaseInterfaces.Select(i => Visit(i)).ToArray();
@interface.AnnotationDefs = @interface.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray();
@interface.Annotations = @interface.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@interface.Methods = @interface.Methods.Select(m => VisitMethod(m)).ToArray();
@interface.Usings = @interface.Usings.Select(u => VisitUsing(u)).ToArray();
@interface.Constants = @interface.Constants.Select(c => VisitConst(c)).ToArray();
EnableNestedType();
return @interface;
}
protected internal virtual CapnpGenericParameter VisitGenericParameter(CapnpGenericParameter @param)
{
return @param;
}
protected internal virtual CapnpBoundGenericType VisitClosedType(CapnpBoundGenericType closed)
{
closed.OpenType = (CapnpNamedType)Visit(closed.OpenType);
if (closed.ParentScope != null)
closed.ParentScope = VisitClosedType(closed.ParentScope);
return closed;
}
protected internal virtual CapnpEnum VisitEnum(CapnpEnum @enum)
{
@enum.Annotations = @enum.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@enum.Enumerants = @enum.Enumerants.Select(e => VisitEnumerant(e)).ToArray();
return @enum;
}
protected internal virtual Enumerant VisitEnumerant(Enumerant e)
{
e.Annotation = VisitAnnotation(e.Annotation);
return e;
}
protected internal virtual Field VisitField(Field fld)
{
fld.Type = Visit(fld.Type);
fld.Value = VisitValue(fld.Value);
fld.Annotation = VisitAnnotation(fld.Annotation);
return fld;
}
protected internal virtual Method VisitMethod(Method method)
{
if (method.Arguments.Params != null)
method.Arguments.Params = method.Arguments.Params.Select(p => VisitParameter(p)).ToArray();
else
method.Arguments.Struct = Visit(method.Arguments.Struct);
if (method.ReturnType.Params != null)
method.ReturnType.Params = method.ReturnType.Params.Select(p => VisitParameter(p)).ToArray();
else
method.ReturnType.Struct = Visit(method.ReturnType.Struct);
method.Annotation = VisitAnnotation(method.Annotation);
return method;
}
protected internal virtual Parameter VisitParameter(Parameter p)
{
p.Type = Visit(p.Type);
p.Annotation = VisitAnnotation(p.Annotation);
p.DefaultValue = VisitValue(p.DefaultValue);
return p;
}
protected internal virtual CapnpGroup VisitGroup(CapnpGroup grp)
{
grp.Fields = grp.Fields.Select(f => VisitField(f)).ToArray();
return grp;
}
protected internal virtual CapnpUnion VisitUnion(CapnpUnion union)
{
union.Fields = union.Fields.Select(u => VisitField(u)).ToArray();
return union;
}
protected internal virtual CapnpType VisitReference(CapnpReference @ref)
{
return @ref;
}
protected internal virtual CapnpConst VisitConst(CapnpConst @const)
{
@const.Value = VisitValue(@const.Value);
return @const;
}
protected internal virtual CapnpType VisitImport(CapnpImport import)
{
import.Type = Visit(import.Type);
return import;
}
protected internal virtual CapnpUsing VisitUsing(CapnpUsing @using)
{
@using.Target = Visit(@using.Target);
return @using;
}
protected internal virtual CapnpAnnotation VisitAnnotationDecl(CapnpAnnotation annotation)
{
annotation.ArgumentType = Visit(annotation.ArgumentType);
return annotation;
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.IO;
using System.Threading;
using Belikov.GenuineChannels.Connection;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.Parameters;
using Belikov.GenuineChannels.TransportContext;
using Belikov.GenuineChannels.Utilities;
namespace Belikov.GenuineChannels.GenuineSharedMemory
{
/// <summary>
/// Implements a Shared Memory listener which is capable of accepting inbound client's requests.
/// </summary>
internal class SMAcceptConnectionClosure
{
/// <summary>
/// Constructs an instance of the SMAcceptConnectionClosure class.
/// </summary>
/// <param name="iTransportContext">The transport context.</param>
/// <param name="sharedMemoryConnection">The server's connection.</param>
/// <param name="sharedMemoryConnectionManager">The connection manager.</param>
/// <param name="shareName">The name of the share.</param>
public SMAcceptConnectionClosure(ITransportContext iTransportContext, SharedMemoryConnection sharedMemoryConnection, SharedMemoryConnectionManager sharedMemoryConnectionManager, string shareName)
{
this.ITransportContext = iTransportContext;
this.SharedMemoryConnection = sharedMemoryConnection;
this.SharedMemoryConnectionManager = sharedMemoryConnectionManager;
this.ShareName = shareName;
}
/// <summary>
/// The transport context.
/// </summary>
public ITransportContext ITransportContext;
/// <summary>
/// The server's memory share.
/// </summary>
public SharedMemoryConnection SharedMemoryConnection;
/// <summary>
/// The connection manager.
/// </summary>
public SharedMemoryConnectionManager SharedMemoryConnectionManager;
/// <summary>
/// Name of the share.
/// </summary>
public string ShareName;
/// <summary>
/// Indicates whether the listening should be stopped.
/// </summary>
public ManualResetEvent StopListening = new ManualResetEvent(false);
private Mutex _mutex;
private NamedEvent _clientConnectedEvent;
private NamedEvent _clientAcceptedEvent;
/// <summary>
/// Accepts incoming connections.
/// </summary>
public void AcceptConnections()
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
byte protocolVersion;
GenuineConnectionType genuineConnectionType;
try
{
IParameterProvider parameters = this.ITransportContext.IParameterProvider;
string mutexName = GenuineSharedMemoryChannel.ConstructSharedObjectName(
"MUTEX" + this.ShareName, parameters);
string clientConnected = GenuineSharedMemoryChannel.ConstructSharedObjectName(
"CC" + this.ShareName, parameters);
string clientAccepted = GenuineSharedMemoryChannel.ConstructSharedObjectName(
"CA" + this.ShareName, parameters);
this._mutex = WindowsAPI.CreateMutex(mutexName);
this._clientConnectedEvent = NamedEvent.CreateNamedEvent(clientConnected, false, false);
this._clientAcceptedEvent = NamedEvent.CreateNamedEvent(clientAccepted, false, true);
WaitHandle[] handles = new WaitHandle[2] { this._clientConnectedEvent.ManualResetEvent, this.StopListening };
for ( ; ; )
{
try
{
// listen
WaitHandle.WaitAny(handles);
// if shutting down
if (this.StopListening.WaitOne(0, false))
return ;
// set timeout
int timeout = GenuineUtility.GetTimeout((TimeSpan) this.ITransportContext.IParameterProvider[GenuineParameter.ConnectTimeout]);
// client is connecting
using (Stream headerStream = this.SharedMemoryConnection.LowLevel_ReadSync(timeout))
{
BinaryReader binaryReader = new BinaryReader(headerStream);
string connectionId;
MessageCoder.DeserializeConnectionHeader(binaryReader, out protocolVersion, out genuineConnectionType, out connectionId);
string shareName = binaryReader.ReadString();
this._clientAcceptedEvent.ManualResetEvent.Set();
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.AcceptingConnection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.AcceptingConnection, "SMAcceptConnectionClosure.AcceptConnections",
LogMessageType.ConnectionAccepting, null, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"An inbound Shared Memory connection is being accepted.");
}
AcceptConnectionInformation acceptConnectionInformation = new AcceptConnectionInformation();
acceptConnectionInformation.ShareName = shareName;
acceptConnectionInformation.ProtocolVersion = protocolVersion;
GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.AcceptConnection), acceptConnectionInformation, true);
}
}
catch(Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.AcceptingConnection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.AcceptingConnection, "SMAcceptConnectionClosure.AcceptConnections",
LogMessageType.ConnectionAccepting, ex, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"Can't accept a connection.");
}
}
}
}
catch(Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.AcceptingConnection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.AcceptingConnection, "SMAcceptConnectionClosure.AcceptConnections",
LogMessageType.CriticalError, ex, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"Critical listener failure. No connections will be accepted.");
}
this.SharedMemoryConnectionManager.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.GeneralListenerFailure, ex, null, this.ShareName));
}
finally
{
this.SharedMemoryConnection.ReleaseUnmanagedResources();
if (this._mutex != null)
this._mutex.Close();
}
}
/// <summary>
/// Contains information about the connection being accepted.
/// </summary>
private class AcceptConnectionInformation
{
/// <summary>
/// The name of the client share.
/// </summary>
public string ShareName;
/// <summary>
/// The version of the protocol supported by the client.
/// </summary>
public byte ProtocolVersion;
}
/// <summary>
/// Accepts incoming connection.
/// </summary>
/// <param name="acceptConnectionInformationAsObject">Information about the connection being accepted.</param>
public void AcceptConnection(object acceptConnectionInformationAsObject)
{
AcceptConnectionInformation acceptConnectionInformation = (AcceptConnectionInformation) acceptConnectionInformationAsObject;
try
{
this.SharedMemoryConnectionManager.Connection_AcceptConnection(acceptConnectionInformation.ShareName, acceptConnectionInformation.ProtocolVersion);
}
catch(Exception ex)
{
this.ITransportContext.BinaryLogWriter.WriteEvent(LogCategory.Connection, "SMAcceptConnectionClosure.AcceptConnection",
LogMessageType.ConnectionAccepting, ex, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"The connection to {0} has been refused due to the exception.", acceptConnectionInformation.ShareName);
this.SharedMemoryConnectionManager.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.GeneralListenerFailure, ex, null, acceptConnectionInformation.ShareName));
}
}
}
}
| |
// Copyright (C) 2015-2021 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using Neo.Cryptography.ECC;
using Neo.IO.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
namespace Neo.SmartContract
{
/// <summary>
/// Represents a parameter of a contract method.
/// </summary>
public class ContractParameter
{
/// <summary>
/// The type of the parameter.
/// </summary>
public ContractParameterType Type;
/// <summary>
/// The value of the parameter.
/// </summary>
public object Value;
/// <summary>
/// Initializes a new instance of the <see cref="ContractParameter"/> class.
/// </summary>
public ContractParameter() { }
/// <summary>
/// Initializes a new instance of the <see cref="ContractParameter"/> class with the specified type.
/// </summary>
/// <param name="type">The type of the parameter.</param>
public ContractParameter(ContractParameterType type)
{
this.Type = type;
this.Value = type switch
{
ContractParameterType.Any => null,
ContractParameterType.Signature => new byte[64],
ContractParameterType.Boolean => false,
ContractParameterType.Integer => 0,
ContractParameterType.Hash160 => new UInt160(),
ContractParameterType.Hash256 => new UInt256(),
ContractParameterType.ByteArray => Array.Empty<byte>(),
ContractParameterType.PublicKey => ECCurve.Secp256r1.G,
ContractParameterType.String => "",
ContractParameterType.Array => new List<ContractParameter>(),
ContractParameterType.Map => new List<KeyValuePair<ContractParameter, ContractParameter>>(),
_ => throw new ArgumentException(null, nameof(type)),
};
}
/// <summary>
/// Converts the parameter from a JSON object.
/// </summary>
/// <param name="json">The parameter represented by a JSON object.</param>
/// <returns>The converted parameter.</returns>
public static ContractParameter FromJson(JObject json)
{
ContractParameter parameter = new()
{
Type = Enum.Parse<ContractParameterType>(json["type"].GetString())
};
if (json["value"] != null)
parameter.Value = parameter.Type switch
{
ContractParameterType.Signature or ContractParameterType.ByteArray => Convert.FromBase64String(json["value"].AsString()),
ContractParameterType.Boolean => json["value"].AsBoolean(),
ContractParameterType.Integer => BigInteger.Parse(json["value"].AsString()),
ContractParameterType.Hash160 => UInt160.Parse(json["value"].AsString()),
ContractParameterType.Hash256 => UInt256.Parse(json["value"].AsString()),
ContractParameterType.PublicKey => ECPoint.Parse(json["value"].AsString(), ECCurve.Secp256r1),
ContractParameterType.String => json["value"].AsString(),
ContractParameterType.Array => ((JArray)json["value"]).Select(p => FromJson(p)).ToList(),
ContractParameterType.Map => ((JArray)json["value"]).Select(p => new KeyValuePair<ContractParameter, ContractParameter>(FromJson(p["key"]), FromJson(p["value"]))).ToList(),
_ => throw new ArgumentException(null, nameof(json)),
};
return parameter;
}
/// <summary>
/// Sets the value of the parameter.
/// </summary>
/// <param name="text">The <see cref="string"/> form of the value.</param>
public void SetValue(string text)
{
switch (Type)
{
case ContractParameterType.Signature:
byte[] signature = text.HexToBytes();
if (signature.Length != 64) throw new FormatException();
Value = signature;
break;
case ContractParameterType.Boolean:
Value = string.Equals(text, bool.TrueString, StringComparison.OrdinalIgnoreCase);
break;
case ContractParameterType.Integer:
Value = BigInteger.Parse(text);
break;
case ContractParameterType.Hash160:
Value = UInt160.Parse(text);
break;
case ContractParameterType.Hash256:
Value = UInt256.Parse(text);
break;
case ContractParameterType.ByteArray:
Value = text.HexToBytes();
break;
case ContractParameterType.PublicKey:
Value = ECPoint.Parse(text, ECCurve.Secp256r1);
break;
case ContractParameterType.String:
Value = text;
break;
default:
throw new ArgumentException();
}
}
/// <summary>
/// Converts the parameter to a JSON object.
/// </summary>
/// <returns>The parameter represented by a JSON object.</returns>
public JObject ToJson()
{
return ToJson(this, null);
}
private static JObject ToJson(ContractParameter parameter, HashSet<ContractParameter> context)
{
JObject json = new();
json["type"] = parameter.Type;
if (parameter.Value != null)
switch (parameter.Type)
{
case ContractParameterType.Signature:
case ContractParameterType.ByteArray:
json["value"] = Convert.ToBase64String((byte[])parameter.Value);
break;
case ContractParameterType.Boolean:
json["value"] = (bool)parameter.Value;
break;
case ContractParameterType.Integer:
case ContractParameterType.Hash160:
case ContractParameterType.Hash256:
case ContractParameterType.PublicKey:
case ContractParameterType.String:
json["value"] = parameter.Value.ToString();
break;
case ContractParameterType.Array:
if (context is null)
context = new HashSet<ContractParameter>();
else if (context.Contains(parameter))
throw new InvalidOperationException();
context.Add(parameter);
json["value"] = new JArray(((IList<ContractParameter>)parameter.Value).Select(p => ToJson(p, context)));
break;
case ContractParameterType.Map:
if (context is null)
context = new HashSet<ContractParameter>();
else if (context.Contains(parameter))
throw new InvalidOperationException();
context.Add(parameter);
json["value"] = new JArray(((IList<KeyValuePair<ContractParameter, ContractParameter>>)parameter.Value).Select(p =>
{
JObject item = new();
item["key"] = ToJson(p.Key, context);
item["value"] = ToJson(p.Value, context);
return item;
}));
break;
}
return json;
}
public override string ToString()
{
return ToString(this, null);
}
private static string ToString(ContractParameter parameter, HashSet<ContractParameter> context)
{
switch (parameter.Value)
{
case null:
return "(null)";
case byte[] data:
return data.ToHexString();
case IList<ContractParameter> data:
if (context is null) context = new HashSet<ContractParameter>();
if (context.Contains(parameter))
{
return "(array)";
}
else
{
context.Add(parameter);
StringBuilder sb = new();
sb.Append('[');
foreach (ContractParameter item in data)
{
sb.Append(ToString(item, context));
sb.Append(", ");
}
if (data.Count > 0)
sb.Length -= 2;
sb.Append(']');
return sb.ToString();
}
case IList<KeyValuePair<ContractParameter, ContractParameter>> data:
if (context is null) context = new HashSet<ContractParameter>();
if (context.Contains(parameter))
{
return "(map)";
}
else
{
context.Add(parameter);
StringBuilder sb = new();
sb.Append('[');
foreach (var item in data)
{
sb.Append('{');
sb.Append(ToString(item.Key, context));
sb.Append(',');
sb.Append(ToString(item.Value, context));
sb.Append('}');
sb.Append(", ");
}
if (data.Count > 0)
sb.Length -= 2;
sb.Append(']');
return sb.ToString();
}
default:
return parameter.Value.ToString();
}
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
using System;
using System.IO;
using System.Reflection;
namespace NUnit.Framework.Tests
{
public class TestDirectory : IDisposable
{
private bool _disposedValue = false;
public string directoryName;
public DirectoryInfo directoryInformation;
public DirectoryInfo diSubSubDirectory;
#region TestDirectory Utility Class
public TestDirectory(string dirName) : this(dirName, true) { }
public TestDirectory(string dirName, bool CreateSubDirectory)
{
this.directoryName = Path.Combine(Path.GetTempPath(), dirName);
directoryInformation = Directory.CreateDirectory(this.directoryName);
if (CreateSubDirectory)
{
DirectoryInfo diSubDirectory = directoryInformation.CreateSubdirectory("SubDirectory");
diSubSubDirectory = diSubDirectory.CreateSubdirectory("SubSubDirectory");
}
}
protected virtual void Dispose(bool disposing)
{
if (!this._disposedValue)
{
if (disposing)
{
if (Directory.Exists(directoryName))
{
Directory.Delete(directoryName,true);
}
}
}
this._disposedValue = true;
}
#region IDisposable Members
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#endregion
}
/// <summary>
/// Summary description for DirectoryAssertTests.
/// </summary>
[TestFixture, Obsolete("DirectoryAssert is obsolete")]
public class DirectoryAssertTests : MessageChecker
{
#region AreEqual
#region Success Tests
[Test]
public void AreEqualPassesWhenBothAreNull()
{
DirectoryInfo expected = null;
DirectoryInfo actual = null;
DirectoryAssert.AreEqual(expected, actual);
}
[Test]
public void AreEqualPassesWithDirectoryInfos()
{
using (TestDirectory td = new TestDirectory("ParentDirectory"))
{
DirectoryAssert.AreEqual(td.directoryInformation, td.directoryInformation);
}
}
[Test]
public void AreEqualPassesWithStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory"))
{
DirectoryAssert.AreEqual(td.directoryName, td.directoryName);
}
}
#endregion
#region Failure Tests
[Test, ExpectedException(typeof(AssertionException))]
public void AreEqualFailsWhenOneIsNull()
{
using (TestDirectory td = new TestDirectory("ParentDirectory"))
{
DirectoryAssert.AreEqual(td.directoryInformation, null);
}
}
[Test, ExpectedException(typeof(AssertionException))]
public void AreEqualFailsWhenOneDoesNotExist()
{
using (TestDirectory td = new TestDirectory("ParentDirectory"))
{
DirectoryInfo actual = new DirectoryInfo("NotExistingDirectoryName");
DirectoryAssert.AreEqual(td.directoryInformation, actual);
}
}
[Test, ExpectedException(typeof(AssertionException))]
public void AreEqualFailsWithDirectoryInfos()
{
using (TestDirectory td1 = new TestDirectory("ParentDirectory1"))
{
using (TestDirectory td2 = new TestDirectory("ParentDirectory2"))
{
DirectoryAssert.AreEqual(td1.directoryInformation, td2.directoryInformation);
}
}
}
[Test, ExpectedException(typeof(AssertionException))]
public void AreEqualFailsWithStringPath()
{
using (TestDirectory td1 = new TestDirectory("ParentDirectory1"))
{
using (TestDirectory td2 = new TestDirectory("ParentDirectory2"))
{
DirectoryAssert.AreEqual(td1.directoryName, td2.directoryName);
}
}
}
#endregion
#endregion
#region AreNotEqual
#region Success Tests
[Test]
public void AreNotEqualPassesIfOneIsNull()
{
using (TestDirectory td = new TestDirectory("ParentDirectory"))
{
DirectoryAssert.AreNotEqual(td.directoryInformation, null);
}
}
[Test]
public void AreNotEqualPassesWhenOneDoesNotExist()
{
using (TestDirectory td = new TestDirectory("ParentDirectory"))
{
DirectoryInfo actual = new DirectoryInfo("NotExistingDirectoryName");
DirectoryAssert.AreNotEqual(td.directoryInformation, actual);
}
}
public void AreNotEqualPassesWithDirectoryInfos()
{
using (TestDirectory td1 = new TestDirectory("ParentDirectory1"))
{
using (TestDirectory td2 = new TestDirectory("ParentDirectory2"))
{
DirectoryAssert.AreNotEqual(td1.directoryInformation, td2.directoryInformation);
}
}
}
[Test]
public void AreNotEqualPassesWithStringPath()
{
using (TestDirectory td1 = new TestDirectory("ParentDirectory1"))
{
using (TestDirectory td2 = new TestDirectory("ParentDirectory2"))
{
DirectoryAssert.AreNotEqual(td1.directoryName, td2.directoryName);
}
}
}
#endregion
#region Failure Tests
[Test, ExpectedException(typeof(AssertionException))]
public void AreNotEqualFailsWhenBothAreNull()
{
DirectoryInfo expected = null;
DirectoryInfo actual = null;
expectedMessage =
" Expected: not null" + Environment.NewLine +
" But was: null" + Environment.NewLine;
DirectoryAssert.AreNotEqual(expected, actual);
}
[Test, ExpectedException(typeof(AssertionException))]
public void AreNotEqualFailsWithDirectoryInfos()
{
using (TestDirectory td = new TestDirectory("ParentDirectory"))
{
DirectoryAssert.AreNotEqual(td.directoryInformation, td.directoryInformation);
}
}
[Test, ExpectedException(typeof(AssertionException))]
public void AreNotEqualFailsWithStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory"))
{
DirectoryAssert.AreNotEqual(td.directoryName, td.directoryName);
}
}
#endregion
#endregion
#region IsEmpty
[Test]
public void IsEmptyPassesWithEmptyDirectoryUsingDirectoryInfo()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", false))
{
DirectoryAssert.IsEmpty(td.directoryInformation);
Assert.That(td.directoryInformation, Is.Empty);
}
}
[Test]
public void IsEmptyPassesWithEmptyDirectoryUsingStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", false))
{
DirectoryAssert.IsEmpty(td.directoryName);
}
}
[Test, ExpectedException(typeof(DirectoryNotFoundException))]
public void IsEmptyFailsWithInvalidDirectory()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", false))
{
DirectoryAssert.IsEmpty(td.directoryName + "INVALID");
}
}
[Test,ExpectedException(typeof(ArgumentException))]
public void IsEmptyThrowsUsingNull()
{
DirectoryAssert.IsEmpty((DirectoryInfo)null);
}
[Test, ExpectedException(typeof(AssertionException))]
public void IsEmptyFailsWithNonEmptyDirectoryUsingDirectoryInfo()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryAssert.IsEmpty(td.directoryInformation);
}
}
[Test, ExpectedException(typeof(AssertionException))]
public void IsEmptyFailsWithNonEmptyDirectoryUsingStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryAssert.IsEmpty(td.directoryName);
}
}
#endregion
#region IsNotEmpty
[Test, ExpectedException(typeof(AssertionException))]
public void IsNotEmptyFailsWithEmptyDirectoryUsingDirectoryInfo()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", false))
{
DirectoryAssert.IsNotEmpty(td.directoryInformation);
}
}
[Test, ExpectedException(typeof(AssertionException))]
public void IsNotEmptyFailsWithEmptyDirectoryUsingStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", false))
{
DirectoryAssert.IsNotEmpty(td.directoryName);
}
}
[Test, ExpectedException(typeof(ArgumentException))]
public void IsNotEmptyThrowsUsingNull()
{
DirectoryAssert.IsNotEmpty((DirectoryInfo) null);
}
[Test, ExpectedException(typeof(DirectoryNotFoundException))]
public void IsNotEmptyFailsWithInvalidDirectory()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", false))
{
DirectoryAssert.IsNotEmpty(td.directoryName + "INVALID");
}
}
[Test]
public void IsNotEmptyPassesWithNonEmptyDirectoryUsingDirectoryInfo()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryAssert.IsNotEmpty(td.directoryInformation);
Assert.That(td.directoryInformation, Is.Not.Empty);
}
}
[Test]
public void IsNotEmptyPassesWithNonEmptyDirectoryUsingStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryAssert.IsNotEmpty(td.directoryName);
}
}
#endregion
#region IsWithin
[Test, ExpectedException(typeof(ArgumentException))]
public void IsWithinThrowsWhenBothAreNull()
{
DirectoryInfo expected = null;
DirectoryInfo actual = null;
DirectoryAssert.IsWithin(expected, actual);
}
[Test]
public void IsWithinPassesWithDirectoryInfo()
{
using (TestDirectory td = new TestDirectory("ParentDirectory",true))
{
DirectoryAssert.IsWithin(td.directoryInformation, td.diSubSubDirectory);
}
}
[Test]
public void IsWithinPassesWithStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryAssert.IsWithin(td.directoryName, td.diSubSubDirectory.FullName);
}
}
[Test]
public void IsWithinPassesWithTempPath()
{
// Special case because GetTempPath() returns with a trailing slash
string tempPath = Path.GetTempPath();
string tempPathParent = Path.GetDirectoryName(Path.GetDirectoryName(tempPath));
DirectoryAssert.IsWithin(tempPathParent, tempPath);
}
[Test, ExpectedException(typeof(AssertionException))]
public void IsWithinFailsWhenOutsidePathUsingDirectoryInfo()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryInfo diSystemFolder = new DirectoryInfo(Environment.SpecialFolder.System.ToString());
DirectoryAssert.IsWithin(td.directoryInformation, diSystemFolder);
}
}
[Test, ExpectedException(typeof(AssertionException))]
public void IsWithinFailsWhenOutsidePathUsingStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryAssert.IsWithin(td.directoryName, Environment.SpecialFolder.System.ToString());
}
}
#endregion
#region IsNotWithin
[Test, ExpectedException(typeof(ArgumentException))]
public void IsNotWithinThrowsWhenBothAreNull()
{
DirectoryInfo expected = null;
DirectoryInfo actual = null;
DirectoryAssert.IsNotWithin(expected, actual);
}
[Test]
public void IsNotWithinPassesWhenOutsidePathUsingDirectoryInfo()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryInfo diSystemFolder = new DirectoryInfo(Environment.SpecialFolder.System.ToString());
DirectoryAssert.IsNotWithin(td.directoryInformation, diSystemFolder);
}
}
[Test]
public void IsNotWithinPassesWhenOutsidePathUsingStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryAssert.IsNotWithin(td.directoryName, Environment.SpecialFolder.System.ToString());
}
}
[Test, ExpectedException(typeof(AssertionException))]
public void IsNotWithinFailsWithDirectoryInfo()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryAssert.IsNotWithin(td.directoryInformation, td.diSubSubDirectory);
}
}
[Test, ExpectedException(typeof(AssertionException))]
public void IsNotWithinFailsWithStringPath()
{
using (TestDirectory td = new TestDirectory("ParentDirectory", true))
{
DirectoryAssert.IsNotWithin(td.directoryName, td.diSubSubDirectory.FullName);
}
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// 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.
// ------------------------------------------------------------------------------
namespace Microsoft.Live.Controls
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
/// <summary>
/// This partial class contains Windows Phone specific code for the SignInButton.
/// </summary>
public partial class SignInButton : Button
{
#region Fields
public static readonly DependencyProperty BrandingProperty = DependencyProperty.Register(
"Branding",
typeof(BrandingType),
typeof(SignInButton),
new PropertyMetadata(default(BrandingType)));
public static readonly DependencyProperty ButtonTextTypeProperty = DependencyProperty.Register(
"ButtonTextType",
typeof(ButtonTextType),
typeof(SignInButton),
new PropertyMetadata(default(ButtonTextType)));
public static readonly DependencyProperty ButtonTextProperty = DependencyProperty.Register(
"ButtonText",
typeof(string),
typeof(SignInButton),
new PropertyMetadata(ResourceHelper.GetResourceString("SignIn")));
public static readonly DependencyProperty ClientIdProperty = DependencyProperty.Register(
"ClientId",
typeof(string),
typeof(SignInButton),
new PropertyMetadata(null));
public static readonly DependencyProperty ScopesProperty = DependencyProperty.Register(
"Scopes",
typeof(string),
typeof(SignInButton),
new PropertyMetadata(null));
public static readonly DependencyProperty SignInTextProperty = DependencyProperty.Register(
"SignInText",
typeof(string),
typeof(SignInButton),
new PropertyMetadata(ResourceHelper.GetResourceString("SignIn")));
public static readonly DependencyProperty SignOutTextProperty = DependencyProperty.Register(
"SignOutText",
typeof(string),
typeof(SignInButton),
new PropertyMetadata(ResourceHelper.GetResourceString("SignOut")));
public static readonly DependencyProperty IconTextProperty = DependencyProperty.Register(
"IconText",
typeof (string),
typeof (SignInButton),
new PropertyMetadata(SkyDriveIcon));
// Icons are stored characters in the LiveSymbol.ttf
private const string SkyDriveIcon = "\uE180";
private const string OutlookIcon = "\uE181";
private const string MessengerIcon = "\uE182";
private const string MicrosoftAccountIcon = "\uE183";
private bool hasPendingLoginRequest;
#endregion
#region Properties & Events
/// <summary>
/// Gets the branding type of the button. This affects the icon shown in the button.
/// </summary>
public BrandingType Branding
{
get
{
return (BrandingType)this.GetValue(BrandingProperty);
}
set
{
this.SetValue(BrandingProperty, value);
this.SetButtonImage();
}
}
/// <summary>
/// Gets the client id of the application.
/// </summary>
public string ClientId
{
get
{
return this.GetValue(ClientIdProperty) as string;
}
set
{
this.SetValue(ClientIdProperty, value);
}
}
/// <summary>
/// Gets the scopes the application needs user consent for.
/// </summary>
public string Scopes
{
get
{
return this.GetValue(ScopesProperty) as string;
}
set
{
this.SetValue(ScopesProperty, value);
}
}
/// <summary>
/// Gets button text type. This affects the text shown on the button.
/// </summary>
public ButtonTextType TextType
{
get
{
return (ButtonTextType)this.GetValue(ButtonTextTypeProperty);
}
set
{
this.SetValue(ButtonTextTypeProperty, value);
this.SetButtonText();
}
}
/// <summary>
/// Gets custom sign in text.
/// </summary>
public string SignInText
{
get
{
return this.GetValue(SignInTextProperty) as string;
}
set
{
this.SetValue(SignInTextProperty, value);
this.SetButtonText();
}
}
/// <summary>
/// Gets custom sign out text.
/// </summary>
public string SignOutText
{
get
{
return this.GetValue(SignOutTextProperty) as string;
}
set
{
this.SetValue(SignOutTextProperty, value);
this.SetButtonText();
}
}
/// <summary>
/// Gets whether or not the we're in design mode.
/// </summary>
private bool IsDesignMode
{
get
{
return DesignerProperties.IsInDesignTool;
}
}
#endregion
#region Methods
private async void Initialize()
{
if (this.authClient == null)
{
this.authClient = new LiveAuthClient(this.ClientId);
if (string.IsNullOrEmpty(this.Scopes))
{
this.Scopes = SignInOfferName;
}
IEnumerable<string> scopes = SignInButton.ParseScopeString(this.Scopes);
try
{
Task<LiveLoginResult> result = this.authClient.InitializeAsync(scopes);
LiveLoginResult r = await result;
this.OnLogin(r);
}
catch (Exception exception)
{
this.RaiseSessionChangedEvent(new LiveConnectSessionChangedEventArgs(exception));
}
this.IsEnabled = true;
}
}
private void LoadControlTemplate()
{
this.InitializeComponent();
}
private async void OnClick(object sender, RoutedEventArgs e)
{
if (this.authClient == null)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentUICulture,
ResourceHelper.GetErrorString("ControlNotInitialized"),
string.Empty,
"Initialize"));
}
if (this.currentState == ButtonState.LogIn)
{
// if there is a pending login request perform a no-op
if (this.hasPendingLoginRequest)
{
return;
}
this.hasPendingLoginRequest = true;
try
{
LiveLoginResult result = await this.authClient.LoginAsync(SignInButton.ParseScopeString(this.Scopes));
this.OnLogin(result);
}
catch (Exception exception)
{
this.RaiseSessionChangedEvent(new LiveConnectSessionChangedEventArgs(exception));
}
finally
{
this.hasPendingLoginRequest = false;
}
}
else
{
this.authClient.Logout();
this.Session = null;
this.SetButtonState(ButtonState.LogIn);
this.RaiseSessionChangedEvent(
new LiveConnectSessionChangedEventArgs(LiveConnectSessionStatus.Unknown, this.Session));
}
}
private void OnControlLoaded(object sender, RoutedEventArgs args)
{
this.Initialize();
}
private void OnLogin(LiveLoginResult loginResult)
{
this.Session = loginResult.Session;
var sessionChangedArgs =
new LiveConnectSessionChangedEventArgs(loginResult.Status, loginResult.Session);
this.RaiseSessionChangedEvent(sessionChangedArgs);
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
this.SetButtonState(ButtonState.LogOut);
}
}
private void SetButtonImage()
{
string iconText;
switch (this.Branding)
{
case BrandingType.Outlook:
iconText = OutlookIcon;
break;
case BrandingType.MicrosoftAccount:
iconText = MicrosoftAccountIcon;
break;
case BrandingType.Messenger:
iconText = MessengerIcon;
break;
default:
iconText = SkyDriveIcon;
break;
}
this.SetValue(IconTextProperty, iconText);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using AllReady.Areas.Admin.Controllers;
using AllReady.Areas.Admin.Features.Requests;
using AllReady.Areas.Admin.ViewModels.Import;
using AllReady.Features.Requests;
using AllReady.UnitTest.Extensions;
using CsvHelper;
using CsvHelper.Configuration;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
using System.Linq;
using AllReady.Areas.Admin.Features.Import;
using Microsoft.Extensions.Logging.Internal;
using System.Threading.Tasks;
using AllReady.Features.Sms;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class ImportControllerTests
{
[Fact]
public void IndexGetReturnsCorrectViewAndViewModel()
{
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.Send(It.IsAny<IndexQuery>())).Returns(new IndexViewModel());
var sut = new ImportController(mediator.Object, null, null);
sut.MakeUserASiteAdmin();
var result = sut.Index() as ViewResult;
Assert.IsType<IndexViewModel>(result.Model);
Assert.Null(result.ViewName);
}
[Fact]
public void IndexGetSendsIndexQuery_WithCorrectOrganizationIdWhenUserIsAnOrgAdmin()
{
const int organizationId = 99;
var mediator = new Mock<IMediator>();
var sut = new ImportController(mediator.Object, null, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
sut.Index();
mediator.Verify(x => x.Send(It.Is<IndexQuery>(y => y.OrganizationId == organizationId)), Times.Once);
}
[Fact]
public void IndexGetSendsIndexQuery_WithCorrectOrganizationIdWhenUserIsNotanOrgAdmin()
{
var mediator = new Mock<IMediator>();
var sut = new ImportController(mediator.Object, null, null);
sut.MakeUserASiteAdmin();
sut.Index();
mediator.Verify(x => x.Send(It.Is<IndexQuery>(y => y.OrganizationId == null)), Times.Once);
}
[Fact]
public async Task IndexPostReturnsTheCorrectViewModelAndView()
{
var sut = new ImportController(null, null, null);
var result = await sut.Index(new IndexViewModel()) as ViewResult;
Assert.IsType<IndexViewModel>(result.Model);
Assert.Null(result.ViewName);
}
[Fact]
public async Task IndexPostReturnsCorrectImportError_WhenEventIsNotPicked()
{
var sut = new ImportController(null, null, null);
var result = (IndexViewModel)((ViewResult) await sut.Index(new IndexViewModel())).Model;
Assert.Contains("please select an Event.", result.ImportErrors);
}
[Fact]
public async Task IndexPostReturnsCorrectImportError_WhenNoFileIsUploaded()
{
var sut = new ImportController(null, null, null);
var result = (IndexViewModel)((ViewResult) await sut.Index(new IndexViewModel())).Model;
Assert.Contains("please select a file to upload.", result.ImportErrors);
}
[Fact]
public async Task IndexPostReturnsCorrectImportError_WhenUploadedFileIsEmpty()
{
Mock<IFormFile> iFormFile;
Mock<ICsvFactory> csvFactory;
Mock<ICsvReader> csvReader;
CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out iFormFile, out csvFactory, out csvReader);
csvReader.Setup(x => x.GetRecords<ImportRequestViewModel>()).Returns(new List<ImportRequestViewModel>());
var sut = new ImportController(null, null, csvFactory.Object);
var result = (IndexViewModel)((ViewResult) await sut.Index(new IndexViewModel { EventId = 1, File = iFormFile.Object })).Model;
Assert.Contains("you uploaded an empty file.", result.ImportErrors);
}
[Fact]
public async Task IndexPostSendsDuplicateProviderRequestIdsQueryWithCorrectProviderRequestIds()
{
const string id = "id";
var importRequestViewModels = new List<ImportRequestViewModel> { new ImportRequestViewModel { Id = id } };
Mock<IFormFile> iFormFile;
Mock<ICsvFactory> csvFactory;
Mock<ICsvReader> csvReader;
CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out iFormFile, out csvFactory, out csvReader);
csvReader.Setup(x => x.GetRecords<ImportRequestViewModel>()).Returns(importRequestViewModels);
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.Send(It.IsAny<DuplicateProviderRequestIdsQuery>())).Returns(new List<string>());
mediator.Setup(x => x.SendAsync(It.IsAny<ValidatePhoneNumberRequestCommand>())).ReturnsAsync(new ValidatePhoneNumberResult { IsValid = true, PhoneNumberE164 = importRequestViewModels[0].Phone });
var sut = new ImportController(mediator.Object, null, csvFactory.Object);
await sut.Index(new IndexViewModel { EventId = 1, File = iFormFile.Object });
mediator.Verify(x => x.Send(It.Is<DuplicateProviderRequestIdsQuery>(y => y.ProviderRequestIds[0] == id)), Times.Once);
}
[Fact]
public async Task IndexPostReturnsCorrectImportError_WhenThereAreDuplicateProviderRequestIdsFound()
{
const string duplicateId = "id";
var duplicateIds = new List<string> { duplicateId };
var importRequestViewModels = new List<ImportRequestViewModel> { new ImportRequestViewModel { Id = duplicateId } };
Mock<IFormFile> iFormFile;
Mock<ICsvFactory> csvFactory;
Mock<ICsvReader> csvReader;
CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out iFormFile, out csvFactory, out csvReader);
csvReader.Setup(x => x.GetRecords<ImportRequestViewModel>()).Returns(importRequestViewModels);
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.Send(It.IsAny<DuplicateProviderRequestIdsQuery>())).Returns(duplicateIds);
var sut = new ImportController(mediator.Object, null, csvFactory.Object);
var result = (IndexViewModel)((ViewResult) await sut.Index(new IndexViewModel { EventId = 1, File = iFormFile.Object })).Model;
Assert.Contains($"These id's already exist in the system. Please remove them from the CSV and try again: {string.Join(", ", duplicateIds)}", result.ImportErrors);
}
[Fact]
public async Task IndexPostSendsValidatePhoneNumberRequestComamndWithCorrectData()
{
const string id = "id";
var importRequestViewModels = new List<ImportRequestViewModel> { new ImportRequestViewModel { Id = id } };
Mock<IFormFile> iFormFile;
Mock<ICsvFactory> csvFactory;
Mock<ICsvReader> csvReader;
CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out iFormFile, out csvFactory, out csvReader);
csvReader.Setup(x => x.GetRecords<ImportRequestViewModel>()).Returns(importRequestViewModels);
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.Send(It.IsAny<DuplicateProviderRequestIdsQuery>())).Returns(new List<string>());
mediator.Setup(x => x.SendAsync(It.IsAny<ValidatePhoneNumberRequestCommand>())).ReturnsAsync(new ValidatePhoneNumberResult { IsValid = true, PhoneNumberE164 = importRequestViewModels[0].Phone });
var sut = new ImportController(mediator.Object, null, csvFactory.Object);
await sut.Index(new IndexViewModel { EventId = 1, File = iFormFile.Object });
mediator.Verify(x => x.SendAsync(It.Is<ValidatePhoneNumberRequestCommand>(y => y.PhoneNumber == importRequestViewModels[0].Phone && y.ValidateType)));
}
[Fact]
public async Task IndexPostReturnsCorrectImportError_WhenPhoneNumbersAreInvalid()
{
var importRequestViewModels = new List<ImportRequestViewModel>
{
new ImportRequestViewModel { Id = "Id", Phone = "InvalidPhoneNumber" }
};
Mock<IFormFile> iFormFile;
Mock<ICsvFactory> csvFactory;
Mock<ICsvReader> csvReader;
CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out iFormFile, out csvFactory, out csvReader);
csvReader.Setup(x => x.GetRecords<ImportRequestViewModel>()).Returns(importRequestViewModels);
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.Send(It.IsAny<DuplicateProviderRequestIdsQuery>())).Returns(new List<string>());
mediator.Setup(x => x.SendAsync(It.IsAny<ValidatePhoneNumberRequestCommand>())).ReturnsAsync(new ValidatePhoneNumberResult { IsValid = false, PhoneNumberE164 = null });
var sut = new ImportController(mediator.Object, null, csvFactory.Object);
var viewResult = await sut.Index(new IndexViewModel { EventId = 1, File = iFormFile.Object }) as ViewResult;
var result = viewResult.Model as IndexViewModel;
Assert.Equal(result.ImportErrors[0], $"These phone numbers are not valid mobile numbers: {importRequestViewModels[0].Phone}");
}
[Fact]
public async Task IndexPostReturnsCorrectValidationErrors_WhenThereAreValidationErrors()
{
var importRequestViewModels = new List<ImportRequestViewModel>
{
new ImportRequestViewModel { Id = "Id", Name = null, Address = string.Empty, Email = "InvalidEmail" }
};
Mock<IFormFile> iFormFile;
Mock<ICsvFactory> csvFactory;
Mock<ICsvReader> csvReader;
CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out iFormFile, out csvFactory, out csvReader);
csvReader.Setup(x => x.GetRecords<ImportRequestViewModel>()).Returns(importRequestViewModels);
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.Send(It.IsAny<DuplicateProviderRequestIdsQuery>())).Returns(new List<string>());
mediator.Setup(x => x.SendAsync(It.IsAny<ValidatePhoneNumberRequestCommand>())).ReturnsAsync(new ValidatePhoneNumberResult { IsValid = true, PhoneNumberE164 = importRequestViewModels[0].Phone });
var sut = new ImportController(mediator.Object, null, csvFactory.Object);
var viewResult = await sut.Index(new IndexViewModel { EventId = 1, File = iFormFile.Object }) as ViewResult;
var result = viewResult.Model as IndexViewModel;
Assert.Equal(result.ValidationErrors[0].ProviderRequestId, importRequestViewModels[0].Id);
Assert.Equal("The Name field is required.", result.ValidationErrors[0].Errors[0].ErrorMessage);
Assert.Equal("The Address field is required.", result.ValidationErrors[0].Errors[1].ErrorMessage);
Assert.Equal("The City field is required.", result.ValidationErrors[0].Errors[2].ErrorMessage);
Assert.Equal("The State field is required.", result.ValidationErrors[0].Errors[3].ErrorMessage);
Assert.Equal("The PostalCode field is required.", result.ValidationErrors[0].Errors[4].ErrorMessage);
Assert.Equal("The Phone field is required.", result.ValidationErrors[0].Errors[5].ErrorMessage);
Assert.Equal("Invalid Email Address", result.ValidationErrors[0].Errors[6].ErrorMessage);
}
[Fact]
public async Task IndexPostSendsImportRequestsCommandWithTheCorrectViewModel()
{
var importRequestViewModels = new List<ImportRequestViewModel>
{
new ImportRequestViewModel { Id = "Id", Name = "Name", Address = "Address", City = "City", Email = "email@email.com", Phone = "111-111-1111", State = "State", PostalCode = "PostalCode" }
};
Mock<IFormFile> iFormFile;
Mock<ICsvFactory> csvFactory;
Mock<ICsvReader> csvReader;
CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out iFormFile, out csvFactory, out csvReader);
iFormFile.Setup(x => x.Name).Returns(It.IsAny<string>());
csvReader.Setup(x => x.GetRecords<ImportRequestViewModel>()).Returns(importRequestViewModels);
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.Send(It.IsAny<DuplicateProviderRequestIdsQuery>())).Returns(new List<string>());
mediator.Setup(x => x.SendAsync(It.IsAny<ValidatePhoneNumberRequestCommand>())).ReturnsAsync(new ValidatePhoneNumberResult { IsValid = true, PhoneNumberE164 = importRequestViewModels[0].Phone });
var sut = new ImportController(mediator.Object, Mock.Of<ILogger<ImportController>>(), csvFactory.Object);
sut.SetFakeUserName("UserName");
await sut.Index(new IndexViewModel { EventId = 1, File = iFormFile.Object });
mediator.Verify(x => x.SendAsync(It.Is<ImportRequestsCommand>(y =>
y.ImportRequestViewModels[0].Id == importRequestViewModels[0].Id &&
y.ImportRequestViewModels[0].Name == importRequestViewModels[0].Name &&
y.ImportRequestViewModels[0].Address == importRequestViewModels[0].Address &&
y.ImportRequestViewModels[0].City == importRequestViewModels[0].City &&
y.ImportRequestViewModels[0].Email == importRequestViewModels[0].Email &&
y.ImportRequestViewModels[0].Phone == importRequestViewModels[0].Phone &&
y.ImportRequestViewModels[0].State == importRequestViewModels[0].State &&
y.ImportRequestViewModels[0].PostalCode == importRequestViewModels[0].PostalCode &&
y.ImportRequestViewModels[0].Longitude == 0 &&
y.ImportRequestViewModels[0].Latitude == 0 &&
y.ImportRequestViewModels[0].ProviderData == null)), Times.Once);
}
[Fact]
public async Task IndexPostLogsCorrectMessage_WhenImportSucceeds()
{
const string userName = "UserName";
const string fileName = "FileName";
var importRequestViewModels = new List<ImportRequestViewModel>
{
new ImportRequestViewModel { Id = "Id", Name = "Name", Address = "Address", City = "City", Email = "email@email.com", Phone = "111-111-1111", State = "State", PostalCode = "PostalCode" }
};
Mock<IFormFile> iFormFile;
Mock<ICsvFactory> csvFactory;
Mock<ICsvReader> csvReader;
CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out iFormFile, out csvFactory, out csvReader);
iFormFile.Setup(x => x.Name).Returns(fileName);
csvReader.Setup(x => x.GetRecords<ImportRequestViewModel>()).Returns(importRequestViewModels);
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<ImportController>>();
mediator.Setup(x => x.Send(It.IsAny<DuplicateProviderRequestIdsQuery>())).Returns(new List<string>());
mediator.Setup(x => x.SendAsync(It.IsAny<ValidatePhoneNumberRequestCommand>())).ReturnsAsync(new ValidatePhoneNumberResult { IsValid = true, PhoneNumberE164 = importRequestViewModels[0].Phone });
var sut = new ImportController(mediator.Object, logger.Object, csvFactory.Object);
sut.SetFakeUserName(userName);
await sut.Index(new IndexViewModel { EventId = 1, File = iFormFile.Object });
logger.Verify(m => m.Log(LogLevel.Information, It.IsAny<EventId>(),
It.Is<FormattedLogValues>(v => v.ToString() == $"{userName} imported file {fileName}"),
null, It.IsAny<Func<object, Exception, string>>()), Times.Once);
}
[Fact]
public async Task IndexPostAssignsImportSuccessToTrue_WhenImportSucceeds()
{
var importRequestViewModels = new List<ImportRequestViewModel>
{
new ImportRequestViewModel { Id = "Id", Name = "Name", Address = "Address", City = "City", Email = "email@email.com", Phone = "111-111-1111", State = "State", PostalCode = "PostalCode" }
};
Mock<IFormFile> iFormFile;
Mock<ICsvFactory> csvFactory;
Mock<ICsvReader> csvReader;
CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out iFormFile, out csvFactory, out csvReader);
iFormFile.Setup(x => x.Name).Returns(It.IsAny<string>());
csvReader.Setup(x => x.GetRecords<ImportRequestViewModel>()).Returns(importRequestViewModels);
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.Send(It.IsAny<DuplicateProviderRequestIdsQuery>())).Returns(new List<string>());
mediator.Setup(x => x.SendAsync(It.IsAny<ValidatePhoneNumberRequestCommand>())).ReturnsAsync(new ValidatePhoneNumberResult { IsValid = true, PhoneNumberE164 = importRequestViewModels[0].Phone });
var sut = new ImportController(mediator.Object, Mock.Of<ILogger<ImportController>>(), csvFactory.Object);
sut.SetFakeUserName("UserName");
var result = (IndexViewModel)((ViewResult)await sut.Index(new IndexViewModel { EventId = 1, File = iFormFile.Object })).Model;
Assert.True(result.ImportSuccess);
}
[Fact]
public void IndexPostHasHttpPostAttribute()
{
var sut = new ImportController(null, null, null);
var attribute = sut.GetAttributesOn(x => x.Index(It.IsAny<IndexViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void IndexPostHasValidateAntiForgeryTokenAttribute()
{
var sut = new ImportController(null, null, null);
var attribute = sut.GetAttributesOn(x => x.Index(It.IsAny<IndexViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
private static void CreateMockAndSetupIFormFileCsvFactoryAndCsvReader(out Mock<IFormFile> iFormFile, out Mock<ICsvFactory> csvFactory, out Mock<ICsvReader> csvReader)
{
iFormFile = new Mock<IFormFile>();
csvFactory = new Mock<ICsvFactory>();
csvReader = new Mock<ICsvReader>();
iFormFile.Setup(x => x.OpenReadStream()).Returns(new MemoryStream());
csvFactory.Setup(x => x.CreateReader(It.IsAny<TextReader>())).Returns(csvReader.Object);
csvReader.Setup(x => x.Configuration).Returns(new CsvConfiguration());
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Reflection;
using System.Resources;
namespace System.Management.Automation
{
/// <summary>
/// </summary>
internal static class ResourceManagerCache
{
/// <summary>
/// Maintains a cache of ResourceManager objects. This is a dictionary that is keyed based on the path
/// to the default resource assembly. The value is another dictionary that is keyed based on the base
/// name for the resource that is being retrieved. The value for this dictionary is the ResourceManager.
/// </summary>
private static readonly Dictionary<string, Dictionary<string, ResourceManager>> s_resourceManagerCache =
new Dictionary<string, Dictionary<string, ResourceManager>>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Used to synchronize access to the ResourceManagerCache.
/// </summary>
private static readonly object s_syncRoot = new object();
/// <summary>
/// Gets the ResourceManager from the cache or gets an instance of the ResourceManager
/// and returns it if it isn't already present in the cache.
/// </summary>
/// <param name="assembly">
/// The assembly to be used as the base for resource lookup.
/// </param>
/// <param name="baseName">
/// The base name of the resources to get the ResourceManager for.
/// </param>
/// <returns>
/// A ResourceManager instance for the assembly and base name that were specified.
/// </returns>
internal static ResourceManager GetResourceManager(
Assembly assembly,
string baseName)
{
if (assembly == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(assembly));
}
if (string.IsNullOrEmpty(baseName))
{
throw PSTraceSource.NewArgumentException(nameof(baseName));
}
// Check to see if the manager is already in the cache
ResourceManager manager = null;
Dictionary<string, ResourceManager> baseNameCache;
string assemblyManifestFileLocation = assembly.Location;
lock (s_syncRoot)
{
// First do the lookup based on the assembly location
if (s_resourceManagerCache.TryGetValue(assemblyManifestFileLocation, out baseNameCache) && baseNameCache != null)
{
// Now do the lookup based on the resource base name
baseNameCache.TryGetValue(baseName, out manager);
}
}
// If it's not in the cache, create it an add it.
if (manager == null)
{
manager = InitRMWithAssembly(baseName, assembly);
// Add the new resource manager to the hash
if (baseNameCache != null)
{
lock (s_syncRoot)
{
// Since the assembly is already cached, we just have
// to cache the base name entry
baseNameCache[baseName] = manager;
}
}
else
{
// Since the assembly wasn't cached, we have to create base name
// cache entry and then add it into the cache keyed by the assembly
// location
var baseNameCacheEntry = new Dictionary<string, ResourceManager>();
baseNameCacheEntry[baseName] = manager;
lock (s_syncRoot)
{
s_resourceManagerCache[assemblyManifestFileLocation] = baseNameCacheEntry;
}
}
}
Diagnostics.Assert(
manager != null,
"If the manager was not already created, it should have been dynamically created or an exception should have been thrown");
return manager;
}
/// <summary>
/// Design For Testability -- assert on failed resource lookup.
/// </summary>
private static bool s_DFT_monitorFailingResourceLookup = true;
internal static bool DFT_DoMonitorFailingResourceLookup
{
get { return ResourceManagerCache.s_DFT_monitorFailingResourceLookup; }
set { ResourceManagerCache.s_DFT_monitorFailingResourceLookup = value; }
}
/// <summary>
/// Gets the string from the resource manager based on the assembly,
/// base name, resource ID, and culture specified.
/// </summary>
/// <param name="assembly">
/// The base assembly from which to get the resources from.
/// </param>
/// <param name="baseName">
/// The base name of the resource to retrieve the string from.
/// </param>
/// <param name="resourceId">
/// Resource ID for which the localized string needs to be retrieved
/// </param>
/// <returns>
/// Localized String, or null if the string does not exist
/// </returns>
/// <remarks>
/// The current thread's UI culture is used.
/// </remarks>
/// <throws>
/// ArgumentException if <paramref name="baseName"/> or <paramref name="resourceId"/>
/// are null or empty..
/// InvalidOperationException if the value of the specified resource is not a string
/// MissingManifestResourceException if no usable set of resources have been found, and
/// there are no neutral culture resources.
/// </throws>
internal static string GetResourceString(
Assembly assembly,
string baseName,
string resourceId)
{
if (assembly == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(assembly));
}
if (string.IsNullOrEmpty(baseName))
{
throw PSTraceSource.NewArgumentException(nameof(baseName));
}
if (string.IsNullOrEmpty(resourceId))
{
throw PSTraceSource.NewArgumentException(nameof(resourceId));
}
ResourceManager resourceManager = null;
string text = string.Empty;
// For a non-existing resource defined by {assembly,baseName,resourceId}
// MissingManifestResourceException is thrown only at the time when resource retrieval method
// such as ResourceManager.GetString or ResourceManager.GetObject is called,
// not when you instantiate a ResourceManager object.
try
{
// try with original baseName first
// if it fails then try with alternative resource path format
resourceManager = GetResourceManager(assembly, baseName);
text = resourceManager.GetString(resourceId);
}
catch (MissingManifestResourceException)
{
const string resourcesSubstring = ".resources.";
int resourcesSubstringIndex = baseName.IndexOf(resourcesSubstring);
string newBaseName = string.Empty;
if (resourcesSubstringIndex != -1)
{
newBaseName = baseName.Substring(resourcesSubstringIndex + resourcesSubstring.Length); // e.g. "FileSystemProviderStrings"
}
else
{
newBaseName = string.Concat(assembly.GetName().Name, resourcesSubstring, baseName); // e.g. "System.Management.Automation.resources.FileSystemProviderStrings"
}
resourceManager = GetResourceManager(assembly, newBaseName);
text = resourceManager.GetString(resourceId);
}
if (string.IsNullOrEmpty(text) && s_DFT_monitorFailingResourceLookup)
{
Diagnostics.Assert(false,
"Lookup failure: baseName " + baseName + " resourceId " + resourceId);
}
return text;
}
/// <summary>
/// Creates a Resource manager instance based on the assembly specified.
/// </summary>
/// <param name="baseName">
/// The root name of the resources.
/// For example, the root name for the resource file
/// named "MyResource.en-US.resources" is "MyResource".
/// </param>
/// <param name="assemblyToUse">
/// The main Assembly for the resources
/// </param>
/// <returns>Resource Manager instance.</returns>
/// <exception cref="ArgumentException">
/// Thrown if the resource manager instance could not be created
/// </exception>
private static ResourceManager InitRMWithAssembly(string baseName, Assembly assemblyToUse)
{
ResourceManager rm = null;
if (baseName != null && assemblyToUse != null)
{
rm = new ResourceManager(baseName, assemblyToUse);
}
else
{
// 2004/10/11-JonN Do we need a better error message? I don't think so,
// since this is private.
throw PSTraceSource.NewArgumentException(nameof(assemblyToUse));
}
return rm;
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// 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 Event Store LLP 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
// HOLDER 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.Linq;
using System.Security.Principal;
using EventStore.Core.Bus;
using EventStore.Core.Data;
using EventStore.Core.Helpers;
using EventStore.Core.Services.TimerService;
using EventStore.Projections.Core.Messages;
namespace EventStore.Projections.Core.Services.Processing
{
public class ReaderStrategy : IReaderStrategy
{
private readonly bool _allStreams;
private readonly HashSet<string> _categories;
private readonly HashSet<string> _streams;
private readonly bool _allEvents;
private readonly bool _includeLinks;
private readonly HashSet<string> _events;
private readonly bool _includeStreamDeletedNotification;
private readonly string _catalogStream;
private readonly bool _reorderEvents;
private readonly IPrincipal _runAs;
private readonly int _processingLag;
private readonly EventFilter _eventFilter;
private readonly PositionTagger _positionTagger;
private readonly ITimeProvider _timeProvider;
private readonly int _phase;
public static IReaderStrategy CreateExternallyFedReaderStrategy(
int phase, ITimeProvider timeProvider, IPrincipal runAs, long limitingCommitPosition)
{
var readerStrategy = new ExternallyFedReaderStrategy(phase, runAs, timeProvider, limitingCommitPosition);
return readerStrategy;
}
public static IReaderStrategy Create(int phase, IQuerySources sources, ITimeProvider timeProvider, bool stopOnEof, IPrincipal runAs)
{
if (!sources.AllStreams && !sources.HasCategories() && !sources.HasStreams()
&& string.IsNullOrEmpty(sources.CatalogStream))
throw new InvalidOperationException("None of streams and categories are included");
if (!sources.AllEvents && !sources.HasEvents())
throw new InvalidOperationException("None of events are included");
if (sources.HasStreams() && sources.HasCategories())
throw new InvalidOperationException(
"Streams and categories cannot be included in a filter at the same time");
if (sources.AllStreams && (sources.HasCategories() || sources.HasStreams()))
throw new InvalidOperationException("Both FromAll and specific categories/streams cannot be set");
if (sources.AllEvents && sources.HasEvents())
throw new InvalidOperationException("Both AllEvents and specific event filters cannot be set");
if (sources.ByStreams && sources.HasStreams())
throw new InvalidOperationException("foreachStream projections are not supported on stream based sources");
if ((sources.HasStreams() || sources.AllStreams) && !string.IsNullOrEmpty(sources.CatalogStream))
throw new InvalidOperationException("catalogStream cannot be used with streams or allStreams");
if (!string.IsNullOrEmpty(sources.CatalogStream) && !sources.ByStreams)
throw new InvalidOperationException("catalogStream is only supported in the byStream mode");
if (!string.IsNullOrEmpty(sources.CatalogStream) && !stopOnEof)
throw new InvalidOperationException("catalogStream is not supported in the projections mode");
if (sources.ReorderEventsOption)
{
if (!string.IsNullOrEmpty(sources.CatalogStream))
throw new InvalidOperationException("Event reordering cannot be used with stream catalogs");
if (sources.AllStreams)
throw new InvalidOperationException("Event reordering cannot be used with fromAll()");
if (!(sources.HasStreams() && sources.Streams.Length > 1))
{
throw new InvalidOperationException(
"Event reordering is only available in fromStreams([]) projections");
}
if (sources.ProcessingLagOption < 50)
throw new InvalidOperationException("Event reordering requires processing lag at least of 50ms");
}
if (sources.HandlesDeletedNotifications && !sources.ByStreams)
throw new InvalidOperationException(
"Deleted stream notifications are only supported with foreachStream()");
var readerStrategy = new ReaderStrategy(
phase, sources.AllStreams, sources.Categories, sources.Streams, sources.AllEvents,
sources.IncludeLinksOption, sources.Events, sources.HandlesDeletedNotifications, sources.CatalogStream,
sources.ProcessingLagOption, sources.ReorderEventsOption, runAs, timeProvider);
return readerStrategy;
}
private ReaderStrategy(
int phase, bool allStreams, string[] categories, string[] streams, bool allEvents, bool includeLinks,
string[] events, bool includeStreamDeletedNotification, string catalogStream, int? processingLag, bool reorderEvents, IPrincipal runAs,
ITimeProvider timeProvider)
{
_phase = phase;
_allStreams = allStreams;
_categories = categories != null && categories.Length > 0 ? new HashSet<string>(categories) : null;
_streams = streams != null && streams.Length > 0 ? new HashSet<string>(streams) : null;
_allEvents = allEvents;
_includeLinks = includeLinks;
_events = events != null && events.Length > 0 ? new HashSet<string>(events) : null;
_includeStreamDeletedNotification = includeStreamDeletedNotification;
_catalogStream = catalogStream;
_processingLag = processingLag.GetValueOrDefault();
_reorderEvents = reorderEvents;
_runAs = runAs;
_eventFilter = CreateEventFilter();
_positionTagger = CreatePositionTagger();
_timeProvider = timeProvider;
}
public bool IsReadingOrderRepeatable {
get
{
return !(_streams != null && _streams.Count > 1);
}
}
public EventFilter EventFilter
{
get { return _eventFilter; }
}
public PositionTagger PositionTagger
{
get { return _positionTagger; }
}
public int Phase
{
get { return _phase; }
}
public IReaderSubscription CreateReaderSubscription(
IPublisher publisher, CheckpointTag fromCheckpointTag, Guid subscriptionId,
ReaderSubscriptionOptions readerSubscriptionOptions)
{
if (_reorderEvents)
return new EventReorderingReaderSubscription(
publisher, subscriptionId, fromCheckpointTag, this,
readerSubscriptionOptions.CheckpointUnhandledBytesThreshold,
readerSubscriptionOptions.CheckpointProcessedEventsThreshold, _processingLag,
readerSubscriptionOptions.StopOnEof, readerSubscriptionOptions.StopAfterNEvents);
else
return new ReaderSubscription(
publisher, subscriptionId, fromCheckpointTag, this,
readerSubscriptionOptions.CheckpointUnhandledBytesThreshold,
readerSubscriptionOptions.CheckpointProcessedEventsThreshold, readerSubscriptionOptions.StopOnEof,
readerSubscriptionOptions.StopAfterNEvents);
}
public IEventReader CreatePausedEventReader(
Guid eventReaderId, IPublisher publisher, IODispatcher ioDispatcher, CheckpointTag checkpointTag, bool stopOnEof, int? stopAfterNEvents)
{
if (_allStreams && _events != null && _events.Count >= 1)
{
//IEnumerable<string> streams = GetEventIndexStreams();
return CreatePausedEventIndexEventReader(
eventReaderId, ioDispatcher, publisher, checkpointTag, stopOnEof, stopAfterNEvents, true, _events,
_includeStreamDeletedNotification);
}
if (_allStreams)
{
var eventReader = new TransactionFileEventReader(
ioDispatcher, publisher, eventReaderId, _runAs,
new TFPos(checkpointTag.CommitPosition.Value, checkpointTag.PreparePosition.Value), _timeProvider,
deliverEndOfTFPosition: true, stopOnEof: stopOnEof, resolveLinkTos: false,
stopAfterNEvents: stopAfterNEvents);
return eventReader;
}
if (_streams != null && _streams.Count == 1)
{
var streamName = checkpointTag.Streams.Keys.First();
//TODO: handle if not the same
return CreatePausedStreamEventReader(
eventReaderId, ioDispatcher, publisher, checkpointTag, streamName, stopOnEof, resolveLinkTos: true,
stopAfterNEvents: stopAfterNEvents, produceStreamDeletes: _includeStreamDeletedNotification);
}
if (_categories != null && _categories.Count == 1)
{
var streamName = checkpointTag.Streams.Keys.First();
return CreatePausedStreamEventReader(
eventReaderId, ioDispatcher, publisher, checkpointTag, streamName, stopOnEof, resolveLinkTos: true,
stopAfterNEvents: stopAfterNEvents, produceStreamDeletes: _includeStreamDeletedNotification);
}
if (_streams != null && _streams.Count > 1)
{
return CreatePausedMultiStreamEventReader(
eventReaderId, ioDispatcher, publisher, checkpointTag, stopOnEof, stopAfterNEvents, true, _streams);
}
if (!string.IsNullOrEmpty(_catalogStream))
{
return CreatePausedCatalogReader(
eventReaderId, publisher, ioDispatcher, checkpointTag, stopOnEof, stopAfterNEvents, true,
_catalogStream);
}
throw new NotSupportedException();
}
private EventFilter CreateEventFilter()
{
if (_allStreams && _events != null && _events.Count >= 1)
return new EventByTypeIndexEventFilter(_events);
if (_allStreams)
//NOTE: a projection cannot handle both stream deleted notifications
// and real stream tombstone/stream deleted events as they have the same position
// and thus processing cannot be correctly checkpointed
return new TransactionFileEventFilter(
_allEvents, !_includeStreamDeletedNotification, _events, includeLinks: _includeLinks);
if (_categories != null && _categories.Count == 1)
return new CategoryEventFilter(_categories.First(), _allEvents, _events);
if (_categories != null)
throw new NotSupportedException();
if (_streams != null && _streams.Count == 1)
return new StreamEventFilter(_streams.First(), _allEvents, _events);
if (_streams != null && _streams.Count > 1)
return new MultiStreamEventFilter(_streams, _allEvents, _events);
if (!string.IsNullOrEmpty(_catalogStream))
return new BypassingEventFilter();
throw new NotSupportedException();
}
private PositionTagger CreatePositionTagger()
{
if (_allStreams && _events != null && _events.Count >= 1)
return new EventByTypeIndexPositionTagger(_phase, _events.ToArray(), _includeStreamDeletedNotification);
if (_allStreams && _reorderEvents)
return new PreparePositionTagger(_phase);
if (_allStreams)
return new TransactionFilePositionTagger(_phase);
if (_categories != null && _categories.Count == 1)
//TODO: '-' is a hardcoded separator
return new StreamPositionTagger(_phase, "$ce-" + _categories.First());
if (_categories != null)
throw new NotSupportedException();
if (_streams != null && _streams.Count == 1)
return new StreamPositionTagger(_phase, _streams.First());
if (_streams != null && _streams.Count > 1)
return new MultiStreamPositionTagger(_phase, _streams.ToArray());
if (!string.IsNullOrEmpty(_catalogStream))
return new PreTaggedPositionTagger(
_phase, CheckpointTag.FromByStreamPosition(0, _catalogStream, -1, null, -1, long.MinValue));
//TODO: consider passing projection phase from outside (above)
throw new NotSupportedException();
}
private IEventReader CreatePausedStreamEventReader(
Guid eventReaderId, IODispatcher ioDispatcher, IPublisher publisher, CheckpointTag checkpointTag,
string streamName, bool stopOnEof, int? stopAfterNEvents, bool resolveLinkTos, bool produceStreamDeletes)
{
var lastProcessedSequenceNumber = checkpointTag.Streams.Values.First();
var fromSequenceNumber = lastProcessedSequenceNumber + 1;
var eventReader = new StreamEventReader(
ioDispatcher, publisher, eventReaderId, _runAs, streamName, fromSequenceNumber, _timeProvider,
resolveLinkTos, produceStreamDeletes, stopOnEof, stopAfterNEvents);
return eventReader;
}
private IEventReader CreatePausedEventIndexEventReader(
Guid eventReaderId, IODispatcher ioDispatcher, IPublisher publisher, CheckpointTag checkpointTag,
bool stopOnEof, int? stopAfterNEvents, bool resolveLinkTos, IEnumerable<string> eventTypes,
bool includeStreamDeletedNotification)
{
//NOTE: just optimization - anyway if reading from TF events may reappear
int p;
var nextPositions = eventTypes.ToDictionary(
v => "$et-" + v, v => checkpointTag.Streams.TryGetValue(v, out p) ? p + 1 : 0);
if (includeStreamDeletedNotification)
nextPositions.Add("$et-$deleted", checkpointTag.Streams.TryGetValue("$deleted", out p) ? p + 1 : 0);
return new EventByTypeIndexEventReader(
ioDispatcher, publisher, eventReaderId, _runAs, eventTypes.ToArray(), includeStreamDeletedNotification,
checkpointTag.Position, nextPositions, resolveLinkTos, _timeProvider, stopOnEof, stopAfterNEvents);
}
private IEventReader CreatePausedMultiStreamEventReader(
Guid eventReaderId, IODispatcher ioDispatcher, IPublisher publisher, CheckpointTag checkpointTag,
bool stopOnEof, int? stopAfterNEvents, bool resolveLinkTos, IEnumerable<string> streams)
{
var nextPositions = checkpointTag.Streams.ToDictionary(v => v.Key, v => v.Value + 1);
return new MultiStreamEventReader(
ioDispatcher, publisher, eventReaderId, _runAs, Phase, streams.ToArray(), nextPositions, resolveLinkTos,
_timeProvider, stopOnEof, stopAfterNEvents);
}
private IEventReader CreatePausedCatalogReader(
Guid eventReaderId, IPublisher publisher, IODispatcher ioDispatcher, CheckpointTag checkpointTag,
bool stopOnEof, int? stopAfterNEvents, bool resolveLinkTos, string catalogStream)
{
if (!stopOnEof) throw new ArgumentException("stopOnEof must be true", "stopOnEof");
var startFromCatalogEventNumber = checkpointTag.CatalogPosition + 1; // read catalog from the next position
var startFromDataStreamName = checkpointTag.DataStream;
var startFromDataStreamEventNumber = checkpointTag.DataPosition + 1; //as it was the last read event
var limitingCommitPosition = checkpointTag.CommitPosition;
return new ByStreamCatalogEventReader(
publisher, eventReaderId, _runAs, ioDispatcher, catalogStream, startFromCatalogEventNumber,
startFromDataStreamName, startFromDataStreamEventNumber, limitingCommitPosition, _timeProvider,
resolveLinkTos, stopAfterNEvents);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
class IlReaderBuilder
{
private readonly StringBuilder myReadMethod = new StringBuilder();
private readonly StringBuilder myCountMethod = new StringBuilder();
//private readonly HashSet<string> myCases = new HashSet<string>(StringComparer.Ordinal);
private readonly List<OpCode> myAllOpcodes;
private static readonly bool UnsafeVersion = true;
public IlReaderBuilder()
{
myAllOpcodes = typeof(OpCodes).GetFields()
.Where(x => x.FieldType == typeof(OpCode))
.Select(x => (OpCode)x.GetValue(null))
.ToList();
}
const byte MultiByteOpCodePrefix = 0xFE;
public string BuildReadMethod()
{
var readMethod = myReadMethod;
readMethod.AppendLine("switch (reader.ReadByte()) {");
// single-byte instructions
foreach (var code in myAllOpcodes)
{
if (IsTwoByteOpcode(code)) continue;
if (code.Value == MultiByteOpCodePrefix) continue;
readMethod.AppendFormat("case 0x{0:X2}: // {1}", code.Value, code.Name).AppendLine();
ReadOperand(code, readMethod);
readMethod.AppendLine(" continue;");
}
readMethod.AppendFormat("case 0x{0:X2}:", MultiByteOpCodePrefix).AppendLine();
readMethod.AppendLine(" switch (reader.ReadByte()) {");
// two-byte instructions
foreach (var code in myAllOpcodes)
{
if (!IsTwoByteOpcode(code)) continue;
var value = code.Value & byte.MaxValue;
readMethod.AppendFormat(" case 0x{0:X2}: // {1}", value, code.Name).AppendLine();
readMethod.Append(" ");
ReadOperand(code, readMethod);
readMethod.AppendLine(" continue;");
}
// note: already checked in counting pass
//readMethod.AppendLine(" default:");
//readMethod.AppendLine(" UnexpectedOpcode();");
//readMethod.AppendLine(" continue;");
//readMethod.AppendLine(" }");
//
//readMethod.AppendLine("default:");
//readMethod.AppendLine(" UnexpectedOpcode();");
//readMethod.AppendLine(" continue;");
//readMethod.AppendLine("}");
readMethod.AppendLine(" default:");
readMethod.AppendLine(" continue;");
readMethod.AppendLine(" }");
readMethod.AppendLine("default:");
readMethod.AppendLine(" continue;");
readMethod.AppendLine("}");
//var cases = string.Join(", ", myCases.OrderBy(x => x).Select((x, i) => string.Format("{0} = {1}", x, i)));
//myReadMethod.AppendFormat("enum Opcode {{ {0} }}", cases);
return readMethod.ToString();
}
private static bool IsTwoByteOpcode(OpCode code)
{
var upperByte = code.Value >> 8;
return (upperByte & MultiByteOpCodePrefix) != 0;
}
public string BuildCountMethod()
{
var countMethod = myCountMethod;
countMethod.AppendLine("switch (reader.ReadByte()) {");
CountOpcodes(myAllOpcodes.Where(code => !IsTwoByteOpcode(code)));
countMethod.AppendFormat("case 0x{0:X2}:", MultiByteOpCodePrefix).AppendLine();
{
countMethod.AppendLine(" switch (reader.ReadByte()) {");
CountOpcodes(myAllOpcodes.Where(IsTwoByteOpcode));
countMethod.AppendLine(" default:");
countMethod.AppendLine(" UnexpectedOpcode();");
countMethod.AppendLine(" continue;");
countMethod.AppendLine(" }");
}
countMethod.AppendLine("default:");
countMethod.AppendLine(" UnexpectedOpcode();");
countMethod.AppendLine(" continue;");
countMethod.AppendLine("}");
countMethod.AppendLine("}");
return countMethod.ToString();
}
private void CountOpcodes(IEnumerable<OpCode> allOpcodes)
{
foreach (var groupByOperandType in allOpcodes.GroupBy(x => SkipOperandCode(x.OperandType)).OrderByDescending(x => string.IsNullOrEmpty(x.Key)))
{
foreach (var code in groupByOperandType.OrderBy(x => x.Value))
{
var value = code.Value;
if (value == MultiByteOpCodePrefix) continue;
if (IsTwoByteOpcode(code)) value = (short) (value & byte.MaxValue);
myCountMethod.AppendFormat("case 0x{0:X2}: // {1}", value, code.Name).AppendLine();
}
myCountMethod.Append(" ");
myCountMethod.Append(groupByOperandType.Key);
myCountMethod.AppendLine();
myCountMethod.AppendLine(" continue;");
}
}
private static string SkipOperandCode(OperandType operandType)
{
switch (operandType)
{
case OperandType.InlineField:
case OperandType.InlineI:
case OperandType.InlineMethod:
case OperandType.InlineSig:
case OperandType.InlineString:
case OperandType.InlineTok:
case OperandType.InlineType:
case OperandType.ShortInlineR:
{
return "reader.ReadInt32();";
}
case OperandType.InlineSwitch:
{
return "for (var cases = reader.ReadUInt32(); cases > 0; cases--) reader.ReadInt32();";
}
case OperandType.InlineI8:
case OperandType.InlineR:
{
return "reader.ReadInt64();";
}
case OperandType.InlineVar:
{
return "reader.ReadInt16();";
}
case OperandType.ShortInlineVar:
case OperandType.ShortInlineI:
{
return "reader.ReadByte();";
}
// todo: add decoding?
case OperandType.InlineBrTarget:
{
return "reader.ReadInt32();";
}
case OperandType.ShortInlineBrTarget:
{
return "reader.ReadSByte();";
}
case OperandType.InlineNone:
{
return string.Empty;
}
default:
throw new ArgumentOutOfRangeException();
}
}
private static void ReadOperand(OpCode code, StringBuilder builder)
{
var name = code.Name;
var value = GetValue(code, ref name);
var caseName = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(name).Replace(".", "");
//myCases.Add(caseName);
if (UnsafeVersion)
{
builder.AppendFormat(" instructions[index].myCode = Opcode.{0};", caseName).AppendLine();
}
else
{
builder.AppendFormat(" instructions.Add(new Instruction(offset");
builder.AppendFormat(", Opcode.{0}", caseName);
}
if (value != null)
{
if (UnsafeVersion)
builder.AppendFormat(" instructions[index].myIntOperand = {0};", value.Value).AppendLine();
else
builder.Append(", ").Append(value.Value);
Debug.Assert(code.OperandType == OperandType.InlineNone);
}
else
{
switch (code.OperandType)
{
case OperandType.InlineField:
case OperandType.InlineI:
case OperandType.InlineMethod:
case OperandType.InlineSig:
case OperandType.InlineString:
case OperandType.InlineTok:
case OperandType.InlineType:
case OperandType.ShortInlineR:
{
if (UnsafeVersion)
builder.AppendLine(" instructions[index].myIntOperand = reader.ReadInt32();");
else
builder.Append(", reader.ReadInt32()");
break;
}
case OperandType.InlineBrTarget:
{
if (UnsafeVersion)
builder.AppendLine(" instructions[index].myIntOperand = reader.ReadInt32() + reader.Offset;");
else
builder.Append(", reader.ReadInt32() + reader.Offset");
break;
}
case OperandType.InlineSwitch:
{
if (UnsafeVersion)
builder.AppendLine(" instructions[index].myOperand = ReadSwitch(ref reader);");
else
builder.Append(", ReadSwitch(ref reader)");
break;
}
case OperandType.InlineI8:
case OperandType.InlineR:
{
if (UnsafeVersion)
builder.AppendLine(" instructions[index].myOperand = reader.ReadInt64();");
else
builder.Append(", reader.ReadInt64()");
break;
}
case OperandType.InlineVar:
{
if (UnsafeVersion)
builder.AppendLine(" instructions[index].myIntOperand = reader.ReadInt16();");
else
builder.Append(", reader.ReadInt16()");
break;
}
case OperandType.ShortInlineVar:
case OperandType.ShortInlineI:
{
if (UnsafeVersion)
builder.AppendLine(" instructions[index].myIntOperand = reader.ReadByte();");
else
builder.Append(", reader.ReadByte()");
break;
}
case OperandType.ShortInlineBrTarget:
{
if (UnsafeVersion)
builder.AppendLine(" instructions[index].myIntOperand = reader.ReadSByte() + reader.Offset;");
else
builder.Append(", reader.ReadSByte() + reader.Offset");
break;
}
}
}
if (!UnsafeVersion) builder.Append("));").AppendLine();
}
private static int? GetValue(OpCode code, ref string name)
{
if (code == OpCodes.Ldc_I4) return null;
if (code == OpCodes.Ldc_I8) return null;
if (code == OpCodes.Ldc_R4) return null;
if (code == OpCodes.Ldc_R8) return null;
var match = Regex.Match(name, @"^(.+)\.(m1|\d|s|[iu][1248]|r[48]|i|u|r)(\.un)?$");
if (!match.Success) return null;
var groups = match.Groups;
name = groups[1].Value + groups[3].Value;
switch (groups[2].Value)
{
case "m1": return -1;
case "0": return 0;
case "1": return 1;
case "2": return 2;
case "3": return 3;
case "4": return 4;
case "5": return 5;
case "6": return 6;
case "7": return 7;
case "8": return 8;
case "i": return 0;
case "i1": return 1;
case "i2": return 2;
case "i4": return 3;
case "i8": return 4;
case "u1": return 5;
case "u2": return 6;
case "u4": return 7;
case "u8": return 8;
case "r4": return 9;
case "r8": return 10;
case "u": return 11;
case "r": return 9;
}
return 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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
#if NET46
internal static readonly Version HttpVersion20 = new Version(2, 0);
internal static readonly Version HttpVersionUnknown = new Version(0, 0);
#else
internal static Version HttpVersion20 => HttpVersion.Version20;
internal static Version HttpVersionUnknown => HttpVersion.Unknown;
#endif
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available.
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = null;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = 64 * 1024;
private int _maxResponseDrainSize = 64 * 1024;
private IDictionary<String, Object> _properties; // Only create dictionary when required.
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(HttpHandlerLoggingStrings.DiagnosticListenerName);
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true);
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
CheckDisposedOrStarted();
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
public IDictionary<string, object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<String, object>();
}
return _properties;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request);
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => ((WinHttpRequestState)s).Handler.StartRequest(s),
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
s_diagnosticListener.LogHttpResponse(tcs.Task, loggingRequestId);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (cookies != null)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO (#5523): Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
SafeWinHttpHandle sessionHandle;
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: proxy accessType={0}", accessType);
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: error={0}", lastError);
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(sessionHandle);
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)Marshal.SizeOf<uint>()))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
SetSessionHandleOptions(sessionHandle);
_sessionHandle = sessionHandle;
}
}
}
}
private async void StartRequest(object obj)
{
WinHttpRequestState state = (WinHttpRequestState)obj;
bool secureConnection = false;
HttpResponseMessage responseMessage = null;
Exception savedException = null;
SafeWinHttpHandle connectHandle = null;
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
state.ClearSendRequestState();
return;
}
try
{
EnsureSessionHandleExists(state);
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.Host,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle);
connectHandle.SetParentHandle(_sessionHandle);
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
secureConnection = true;
}
else
{
secureConnection = false;
}
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersion.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersion.Version11)
{
httpVersion = "HTTP/1.1";
}
// Turn off additional URI reserved character escaping (percent-encoding). This matches
// .NET Framework behavior. System.Uri establishes the baseline rules for percent-encoding
// of reserved characters.
uint flags = Interop.WinHttp.WINHTTP_FLAG_ESCAPE_DISABLE;
if (secureConnection)
{
flags |= Interop.WinHttp.WINHTTP_FLAG_SECURE;
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
flags);
ThrowOnInvalidHandle(state.RequestHandle);
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state).ConfigureAwait(false);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state).ConfigureAwait(false);
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = (uint)_receiveDataTimeout.TotalMilliseconds;
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck);
}
catch (Exception ex)
{
if (state.SavedException != null)
{
savedException = state.SavedException;
}
else
{
savedException = ex;
}
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
// Move the main task to a terminal state. This releases any callers of SendAsync() that are awaiting.
if (responseMessage != null)
{
state.Tcs.TrySetResult(responseMessage);
}
else
{
HandleAsyncException(state, savedException);
}
state.ClearSendRequestState();
}
}
private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle)
{
SetSessionHandleConnectionOptions(sessionHandle);
SetSessionHandleTlsOptions(sessionHandle);
SetSessionHandleTimeoutOptions(sessionHandle);
}
private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = 0;
SslProtocols sslProtocols =
(_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols;
if ((sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle)
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
sessionHandle,
0,
0,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{
if (state.Proxy != null)
{
Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy);
updateProxySettings = true;
if (state.Proxy.IsBypassed(uri))
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
Uri proxyUri = state.Proxy.GetProxy(uri);
string proxyString = proxyUri.Scheme + "://" + proxyUri.Authority;
proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString);
}
}
else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed)
{
if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo))
{
updateProxySettings = true;
}
}
if (updateProxySettings)
{
GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned);
try
{
SetWinHttpOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_PROXY,
pinnedHandle.AddrOfPinnedObject(),
(uint)Marshal.SizeOf(proxyInfo));
}
finally
{
pinnedHandle.Free();
}
}
}
finally
{
Marshal.FreeHGlobal(proxyInfo.Proxy);
Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
}
}
}
private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticDecompression != DecompressionMethods.None)
{
if ((_automaticDecompression & DecompressionMethods.GZip) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP;
}
if ((_automaticDecompression & DecompressionMethods.Deflate) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
}
try
{
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData);
}
catch (WinHttpException ex)
{
if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw;
}
// We are running on a platform earlier than Win8.1 for which WINHTTP.DLL
// doesn't support this option. So, we'll have to do the decompression
// manually.
_doManualDecompressionCheck = true;
}
}
}
private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticRedirection)
{
optionData = (uint)_maxAutomaticRedirections;
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
ref optionData);
}
optionData = _automaticRedirection ?
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP :
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData);
}
private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle)
{
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ||
_cookieUsePolicy == CookieUsePolicy.IgnoreCookies)
{
uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle)
{
// If we have a custom server certificate validation callback method then
// we need to have WinHTTP ignore some errors so that the callback method
// will have a chance to be called.
uint optionData;
if (_serverCertificateValidationCallback != null)
{
optionData =
Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData);
}
else if (_checkCertificateRevocationList)
{
// If no custom validation method, then we let WinHTTP do the revocation check itself.
optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
{
if (requestUri.Scheme != UriScheme.Https)
{
return;
}
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
clientCertificate.Handle,
(uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
}
else
{
SetNoClientCertificate(requestHandle);
}
}
internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
IntPtr.Zero,
0);
}
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// By default, WinHTTP sets the default credentials policy such that it automatically sends default credentials
// (current user's logged on Windows credentials) to a proxy when needed (407 response). It only sends
// default credentials to a server (401 response) if the server is considered to be on the Intranet.
// WinHttpHandler uses a more granual opt-in model for using default credentials that can be different between
// proxy and server credentials. It will explicitly allow default credentials to be sent at a later stage in
// the request processing (after getting a 401/407 response) when the proxy or server credential is set as
// CredentialCache.DefaultNetworkCredential. For now, we set the policy to prevent any default credentials
// from being automatically sent until we get a 401/407 response.
_authHelper.ChangeDefaultCredentialsPolicy(
state.RequestHandle,
Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER,
allowDefaultCredentials:false);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = (uint)_maxResponseHeadersLength;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData);
optionData = (uint)_maxResponseDrainSize;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData);
}
private void SetRequestHandleHttp2Options(SafeWinHttpHandle requestHandle, Version requestVersion)
{
Debug.Assert(requestHandle != null);
if (requestVersion == HttpVersion20)
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: setting HTTP/2 option");
uint optionData = Interop.WinHttp.WINHTTP_PROTOCOL_FLAG_HTTP2;
if (Interop.WinHttp.WinHttpSetOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL,
ref optionData))
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option supported");
}
else
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option not supported");
}
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
(uint)optionData.Length))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void SetWinHttpOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionSize)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
optionSize))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void HandleAsyncException(WinHttpRequestState state, Exception ex)
{
if (state.CancellationToken.IsCancellationRequested)
{
// If the exception was due to the cancellation token being canceled, throw cancellation exception.
state.Tcs.TrySetCanceled(state.CancellationToken);
}
else if (ex is WinHttpException || ex is IOException)
{
// Wrap expected exceptions as HttpRequestExceptions since this is considered an error during
// execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions
// are 'unexpected' or caused by user error and should not be wrapped.
state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex));
}
else
{
state.Tcs.TrySetException(ex);
}
}
private void SetOperationStarted()
{
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void SetStatusCallback(
SafeWinHttpHandle requestHandle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback)
{
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST;
IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback(
requestHandle,
callback,
notificationFlags,
IntPtr.Zero);
if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed.
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
private void ThrowOnInvalidHandle(SafeWinHttpHandle handle)
{
if (handle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.ThrowOnInvalidHandle: error={0}", lastError);
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
private Task<bool> InternalSendRequestAsync(WinHttpRequestState state)
{
state.TcsSendRequest = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
state.Pin();
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
// Dispose (which will unpin) the state object. Since this failed, WinHTTP won't associate
// our context value (state object) to the request handle. And thus we won't get HANDLE_CLOSING
// notifications which would normally cause the state object to be unpinned and disposed.
state.Dispose();
WinHttpException.ThrowExceptionUsingLastError();
}
}
return state.TcsSendRequest.Task;
}
private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend)
{
using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend))
{
await state.RequestMessage.Content.CopyToAsync(
requestStream,
state.TransportContext).ConfigureAwait(false);
await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false);
}
}
private Task<bool> InternalReceiveResponseHeadersAsync(WinHttpRequestState state)
{
state.TcsReceiveResponseHeaders =
new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero))
{
throw WinHttpException.CreateExceptionUsingLastError();
}
}
return state.TcsReceiveResponseHeaders.Task;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class DisposedSocket
{
private readonly static byte[] s_buffer = new byte[1];
private readonly static IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) };
private readonly static SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs();
private static Socket GetDisposedSocket(AddressFamily addressFamily = AddressFamily.InterNetwork)
{
using (var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp))
{
return socket;
}
}
private static void TheAsyncCallback(IAsyncResult ar)
{
}
[Fact]
public void Available_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Available);
}
[Fact]
public void LocalEndPoint_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().LocalEndPoint);
}
[Fact]
public void RemoteEndPoint_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().RemoteEndPoint);
}
[Fact]
public void SetBlocking_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().Blocking = true;
});
}
[Fact]
public void ExclusiveAddressUse_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ExclusiveAddressUse);
}
[Fact]
public void SetExclusiveAddressUse_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().ExclusiveAddressUse = true;
});
}
[Fact]
public void ReceiveBufferSize_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveBufferSize);
}
[Fact]
public void SetReceiveBufferSize_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().ReceiveBufferSize = 1;
});
}
[Fact]
public void SendBufferSize_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendBufferSize);
}
[Fact]
public void SetSendBufferSize_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().SendBufferSize = 1;
});
}
[Fact]
public void ReceiveTimeout_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveTimeout);
}
[Fact]
public void SetReceiveTimeout_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().ReceiveTimeout = 1;
});
}
[Fact]
public void SendTimeout_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTimeout);
}
[Fact]
public void SetSendTimeout_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().SendTimeout = 1;
});
}
[Fact]
public void LingerState_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().LingerState);
}
[Fact]
public void SetLingerState_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().LingerState = new LingerOption(true, 1);
});
}
[Fact]
public void NoDelay_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().NoDelay);
}
[Fact]
public void SetNoDelay_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().NoDelay = true;
});
}
[Fact]
public void Ttl_IPv4_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetwork).Ttl);
}
[Fact]
public void SetTtl_IPv4_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket(AddressFamily.InterNetwork).Ttl = 1;
});
}
[Fact]
public void Ttl_IPv6_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).Ttl);
}
[Fact]
public void SetTtl_IPv6_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket(AddressFamily.InterNetworkV6).Ttl = 1;
});
}
[Fact]
public void DontFragment_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().DontFragment);
}
[Fact]
public void SetDontFragment_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().DontFragment = true;
});
}
[Fact]
public void MulticastLoopback_IPv4_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetwork).MulticastLoopback);
}
[Fact]
public void SetMulticastLoopback_IPv4_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket(AddressFamily.InterNetwork).MulticastLoopback = true;
});
}
[Fact]
public void MulticastLoopback_IPv6_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).MulticastLoopback);
}
[Fact]
public void SetMulticastLoopback_IPv6_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket(AddressFamily.InterNetworkV6).MulticastLoopback = true;
});
}
[Fact]
public void EnableBroadcast_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().EnableBroadcast);
}
[Fact]
public void SetEnableBroadcast_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket().EnableBroadcast = true;
});
}
[Fact]
public void DualMode_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).DualMode);
}
[Fact]
public void SetDualMode_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() =>
{
GetDisposedSocket(AddressFamily.InterNetworkV6).DualMode = true;
});
}
[Fact]
public void Bind_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Bind(new IPEndPoint(IPAddress.Loopback, 0)));
}
[Fact]
public void Connect_IPEndPoint_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect(new IPEndPoint(IPAddress.Loopback, 1)));
}
[Fact]
public void Connect_IPAddress_Port_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect(IPAddress.Loopback, 1));
}
[Fact]
public void Connect_Host_Port_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect("localhost", 1));
}
[Fact]
public void Connect_IPAddresses_Port_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Connect(new[] { IPAddress.Loopback }, 1));
}
[Fact]
public void Disconnect_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Disconnect(false));
}
[Fact]
public void Listen_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Listen(1));
}
[Fact]
public void Accept_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Accept());
}
[Fact]
public void Send_Buffer_Size_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, s_buffer.Length, SocketFlags.None));
}
[Fact]
public void Send_Buffer_SocketFlags_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, SocketFlags.None));
}
[Fact]
public void Send_Buffer_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer));
}
[Fact]
public void Send_Buffer_Offset_Size_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, 0, s_buffer.Length, SocketFlags.None));
}
[Fact]
public void Send_Buffer_Offset_Size_SocketError_Throws_ObjectDisposed()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffer, 0, s_buffer.Length, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffers_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffers));
}
[Fact]
public void Send_Buffers_SocketFlags_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffers, SocketFlags.None));
}
[Fact]
public void Send_Buffers_SocketFlags_SocketError_Throws_ObjectDisposed()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Send(s_buffers, SocketFlags.None, out errorCode));
}
[Fact]
public void SendTo_Buffer_Offset_Size_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, 0, s_buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)));
}
[Fact]
public void SendTo_Buffer_Size_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, s_buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)));
}
[Fact]
public void SendTo_Buffer_SocketFlags_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)));
}
[Fact]
public void SendTo_Buffer_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendTo(s_buffer, new IPEndPoint(IPAddress.Loopback, 1)));
}
[Fact]
public void Receive_Buffer_Size_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, s_buffer.Length, SocketFlags.None));
}
[Fact]
public void Receive_Buffer_SocketFlags_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, SocketFlags.None));
}
[Fact]
public void Receive_Buffer_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer));
}
[Fact]
public void Receive_Buffer_Offset_Size_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, 0, s_buffer.Length, SocketFlags.None));
}
[Fact]
public void Receive_Buffer_Offset_Size_SocketError_Throws_ObjectDisposed()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffer, 0, s_buffer.Length, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffers_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffers));
}
[Fact]
public void Receive_Buffers_SocketFlags_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffers, SocketFlags.None));
}
[Fact]
public void Receive_Buffers_SocketFlags_SocketError_Throws_ObjectDisposed()
{
SocketError errorCode;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Receive(s_buffers, SocketFlags.None, out errorCode));
}
[Fact]
public void ReceiveMessageFrom_Throws_ObjectDisposed()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveFrom_Buffer_Offset_Size_Throws_ObjectDisposed()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length, SocketFlags.None, ref remote));
}
[Fact]
public void ReceiveFrom_Buffer_Size_Throws_ObjectDisposed()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, s_buffer.Length, SocketFlags.None, ref remote));
}
[Fact]
public void ReceiveFrom_Buffer_SocketFlags_Throws_ObjectDisposed()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, SocketFlags.None, ref remote));
}
[Fact]
public void ReceiveFrom_Buffer_Throws_ObjectDisposed()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFrom(s_buffer, ref remote));
}
[Fact]
public void Shutdown_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Shutdown(SocketShutdown.Both));
}
[Fact]
public void IOControl_Int_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().IOControl(0, s_buffer, s_buffer));
}
[Fact]
public void IOControl_IOControlCode_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().IOControl(IOControlCode.Flush, s_buffer, s_buffer));
}
[Fact]
public void SetIPProtectionLevel_IPv4_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetwork).SetIPProtectionLevel(IPProtectionLevel.Unrestricted));
}
[Fact]
public void SetIPProtectionLevel_IPv6_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket(AddressFamily.InterNetworkV6).SetIPProtectionLevel(IPProtectionLevel.Unrestricted));
}
[Fact]
public void SetSocketOption_Int_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, 0));
}
[Fact]
public void SetSocketOption_Buffer_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, s_buffer));
}
[Fact]
public void SetSocketOption_Bool_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, true));
}
[Fact]
public void SetSocketOption_Object_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 1)));
}
[Fact]
public void GetSocketOption_Int_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, 4));
}
[Fact]
public void GetSocketOption_Buffer_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, s_buffer));
}
[Fact]
public void GetSocketOption_Object_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger));
}
[Fact]
public void Poll_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().Poll(-1, SelectMode.SelectWrite));
}
[Fact]
public void AcceptAsync_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().AcceptAsync(s_eventArgs));
}
[Fact]
public void ConnectAsync_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ConnectAsync(s_eventArgs));
}
[Fact]
public void DisconnectAsync_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().DisconnectAsync(s_eventArgs));
}
[Fact]
public void ReceiveAsync_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveAsync(s_eventArgs));
}
[Fact]
public void ReceiveFromAsync_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveFromAsync(s_eventArgs));
}
[Fact]
public void ReceiveMessageFromAsync_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().ReceiveMessageFromAsync(s_eventArgs));
}
[Fact]
public void SendAsync_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendAsync(s_eventArgs));
}
[Fact]
public void SendPacketsAsync_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendPacketsAsync(s_eventArgs));
}
[Fact]
public void SendToAsync_Throws_ObjectDisposed()
{
Assert.Throws<ObjectDisposedException>(() => GetDisposedSocket().SendToAsync(s_eventArgs));
}
}
}
| |
using UnityEngine;
using System;
namespace UnityStandardAssets.CinematicEffects
{
//Improvement ideas:
// In hdr do local tonemapping/inverse tonemapping to stabilize bokeh.
// Use rgba8 buffer in ldr / in some pass in hdr (in correlation to previous point and remapping coc from -1/0/1 to 0/0.5/1)
// Use temporal stabilisation.
// Add a mode to do bokeh texture in quarter res as well
// Support different near and far blur for the bokeh texture
// Try distance field for the bokeh texture.
// Try to separate the output of the blur pass to two rendertarget near+far, see the gain in quality vs loss in performance.
// Try swirl effect on the samples of the circle blur.
//References :
// This DOF implementation use ideas from public sources, a big thank to them :
// http://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare
// http://www.crytek.com/download/Sousa_Graphics_Gems_CryENGINE3.pdf
// http://graphics.cs.williams.edu/papers/MedianShaderX6/
// http://http.developer.nvidia.com/GPUGems/gpugems_ch24.html
// http://vec3.ca/bicubic-filtering-in-fewer-taps/
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Other/DepthOfField")]
[RequireComponent(typeof(Camera))]
public class DepthOfField : MonoBehaviour
{
[AttributeUsage(AttributeTargets.Field)]
public sealed class GradientRangeAttribute : PropertyAttribute
{
public readonly float max;
public readonly float min;
// Attribute used to make a float or int variable in a script be restricted to a specific range.
public GradientRangeAttribute(float min, float max)
{
this.min = min;
this.max = max;
}
}
const float kMaxBlur = 35.0f;
private enum Passes
{
BlurAlphaWeighted = 0 ,
BoxBlur = 1 ,
DilateFgCocFromColor = 2 ,
DilateFgCoc = 3 ,
CaptureCoc = 4 ,
CaptureCocExplicit = 5 ,
VisualizeCoc = 6 ,
VisualizeCocExplicit = 7 ,
CocPrefilter = 8 ,
CircleBlur = 9 ,
CircleBlurWithDilatedFg = 10,
CircleBlurLowQuality = 11,
CircleBlowLowQualityWithDilatedFg = 12,
Merge = 13,
MergeExplicit = 14,
MergeBicubic = 15,
MergeExplicitBicubic = 16,
ShapeLowQuality = 17,
ShapeLowQualityDilateFg = 18,
ShapeLowQualityMerge = 19,
ShapeLowQualityMergeDilateFg = 20,
ShapeMediumQuality = 21,
ShapeMediumQualityDilateFg = 22,
ShapeMediumQualityMerge = 23,
ShapeMediumQualityMergeDilateFg = 24,
ShapeHighQuality = 25,
ShapeHighQualityDilateFg = 26,
ShapeHighQualityMerge = 27,
ShapeHighQualityMergeDilateFg = 28
}
public enum MedianPasses
{
Median3 = 0,
Median3X3 = 1
}
public enum BokehTexturesPasses
{
Apply = 0,
Collect = 1
}
public enum UIMode
{
Basic,
Advanced,
Explicit
}
public enum ApertureShape
{
Circular,
Hexagonal,
Octogonal
}
public enum FilterQuality
{
None,
Normal,
High
}
[Tooltip("Allow to view where the blur will be applied. Yellow for near blur, Blue for far blur.")]
public bool visualizeBluriness = false;
[Tooltip("When enabled quality settings can be hand picked, rather than being driven by the quality slider.")]
public bool customizeQualitySettings = false;
public bool prefilterBlur = true;
public FilterQuality medianFilter = FilterQuality.High;
public bool dilateNearBlur = true;
public bool highQualityUpsampling = true;
[GradientRange(0.0f, 100.0f)]
[Tooltip("Color represent relative performance. From green (faster) to yellow (slower).")]
public float quality = 100.0f;
[Range(0.0f, 1.0f)]
public float focusPlane = 0.225f;
[Range(0.0f, 1.0f)]
public float focusRange = 0.9f;
[Range(0.0f, 1.0f)]
public float nearPlane = 0.0f;
[Range(0.0f, kMaxBlur)]
public float nearRadius = 20.0f;
[Range(0.0f, 1.0f)]
public float farPlane = 1.0f;
[Range(0.0f, kMaxBlur)]
public float farRadius = 20.0f;
[Range(0.0f, kMaxBlur)]
public float radius = 20.0f;
[Range(0.5f, 4.0f)]
public float boostPoint = 0.75f;
[Range(0.0f, 1.0f)]
public float nearBoostAmount = 0.0f;
[Range(0.0f, 1.0f)]
public float farBoostAmount = 0.0f;
[Range(0.0f, 32.0f)]
public float fStops = 5.0f;
[Range(0.01f, 5.0f)]
public float textureBokehScale = 1.0f;
[Range(0.01f, 100.0f)]
public float textureBokehIntensity = 50.0f;
[Range(0.01f, 50.0f)]
public float textureBokehThreshold = 2.0f;
[Range(0.01f, 1.0f)]
public float textureBokehSpawnHeuristic = 0.15f;
public Transform focusTransform = null;
public Texture2D bokehTexture = null;
public ApertureShape apertureShape = ApertureShape.Circular;
[Range(0.0f, 179.0f)]
public float apertureOrientation = 0.0f;
[Tooltip("Use with care Bokeh texture are only available on shader model 5, and performance scale with the number of bokehs.")]
public bool useBokehTexture;
public UIMode uiMode = UIMode.Basic;
public Shader filmicDepthOfFieldShader;
public Shader medianFilterShader;
public Shader textureBokehShader;
[NonSerialized]
private RenderTexureUtility m_RTU = new RenderTexureUtility();
public Material filmicDepthOfFieldMaterial
{
get
{
if (m_FilmicDepthOfFieldMaterial == null)
m_FilmicDepthOfFieldMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(filmicDepthOfFieldShader);
return m_FilmicDepthOfFieldMaterial;
}
}
public Material medianFilterMaterial
{
get
{
if (m_MedianFilterMaterial == null)
m_MedianFilterMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(medianFilterShader);
return m_MedianFilterMaterial;
}
}
public Material textureBokehMaterial
{
get
{
if (m_TextureBokehMaterial == null)
m_TextureBokehMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(textureBokehShader);
return m_TextureBokehMaterial;
}
}
public ComputeBuffer computeBufferDrawArgs
{
get
{
if (m_ComputeBufferDrawArgs == null)
{
m_ComputeBufferDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.DrawIndirect);
var args = new int[4];
args[0] = 0;
args[1] = 1;
args[2] = 0;
args[3] = 0;
m_ComputeBufferDrawArgs.SetData(args);
}
return m_ComputeBufferDrawArgs;
}
}
public ComputeBuffer computeBufferPoints
{
get
{
if (m_ComputeBufferPoints == null)
{
m_ComputeBufferPoints = new ComputeBuffer(90000, 12 + 16, ComputeBufferType.Append);
}
return m_ComputeBufferPoints;
}
}
private ComputeBuffer m_ComputeBufferDrawArgs;
private ComputeBuffer m_ComputeBufferPoints;
private Material m_FilmicDepthOfFieldMaterial;
private Material m_MedianFilterMaterial;
private Material m_TextureBokehMaterial;
private float m_LastApertureOrientation;
private Vector4 m_OctogonalBokehDirection1;
private Vector4 m_OctogonalBokehDirection2;
private Vector4 m_OctogonalBokehDirection3;
private Vector4 m_OctogonalBokehDirection4;
private Vector4 m_HexagonalBokehDirection1;
private Vector4 m_HexagonalBokehDirection2;
private Vector4 m_HexagonalBokehDirection3;
protected void OnEnable()
{
if (filmicDepthOfFieldShader == null)
filmicDepthOfFieldShader = Shader.Find("Hidden/DepthOfField/DepthOfField");
if (medianFilterShader == null)
medianFilterShader = Shader.Find("Hidden/DepthOfField/MedianFilter");
if (textureBokehShader == null)
textureBokehShader = Shader.Find("Hidden/DepthOfField/BokehSplatting");
if (!ImageEffectHelper.IsSupported(filmicDepthOfFieldShader, true, true, this)
|| !ImageEffectHelper.IsSupported(medianFilterShader, true, true, this)
)
{
enabled = false;
Debug.LogWarning("The image effect " + ToString() + " has been disabled as it's not supported on the current platform.");
return;
}
if (ImageEffectHelper.supportsDX11)
{
if (!ImageEffectHelper.IsSupported(textureBokehShader, true, true, this))
{
enabled = false;
Debug.LogWarning("The image effect " + ToString() + " has been disabled as it's not supported on the current platform.");
return;
}
}
ComputeBlurDirections(true);
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
protected void OnDisable()
{
ReleaseComputeResources();
if (m_FilmicDepthOfFieldMaterial)
DestroyImmediate(m_FilmicDepthOfFieldMaterial);
if (m_TextureBokehMaterial)
DestroyImmediate(m_TextureBokehMaterial);
if (m_MedianFilterMaterial)
DestroyImmediate(m_MedianFilterMaterial);
m_TextureBokehMaterial = null;
m_FilmicDepthOfFieldMaterial = null;
m_MedianFilterMaterial = null;
m_RTU.ReleaseAllTemporyRenderTexutres();
}
//-------------------------------------------------------------------//
// Main entry point //
//-------------------------------------------------------------------//
public void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (medianFilterMaterial == null || filmicDepthOfFieldMaterial == null)
{
Graphics.Blit(source, destination);
return;
}
if (visualizeBluriness)
{
Vector4 blurrinessParam;
Vector4 blurrinessCoe;
ComputeCocParameters(out blurrinessParam, out blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_BlurParams", blurrinessParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
Graphics.Blit(null, destination, filmicDepthOfFieldMaterial, (uiMode == UIMode.Explicit) ? (int)Passes.VisualizeCocExplicit : (int)Passes.VisualizeCoc);
}
else
{
DoDepthOfField(source, destination);
}
m_RTU.ReleaseAllTemporyRenderTexutres();
}
private void DoDepthOfField(RenderTexture source, RenderTexture destination)
{
float radiusAdjustement = source.height / 720.0f;
float textureBokehScale = radiusAdjustement;
float textureBokehMaxRadius = Mathf.Max(nearRadius, farRadius) * textureBokehScale * 0.75f;
float nearBlurRadius = nearRadius * radiusAdjustement;
float farBlurRadius = farRadius * radiusAdjustement;
float maxBlurRadius = Mathf.Max(nearBlurRadius, farBlurRadius);
switch (apertureShape)
{
case ApertureShape.Hexagonal: maxBlurRadius *= 1.2f; break;
case ApertureShape.Octogonal: maxBlurRadius *= 1.15f; break;
}
if (maxBlurRadius < 0.5f)
{
Graphics.Blit(source, destination);
return;
}
//Quarter resolution
int rtW = source.width / 2;
int rtH = source.height / 2;
Vector4 blurrinessCoe = new Vector4(nearBlurRadius * 0.5f, farBlurRadius * 0.5f, 0.0f, 0.0f);
RenderTexture colorAndCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
RenderTexture colorAndCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
// Downsample to Color + COC buffer and apply boost
Vector4 cocParam;
Vector4 cocCoe;
ComputeCocParameters(out cocParam, out cocCoe);
filmicDepthOfFieldMaterial.SetVector("_BlurParams", cocParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", cocCoe);
filmicDepthOfFieldMaterial.SetVector("_BoostParams", new Vector4(nearBlurRadius * nearBoostAmount * -0.5f, farBlurRadius * farBoostAmount * 0.5f, boostPoint, 0.0f));
Graphics.Blit(source, colorAndCoc2, filmicDepthOfFieldMaterial, (uiMode == UIMode.Explicit) ? (int)Passes.CaptureCocExplicit : (int)Passes.CaptureCoc);
RenderTexture src = colorAndCoc2;
RenderTexture dst = colorAndCoc;
// Collect texture bokeh candidates and replace with a darker pixel
if (shouldPerformBokeh)
{
// Blur a bit so we can do a frequency check
RenderTexture blurred = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
Graphics.Blit(src, blurred, filmicDepthOfFieldMaterial, (int)Passes.BoxBlur);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.5f, 0.0f, 1.5f));
Graphics.Blit(blurred, dst, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(1.5f, 0.0f, 0.0f, 1.5f));
Graphics.Blit(dst, blurred, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
// Collect texture bokeh candidates and replace with a darker pixel
textureBokehMaterial.SetTexture("_BlurredColor", blurred);
textureBokehMaterial.SetFloat("_SpawnHeuristic", textureBokehSpawnHeuristic);
textureBokehMaterial.SetVector("_BokehParams", new Vector4(this.textureBokehScale * textureBokehScale, textureBokehIntensity, textureBokehThreshold, textureBokehMaxRadius));
Graphics.SetRandomWriteTarget(1, computeBufferPoints);
Graphics.Blit(src, dst, textureBokehMaterial, (int)BokehTexturesPasses.Collect);
Graphics.ClearRandomWriteTargets();
SwapRenderTexture(ref src, ref dst);
m_RTU.ReleaseTemporaryRenderTexture(blurred);
}
filmicDepthOfFieldMaterial.SetVector("_BlurParams", cocParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_BoostParams", new Vector4(nearBlurRadius * nearBoostAmount * -0.5f, farBlurRadius * farBoostAmount * 0.5f, boostPoint, 0.0f));
// Dilate near blur factor
RenderTexture blurredFgCoc = null;
if (dilateNearBlur)
{
RenderTexture blurredFgCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
blurredFgCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(0.0f, nearBlurRadius * 0.75f, 0.0f, 0.0f));
Graphics.Blit(src, blurredFgCoc2, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCocFromColor);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(nearBlurRadius * 0.75f, 0.0f, 0.0f, 0.0f));
Graphics.Blit(blurredFgCoc2, blurredFgCoc, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCoc);
m_RTU.ReleaseTemporaryRenderTexture(blurredFgCoc2);
}
// Blur downsampled color to fill the gap between samples
if (prefilterBlur)
{
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, (int)Passes.CocPrefilter);
SwapRenderTexture(ref src, ref dst);
}
// Apply blur : Circle / Hexagonal or Octagonal (blur will create bokeh if bright pixel where not removed by "m_UseBokehTexture")
switch (apertureShape)
{
case ApertureShape.Circular: DoCircularBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius); break;
case ApertureShape.Hexagonal: DoHexagonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius); break;
case ApertureShape.Octogonal: DoOctogonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius); break;
}
// Smooth result
switch (medianFilter)
{
case FilterQuality.Normal:
{
medianFilterMaterial.SetVector("_Offsets", new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
medianFilterMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
break;
}
case FilterQuality.High:
{
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3X3);
SwapRenderTexture(ref src, ref dst);
break;
}
}
// Merge to full resolution (with boost) + upsampling (linear or bicubic)
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_Convolved_TexelSize", new Vector4(src.width, src.height, 1.0f / src.width, 1.0f / src.height));
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", src);
int mergePass = (uiMode == UIMode.Explicit) ? (int)Passes.MergeExplicit : (int)Passes.Merge;
if (highQualityUpsampling)
{
mergePass = (uiMode == UIMode.Explicit) ? (int)Passes.MergeExplicitBicubic : (int)Passes.MergeBicubic;
}
// Apply texture bokeh
if (shouldPerformBokeh)
{
RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(source.height, source.width, 0, source.format);
Graphics.Blit(source, tmp, filmicDepthOfFieldMaterial, mergePass);
Graphics.SetRenderTarget(tmp);
ComputeBuffer.CopyCount(computeBufferPoints, computeBufferDrawArgs, 0);
textureBokehMaterial.SetBuffer("pointBuffer", computeBufferPoints);
textureBokehMaterial.SetTexture("_MainTex", bokehTexture);
textureBokehMaterial.SetVector("_Screen", new Vector3(1.0f / (1.0f * source.width), 1.0f / (1.0f * source.height), textureBokehMaxRadius));
textureBokehMaterial.SetPass((int)BokehTexturesPasses.Apply);
Graphics.DrawProceduralIndirect(MeshTopology.Points, computeBufferDrawArgs, 0);
Graphics.Blit(tmp, destination);// hackaround for DX11 flipfun (OPTIMIZEME)
}
else
{
Graphics.Blit(source, destination, filmicDepthOfFieldMaterial, mergePass);
}
}
//-------------------------------------------------------------------//
// Blurs //
//-------------------------------------------------------------------//
private void DoHexagonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection2);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection3);
filmicDepthOfFieldMaterial.SetTexture("_ThirdTex", src);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
SwapRenderTexture(ref src, ref dst);
}
private void DoOctogonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection2);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection3);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection4);
filmicDepthOfFieldMaterial.SetTexture("_ThirdTex", dst);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
}
private void DoCircularBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
int bokehPass;
if (blurredFgCoc != null)
{
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
bokehPass = (maxRadius > 10.0f) ? (int)Passes.CircleBlurWithDilatedFg : (int)Passes.CircleBlowLowQualityWithDilatedFg;
}
else
{
bokehPass = (maxRadius > 10.0f) ? (int)Passes.CircleBlur : (int)Passes.CircleBlurLowQuality;
}
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, bokehPass);
SwapRenderTexture(ref src, ref dst);
}
//-------------------------------------------------------------------//
// Helpers //
//-------------------------------------------------------------------//
private void ComputeCocParameters(out Vector4 blurParams, out Vector4 blurCoe)
{
Camera sceneCamera = GetComponent<Camera>();
float focusDistance01 = focusTransform ? (sceneCamera.WorldToViewportPoint(focusTransform.position)).z / (sceneCamera.farClipPlane) : (focusPlane * focusPlane * focusPlane * focusPlane);
if (uiMode == UIMode.Basic || uiMode == UIMode.Advanced)
{
float focusRange01 = focusRange * focusRange * focusRange * focusRange;
float focalLength = 4.0f / Mathf.Tan(0.5f * sceneCamera.fieldOfView * Mathf.Deg2Rad);
float aperture = focalLength / fStops;
blurCoe = new Vector4(0.0f, 0.0f, 1.0f, 1.0f);
blurParams = new Vector4(aperture, focalLength, focusDistance01, focusRange01);
}
else
{
float nearDistance01 = nearPlane * nearPlane * nearPlane * nearPlane;
float farDistance01 = farPlane * farPlane * farPlane * farPlane;
float nearFocusRange01 = focusRange * focusRange * focusRange * focusRange;
float farFocusRange01 = nearFocusRange01;
if (focusDistance01 <= nearDistance01)
focusDistance01 = nearDistance01 + 0.0000001f;
if (focusDistance01 >= farDistance01)
focusDistance01 = farDistance01 - 0.0000001f;
if ((focusDistance01 - nearFocusRange01) <= nearDistance01)
nearFocusRange01 = (focusDistance01 - nearDistance01 - 0.0000001f);
if ((focusDistance01 + farFocusRange01) >= farDistance01)
farFocusRange01 = (farDistance01 - focusDistance01 - 0.0000001f);
float a1 = 1.0f / (nearDistance01 - focusDistance01 + nearFocusRange01);
float a2 = 1.0f / (farDistance01 - focusDistance01 - farFocusRange01);
float b1 = (1.0f - a1 * nearDistance01), b2 = (1.0f - a2 * farDistance01);
const float c1 = -1.0f;
const float c2 = 1.0f;
blurParams = new Vector4(c1 * a1, c1 * b1, c2 * a2, c2 * b2);
blurCoe = new Vector4(0.0f, 0.0f, (b2 - b1) / (a1 - a2), 0.0f);
}
}
private void ReleaseComputeResources()
{
if (m_ComputeBufferDrawArgs != null)
m_ComputeBufferDrawArgs.Release();
m_ComputeBufferDrawArgs = null;
if (m_ComputeBufferPoints != null)
m_ComputeBufferPoints.Release();
m_ComputeBufferPoints = null;
}
private void ComputeBlurDirections(bool force)
{
if (!force && Math.Abs(m_LastApertureOrientation - apertureOrientation) < float.Epsilon) return;
m_LastApertureOrientation = apertureOrientation;
float rotationRadian = apertureOrientation * Mathf.Deg2Rad;
float cosinus = Mathf.Cos(rotationRadian);
float sinus = Mathf.Sin(rotationRadian);
m_OctogonalBokehDirection1 = new Vector4(0.5f, 0.0f, 0.0f, 0.0f);
m_OctogonalBokehDirection2 = new Vector4(0.0f, 0.5f, 1.0f, 0.0f);
m_OctogonalBokehDirection3 = new Vector4(-0.353553f, 0.353553f, 1.0f, 0.0f);
m_OctogonalBokehDirection4 = new Vector4(0.353553f, 0.353553f, 1.0f, 0.0f);
m_HexagonalBokehDirection1 = new Vector4(0.5f, 0.0f, 0.0f, 0.0f);
m_HexagonalBokehDirection2 = new Vector4(0.25f, 0.433013f, 1.0f, 0.0f);
m_HexagonalBokehDirection3 = new Vector4(0.25f, -0.433013f, 1.0f, 0.0f);
if (rotationRadian > float.Epsilon)
{
Rotate2D(ref m_OctogonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection3, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection4, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection3, cosinus, sinus);
}
}
private bool shouldPerformBokeh
{
get { return ImageEffectHelper.supportsDX11 && useBokehTexture && textureBokehMaterial; }
}
private static void Rotate2D(ref Vector4 direction, float cosinus, float sinus)
{
Vector4 source = direction;
direction.x = source.x * cosinus - source.y * sinus;
direction.y = source.x * sinus + source.y * cosinus;
}
private static void SwapRenderTexture(ref RenderTexture src, ref RenderTexture dst)
{
RenderTexture tmp = dst;
dst = src;
src = tmp;
}
private static void GetDirectionalBlurPassesFromRadius(RenderTexture blurredFgCoc, float maxRadius, out int blurPass, out int blurAndMergePass)
{
if (blurredFgCoc == null)
{
if (maxRadius > 10.0f)
{
blurPass = (int)Passes.ShapeHighQuality;
blurAndMergePass = (int)Passes.ShapeHighQualityMerge;
}
else if (maxRadius > 5.0f)
{
blurPass = (int)Passes.ShapeMediumQuality;
blurAndMergePass = (int)Passes.ShapeMediumQualityMerge;
}
else
{
blurPass = (int)Passes.ShapeLowQuality;
blurAndMergePass = (int)Passes.ShapeLowQualityMerge;
}
}
else
{
if (maxRadius > 10.0f)
{
blurPass = (int)Passes.ShapeHighQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeHighQualityMergeDilateFg;
}
else if (maxRadius > 5.0f)
{
blurPass = (int)Passes.ShapeMediumQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeMediumQualityMergeDilateFg;
}
else
{
blurPass = (int)Passes.ShapeLowQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeLowQualityMergeDilateFg;
}
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, 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.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace OpenMetaverse.Imaging
{
#if !NO_UNSAFE
/// <summary>
/// A Wrapper around openjpeg to encode and decode images to and from byte arrays
/// </summary>
public class OpenJPEG
{
/// <summary>TGA Header size</summary>
public const int TGA_HEADER_SIZE = 32;
#region JPEG2000 Structs
/// <summary>
/// Defines the beginning and ending file positions of a layer in an
/// LRCP-progression JPEG2000 file
/// </summary>
[System.Diagnostics.DebuggerDisplay("Start = {Start} End = {End} Size = {End - Start}")]
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct J2KLayerInfo
{
public int Start;
public int End;
}
/// <summary>
/// This structure is used to marshal both encoded and decoded images.
/// MUST MATCH THE STRUCT IN dotnet.h!
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct MarshalledImage
{
public IntPtr encoded; // encoded image data
public int length; // encoded image length
public int dummy; // padding for 64-bit alignment
public IntPtr decoded; // decoded image, contiguous components
public int width; // width of decoded image
public int height; // height of decoded image
public int layers; // layer count
public int resolutions; // resolution count
public int components; // component count
public int packet_count; // packet count
public IntPtr packets; // pointer to the packets array
}
/// <summary>
/// Information about a single packet in a JPEG2000 stream
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct MarshalledPacket
{
/// <summary>Packet start position</summary>
public int start_pos;
/// <summary>Packet header end position</summary>
public int end_ph_pos;
/// <summary>Packet end position</summary>
public int end_pos;
public override string ToString()
{
return String.Format("start_pos: {0} end_ph_pos: {1} end_pos: {2}",
start_pos, end_ph_pos, end_pos);
}
}
#endregion JPEG2000 Structs
#region Unmanaged Function Declarations
// allocate encoded buffer based on length field
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetAllocEncoded(ref MarshalledImage image);
// allocate decoded buffer based on width and height fields
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetAllocDecoded(ref MarshalledImage image);
// free buffers
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetFree(ref MarshalledImage image);
// encode raw to jpeg2000
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetEncode(ref MarshalledImage image, bool lossless);
// decode jpeg2000 to raw
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetDecode(ref MarshalledImage image);
// decode jpeg2000 to raw, get jpeg2000 file info
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetDecodeWithInfo(ref MarshalledImage image);
// invoke 64 bit openjpeg calls
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetAllocEncoded64(ref MarshalledImage image);
// allocate decoded buffer based on width and height fields
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetAllocDecoded64(ref MarshalledImage image);
// free buffers
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetFree64(ref MarshalledImage image);
// encode raw to jpeg2000
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetEncode64(ref MarshalledImage image, bool lossless);
// decode jpeg2000 to raw
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetDecode64(ref MarshalledImage image);
// decode jpeg2000 to raw, get jpeg2000 file info
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet-x86_64.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetDecodeWithInfo64(ref MarshalledImage image);
#endregion Unmanaged Function Declarations
/// <summary>OpenJPEG is not threadsafe, so this object is used to lock
/// during calls into unmanaged code</summary>
private static object OpenJPEGLock = new object();
/// <summary>
/// Encode a <seealso cref="ManagedImage"/> object into a byte array
/// </summary>
/// <param name="image">The <seealso cref="ManagedImage"/> object to encode</param>
/// <param name="lossless">true to enable lossless conversion, only useful for small images ie: sculptmaps</param>
/// <returns>A byte array containing the encoded Image object</returns>
public static byte[] Encode(ManagedImage image, bool lossless)
{
if ((image.Channels & ManagedImage.ImageChannels.Color) == 0 ||
((image.Channels & ManagedImage.ImageChannels.Bump) != 0 && (image.Channels & ManagedImage.ImageChannels.Alpha) == 0))
throw new ArgumentException("JPEG2000 encoding is not supported for this channel combination");
byte[] encoded = null;
MarshalledImage marshalled = new MarshalledImage();
// allocate and copy to input buffer
marshalled.width = image.Width;
marshalled.height = image.Height;
marshalled.components = 3;
if ((image.Channels & ManagedImage.ImageChannels.Alpha) != 0) marshalled.components++;
if ((image.Channels & ManagedImage.ImageChannels.Bump) != 0) marshalled.components++;
lock (OpenJPEGLock)
{
bool allocSuccess = (IntPtr.Size == 8) ? DotNetAllocDecoded64(ref marshalled) : DotNetAllocDecoded(ref marshalled);
if (!allocSuccess)
throw new Exception("DotNetAllocDecoded failed");
int n = image.Width * image.Height;
if ((image.Channels & ManagedImage.ImageChannels.Color) != 0)
{
Marshal.Copy(image.Red, 0, marshalled.decoded, n);
Marshal.Copy(image.Green, 0, (IntPtr)(marshalled.decoded.ToInt64() + n), n);
Marshal.Copy(image.Blue, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 2), n);
}
if ((image.Channels & ManagedImage.ImageChannels.Alpha) != 0) Marshal.Copy(image.Alpha, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 3), n);
if ((image.Channels & ManagedImage.ImageChannels.Bump) != 0) Marshal.Copy(image.Bump, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 4), n);
// codec will allocate output buffer
bool encodeSuccess = (IntPtr.Size == 8) ? DotNetEncode64(ref marshalled, lossless) : DotNetEncode(ref marshalled, lossless);
if (!encodeSuccess)
throw new Exception("DotNetEncode failed");
// copy output buffer
encoded = new byte[marshalled.length];
Marshal.Copy(marshalled.encoded, encoded, 0, marshalled.length);
// free buffers
if (IntPtr.Size == 8)
DotNetFree64(ref marshalled);
else
DotNetFree(ref marshalled);
}
return encoded;
}
/// <summary>
/// Encode a <seealso cref="ManagedImage"/> object into a byte array
/// </summary>
/// <param name="image">The <seealso cref="ManagedImage"/> object to encode</param>
/// <returns>a byte array of the encoded image</returns>
public static byte[] Encode(ManagedImage image)
{
return Encode(image, false);
}
/// <summary>
/// Decode JPEG2000 data to an <seealso cref="System.Drawing.Image"/> and
/// <seealso cref="ManagedImage"/>
/// </summary>
/// <param name="encoded">JPEG2000 encoded data</param>
/// <param name="managedImage">ManagedImage object to decode to</param>
/// <param name="image">Image object to decode to</param>
/// <returns>True if the decode succeeds, otherwise false</returns>
public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage, out Image image)
{
managedImage = null;
image = null;
if (DecodeToImage(encoded, out managedImage))
{
try
{
image = managedImage.ExportBitmap();
return true;
}
catch (Exception ex)
{
Logger.Log("Failed to export and load TGA data from decoded image", Helpers.LogLevel.Error, ex);
return false;
}
}
else
{
return false;
}
}
/// <summary>
///
/// </summary>
/// <param name="encoded"></param>
/// <param name="managedImage"></param>
/// <returns></returns>
public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage)
{
MarshalledImage marshalled = new MarshalledImage();
// Allocate and copy to input buffer
marshalled.length = encoded.Length;
lock (OpenJPEGLock)
{
if (IntPtr.Size == 8)
DotNetAllocEncoded64(ref marshalled);
else
DotNetAllocEncoded(ref marshalled);
Marshal.Copy(encoded, 0, marshalled.encoded, encoded.Length);
// Codec will allocate output buffer
if (IntPtr.Size == 8)
DotNetDecode64(ref marshalled);
else
DotNetDecode(ref marshalled);
int n = marshalled.width * marshalled.height;
switch (marshalled.components)
{
case 1: // Grayscale
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Buffer.BlockCopy(managedImage.Red, 0, managedImage.Green, 0, n);
Buffer.BlockCopy(managedImage.Red, 0, managedImage.Blue, 0, n);
break;
case 2: // Grayscale + alpha
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Buffer.BlockCopy(managedImage.Red, 0, managedImage.Green, 0, n);
Buffer.BlockCopy(managedImage.Red, 0, managedImage.Blue, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Alpha, 0, n);
break;
case 3: // RGB
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n);
break;
case 4: // RGBA
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 3)), managedImage.Alpha, 0, n);
break;
case 5: // RGBAB
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha | ManagedImage.ImageChannels.Bump);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 3)), managedImage.Alpha, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 4)), managedImage.Bump, 0, n);
break;
default:
Logger.Log("Decoded image with unhandled number of components: " + marshalled.components,
Helpers.LogLevel.Error);
if (IntPtr.Size == 8)
DotNetFree64(ref marshalled);
else
DotNetFree(ref marshalled);
managedImage = null;
return false;
}
if (IntPtr.Size == 8)
DotNetFree64(ref marshalled);
else
DotNetFree(ref marshalled);
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="encoded"></param>
/// <param name="layerInfo"></param>
/// <param name="components"></param>
/// <returns></returns>
public static bool DecodeLayerBoundaries(byte[] encoded, out J2KLayerInfo[] layerInfo, out int components)
{
bool success = false;
layerInfo = null;
components = 0;
MarshalledImage marshalled = new MarshalledImage();
// Allocate and copy to input buffer
marshalled.length = encoded.Length;
lock (OpenJPEGLock)
{
if (IntPtr.Size == 8)
DotNetAllocEncoded64(ref marshalled);
else
DotNetAllocEncoded(ref marshalled);
Marshal.Copy(encoded, 0, marshalled.encoded, encoded.Length);
// Run the decode
bool decodeSuccess = (IntPtr.Size == 8) ? DotNetDecodeWithInfo64(ref marshalled) : DotNetDecodeWithInfo(ref marshalled);
if (decodeSuccess)
{
components = marshalled.components;
// Sanity check
if (marshalled.layers * marshalled.resolutions * marshalled.components == marshalled.packet_count)
{
// Manually marshal the array of opj_packet_info structs
MarshalledPacket[] packets = new MarshalledPacket[marshalled.packet_count];
int offset = 0;
for (int i = 0; i < marshalled.packet_count; i++)
{
MarshalledPacket packet;
packet.start_pos = Marshal.ReadInt32(marshalled.packets, offset);
offset += 4;
packet.end_ph_pos = Marshal.ReadInt32(marshalled.packets, offset);
offset += 4;
packet.end_pos = Marshal.ReadInt32(marshalled.packets, offset);
offset += 4;
//double distortion = (double)Marshal.ReadInt64(marshalled.packets, offset);
offset += 8;
packets[i] = packet;
}
layerInfo = new J2KLayerInfo[marshalled.layers];
for (int i = 0; i < marshalled.layers; i++)
{
int packetsPerLayer = marshalled.packet_count / marshalled.layers;
MarshalledPacket startPacket = packets[packetsPerLayer * i];
MarshalledPacket endPacket = packets[(packetsPerLayer * (i + 1)) - 1];
layerInfo[i].Start = startPacket.start_pos;
layerInfo[i].End = endPacket.end_pos;
}
// More sanity checking
if (layerInfo.Length == 0 || layerInfo[layerInfo.Length - 1].End <= encoded.Length - 1)
{
success = true;
for (int i = 0; i < layerInfo.Length; i++)
{
if (layerInfo[i].Start >= layerInfo[i].End ||
(i > 0 && layerInfo[i].Start <= layerInfo[i - 1].End))
{
System.Text.StringBuilder output = new System.Text.StringBuilder(
"Inconsistent packet data in JPEG2000 stream:\n");
for (int j = 0; j < layerInfo.Length; j++)
output.AppendFormat("Layer {0}: Start: {1} End: {2}\n", j, layerInfo[j].Start, layerInfo[j].End);
Logger.DebugLog(output.ToString());
success = false;
break;
}
}
if (!success)
{
for (int i = 0; i < layerInfo.Length; i++)
{
if (i < layerInfo.Length - 1)
layerInfo[i].End = layerInfo[i + 1].Start - 1;
else
layerInfo[i].End = marshalled.length;
}
Logger.DebugLog("Corrected JPEG2000 packet data");
success = true;
for (int i = 0; i < layerInfo.Length; i++)
{
if (layerInfo[i].Start >= layerInfo[i].End ||
(i > 0 && layerInfo[i].Start <= layerInfo[i - 1].End))
{
System.Text.StringBuilder output = new System.Text.StringBuilder(
"Still inconsistent packet data in JPEG2000 stream, giving up:\n");
for (int j = 0; j < layerInfo.Length; j++)
output.AppendFormat("Layer {0}: Start: {1} End: {2}\n", j, layerInfo[j].Start, layerInfo[j].End);
Logger.DebugLog(output.ToString());
success = false;
break;
}
}
}
}
else
{
Logger.Log(String.Format(
"Last packet end in JPEG2000 stream extends beyond the end of the file. filesize={0} layerend={1}",
encoded.Length, layerInfo[layerInfo.Length - 1].End), Helpers.LogLevel.Warning);
}
}
else
{
Logger.Log(String.Format(
"Packet count mismatch in JPEG2000 stream. layers={0} resolutions={1} components={2} packets={3}",
marshalled.layers, marshalled.resolutions, marshalled.components, marshalled.packet_count),
Helpers.LogLevel.Warning);
}
}
if (IntPtr.Size == 8)
DotNetFree64(ref marshalled);
else
DotNetFree(ref marshalled);
}
return success;
}
/// <summary>
/// Encode a <seealso cref="System.Drawing.Bitmap"/> object into a byte array
/// </summary>
/// <param name="bitmap">The source <seealso cref="System.Drawing.Bitmap"/> object to encode</param>
/// <param name="lossless">true to enable lossless decoding</param>
/// <returns>A byte array containing the source Bitmap object</returns>
public unsafe static byte[] EncodeFromImage(Bitmap bitmap, bool lossless)
{
BitmapData bd;
ManagedImage decoded;
int bitmapWidth = bitmap.Width;
int bitmapHeight = bitmap.Height;
int pixelCount = bitmapWidth * bitmapHeight;
int i;
if ((bitmap.PixelFormat & PixelFormat.Alpha) != 0 || (bitmap.PixelFormat & PixelFormat.PAlpha) != 0)
{
// Four layers, RGBA
decoded = new ManagedImage(bitmapWidth, bitmapHeight,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha);
bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte* pixel = (byte*)bd.Scan0;
for (i = 0; i < pixelCount; i++)
{
// GDI+ gives us BGRA and we need to turn that in to RGBA
decoded.Blue[i] = *(pixel++);
decoded.Green[i] = *(pixel++);
decoded.Red[i] = *(pixel++);
decoded.Alpha[i] = *(pixel++);
}
}
else if (bitmap.PixelFormat == PixelFormat.Format16bppGrayScale)
{
// One layer
decoded = new ManagedImage(bitmapWidth, bitmapHeight,
ManagedImage.ImageChannels.Color);
bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight),
ImageLockMode.ReadOnly, PixelFormat.Format16bppGrayScale);
byte* pixel = (byte*)bd.Scan0;
for (i = 0; i < pixelCount; i++)
{
// Normalize 16-bit data down to 8-bit
ushort origVal = (byte)(*(pixel) + (*(pixel + 1) << 8));
byte val = (byte)(((double)origVal / (double)UInt32.MaxValue) * (double)Byte.MaxValue);
decoded.Red[i] = val;
decoded.Green[i] = val;
decoded.Blue[i] = val;
pixel += 2;
}
}
else
{
// Three layers, RGB
decoded = new ManagedImage(bitmapWidth, bitmapHeight,
ManagedImage.ImageChannels.Color);
bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight),
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
byte* pixel = (byte*)bd.Scan0;
for (i = 0; i < pixelCount; i++)
{
decoded.Blue[i] = *(pixel++);
decoded.Green[i] = *(pixel++);
decoded.Red[i] = *(pixel++);
}
}
bitmap.UnlockBits(bd);
byte[] encoded = Encode(decoded, lossless);
return encoded;
}
}
#endif
}
| |
namespace Nancy
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
/// <summary>
/// Represents a full Url of the form scheme://hostname:port/basepath/path?query
/// </summary>
/// <remarks>Since this is for internal use, and fragments are not passed to the server, fragments are not supported.</remarks>
public sealed class Url
{
private string basePath;
private string query;
/// <summary>
/// Creates an instance of the <see cref="Url" /> class
/// </summary>
public Url()
{
this.Scheme = "http";
this.HostName = string.Empty;
this.Port = null;
this.BasePath = string.Empty;
this.Path = string.Empty;
this.Query = string.Empty;
}
/// <summary>
/// Creates an instance of the <see cref="Url" /> class
/// </summary>
/// <param name="url">A <see cref="string" /> containing a URL.</param>
public Url(string url)
{
var uri = new Uri(url);
this.HostName = uri.Host;
this.Path = uri.LocalPath;
this.Port = uri.Port;
this.Query = uri.Query;
this.Scheme = uri.Scheme;
}
/// <summary>
/// Gets or sets the HTTP protocol used by the client.
/// </summary>
/// <value>The protocol.</value>
public string Scheme { get; set; }
/// <summary>
/// Gets the hostname of the request
/// </summary>
public string HostName { get; set; }
/// <summary>
/// Gets the port name of the request
/// </summary>
public int? Port { get; set; }
/// <summary>
/// Gets the base path of the request i.e. the "Nancy root"
/// </summary>
public string BasePath
{
get { return this.basePath; }
set { this.basePath = (value ?? string.Empty).TrimEnd('/'); }
}
/// <summary>
/// Gets the path of the request, relative to the base path
/// This property drives the route matching
/// </summary>
public string Path { get; set; }
/// <summary>
/// Gets the querystring data of the requested resource.
/// </summary>
public string Query
{
get { return this.query; }
set { this.query = GetQuery(value); }
}
/// <summary>
/// Gets the domain part of the request
/// </summary>
public string SiteBase
{
get
{
return new StringBuilder()
.Append(this.Scheme)
.Append("://")
.Append(GetHostName(this.HostName))
.Append(GetPort(this.Port))
.ToString();
}
}
/// <summary>
/// Gets whether the url is secure or not.
/// </summary>
public bool IsSecure
{
get
{
return "https".Equals(this.Scheme, StringComparison.OrdinalIgnoreCase);
}
}
public override string ToString()
{
return new StringBuilder()
.Append(this.Scheme)
.Append("://")
.Append(GetHostName(this.HostName))
.Append(GetPort(this.Port))
.Append(GetCorrectPath(this.BasePath))
.Append(GetCorrectPath(this.Path))
.Append(this.Query)
.ToString();
}
/// <summary>
/// Clones the url.
/// </summary>
/// <returns>Returns a new cloned instance of the url.</returns>
public Url Clone()
{
return new Url
{
BasePath = this.BasePath,
HostName = this.HostName,
Port = this.Port,
Query = this.Query,
Path = this.Path,
Scheme = this.Scheme
};
}
/// <summary>
/// Casts the current <see cref="Url"/> instance to a <see cref="string"/> instance.
/// </summary>
/// <param name="url">The instance that should be cast.</param>
/// <returns>A <see cref="string"/> representation of the <paramref name="url"/>.</returns>
public static implicit operator string(Url url)
{
return url.ToString();
}
/// <summary>
/// Casts the current <see cref="string"/> instance to a <see cref="Url"/> instance.
/// </summary>
/// <param name="url">The instance that should be cast.</param>
/// <returns>An <see cref="Url"/> representation of the <paramref name="url"/>.</returns>
public static implicit operator Url(string url)
{
return new Uri(url);
}
/// <summary>
/// Casts the current <see cref="Url"/> instance to a <see cref="Uri"/> instance.
/// </summary>
/// <param name="url">The instance that should be cast.</param>
/// <returns>An <see cref="Uri"/> representation of the <paramref name="url"/>.</returns>
public static implicit operator Uri(Url url)
{
return new Uri(url.ToString(), UriKind.Absolute);
}
/// <summary>
/// Casts a <see cref="Uri"/> instance to a <see cref="Url"/> instance
/// </summary>
/// <param name="uri">The instance that should be cast.</param>
/// <returns>An <see cref="Url"/> representation of the <paramref name="uri"/>.</returns>
public static implicit operator Url(Uri uri)
{
if (uri.IsAbsoluteUri)
{
return new Url
{
HostName = uri.Host,
Path = uri.LocalPath,
Port = uri.Port,
Query = uri.Query,
Scheme = uri.Scheme
};
}
return new Url { Path = uri.OriginalString };
}
private static string GetQuery(string query)
{
return string.IsNullOrEmpty(query) ? string.Empty : (query[0] == '?' ? query : '?' + query);
}
private static string GetCorrectPath(string path)
{
return (string.IsNullOrEmpty(path) || path.Equals("/")) ? string.Empty : path;
}
private static string GetPort(int? port)
{
return port.HasValue ? string.Concat(":", port.Value) : string.Empty;
}
private static string GetHostName(string hostName)
{
IPAddress address;
if (IPAddress.TryParse(hostName, out address))
{
var addressString = address.ToString();
return address.AddressFamily == AddressFamily.InterNetworkV6
? string.Format("[{0}]", addressString)
: addressString;
}
return hostName;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
using Deja.Crypto.BcPgp;
using System.Text.RegularExpressions;
using NLog;
namespace OutlookPrivacyPlugin
{
public class ButtonStateData
{
public bool SignButton = false;
public bool EncryptButton = false;
public bool OnlyAttachmentsButton = false;
public ButtonStateData(bool sign, bool encrypt, bool onlyAttachments)
{
SignButton = sign;
EncryptButton = encrypt;
OnlyAttachmentsButton = onlyAttachments;
}
}
[ComVisible(true)]
public class GnuPGRibbon : Office.IRibbonExtensibility
{
static NLog.Logger logger = LogManager.GetCurrentClassLogger();
private Office.IRibbonUI ribbon;
public GnuPGToggleButton SignButton;
public GnuPGToggleButton EncryptButton;
public GnuPGToggleButton VerifyButton;
public GnuPGToggleButton DecryptButton;
public GnuPGToggleButton AttachPublicKeyButton;
public GnuPGToggleButton OnlyAttachmentsButton;
public Dictionary<string, ButtonStateData> ButtonState = new Dictionary<string, ButtonStateData>();
private Dictionary<string, GnuPGToggleButton> Buttons = new Dictionary<string, GnuPGToggleButton>();
public GnuPGRibbon()
{
SignButton = new GnuPGToggleButton("signButton");
EncryptButton = new GnuPGToggleButton("encryptButton");
VerifyButton = new GnuPGToggleButton("verifyButton");
DecryptButton = new GnuPGToggleButton("decryptButton");
AttachPublicKeyButton = new GnuPGToggleButton("attachPublicKeyButton");
OnlyAttachmentsButton = new GnuPGToggleButton("onlyAttachmentsButton");
Buttons.Add(SignButton.Id, SignButton);
Buttons.Add(EncryptButton.Id, EncryptButton);
Buttons.Add(VerifyButton.Id, VerifyButton);
Buttons.Add(DecryptButton.Id, DecryptButton);
Buttons.Add(AttachPublicKeyButton.Id, AttachPublicKeyButton);
Buttons.Add(OnlyAttachmentsButton.Id, OnlyAttachmentsButton);
}
#region IRibbonExtensibility Members
public string GetCustomUI(string ribbonID)
{
String ui = null;
// Examine the ribbonID to see if the current item
// is a Mail inspector.
if (ribbonID == "Microsoft.Outlook.Mail.Read")
{
// Retrieve the customized Ribbon XML.
ui = GetResourceText("OutlookPrivacyPlugin.GnuPGRibbonRead.xml");
}
if (ribbonID == "Microsoft.Outlook.Mail.Compose")
{
// Retrieve the customized Ribbon XML.
ui = GetResourceText("OutlookPrivacyPlugin.GnuPGRibbonCompose.xml");
}
return ui;
}
#endregion
internal void UpdateButtons(Properties.Settings settings)
{
// Compose Mail
EncryptButton.Checked = settings.AutoEncrypt;
SignButton.Checked = settings.AutoSign;
AttachPublicKeyButton.Checked = false;
OnlyAttachmentsButton.Checked = false;
// Read Mail
DecryptButton.Checked = settings.AutoDecrypt;
VerifyButton.Checked = settings.AutoVerify;
}
internal void InvalidateButtons()
{
if (ribbon == null)
return;
ribbon.InvalidateControl(SignButton.Id);
ribbon.InvalidateControl(EncryptButton.Id);
ribbon.InvalidateControl(VerifyButton.Id);
ribbon.InvalidateControl(DecryptButton.Id);
ribbon.InvalidateControl(AttachPublicKeyButton.Id);
ribbon.InvalidateControl(OnlyAttachmentsButton.Id);
}
#region Ribbon Callbacks
public void OnLoad(Office.IRibbonUI ribbonUI)
{
this.ribbon = ribbonUI;
}
public void OnEncryptButton(Office.IRibbonControl control, bool isPressed)
{
logger.Trace("OnEncryptButton("+control.Id+", "+isPressed+")");
Outlook.MailItem mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (mailItem == null)
logger.Trace("OnEncryptButton: mailItem == null");
if (isPressed == true)
{
if (mailItem != null)
{
var settings = new Properties.Settings();
if (settings.Default2PlainFormat)
{
string body = mailItem.Body;
mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatPlain;
mailItem.Body = body;
}
}
}
OutlookPrivacyPlugin.SetProperty(mailItem, "GnuPGSetting.Encrypt", isPressed);
EncryptButton.Checked = isPressed;
ribbon.InvalidateControl(EncryptButton.Id);
}
public void OnOnlyAttachmentsButton(Office.IRibbonControl control, bool isPressed)
{
logger.Trace("OnOnlyAttachmentsButton(" + control.Id + ", " + isPressed + ")");
Outlook.MailItem mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (mailItem == null)
logger.Trace("OnOnlyAttachmentsButton: mailItem == null");
if (isPressed == true)
{
if (mailItem != null)
{
var settings = new Properties.Settings();
if (settings.Default2PlainFormat)
{
string body = mailItem.Body;
mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatPlain;
mailItem.Body = body;
}
}
}
OutlookPrivacyPlugin.SetProperty(mailItem, "GnuPGSetting.OnlyAttachments", isPressed);
OnlyAttachmentsButton.Checked = isPressed;
ribbon.InvalidateControl(OnlyAttachmentsButton.Id);
}
public void OnDecryptButton(Office.IRibbonControl control)
{
Outlook.MailItem mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (mailItem != null)
Globals.OutlookPrivacyPlugin.DecryptEmail(mailItem);
}
public void OnSignButton(Office.IRibbonControl control, bool isPressed)
{
Outlook.MailItem mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (isPressed == true)
{
if (mailItem != null)
{
var settings = new Properties.Settings();
if (settings.Default2PlainFormat)
{
string body = mailItem.Body;
mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatPlain;
mailItem.Body = body;
}
}
}
OutlookPrivacyPlugin.SetProperty(mailItem, "GnuPGSetting.Sign", isPressed);
SignButton.Checked = isPressed;
ribbon.InvalidateControl(SignButton.Id);
}
public void OnVerifyButton(Office.IRibbonControl control)
{
Outlook.MailItem mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (mailItem != null)
Globals.OutlookPrivacyPlugin.VerifyEmail(mailItem);
}
public void OnAttachPublicKeyButton(Office.IRibbonControl control)
{
Outlook.MailItem mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (mailItem == null)
{
// TODO - Generate a log message
MessageBox.Show("Error, mailItem was null.");
return;
}
var smtp = Globals.OutlookPrivacyPlugin.GetSMTPAddress(mailItem);
var crypto = new Deja.Crypto.BcPgp.PgpCrypto(new Deja.Crypto.BcPgp.CryptoContext());
var headers = new Dictionary<string, string>();
headers["Version"] = "Outlook Privacy Plugin";
var publicKey = crypto.PublicKey(smtp, headers);
if(publicKey == null)
{
// TODO - Generate log message
MessageBox.Show("Error, unable to find public key to attach.");
return;
}
var tempFile = Path.Combine(Path.GetTempPath(), "public_key.asc");
File.WriteAllText(tempFile, publicKey);
try
{
mailItem.Attachments.Add(
tempFile,
Outlook.OlAttachmentType.olByValue,
1,
"public_key.asc");
mailItem.Save();
}
finally
{
File.Delete(tempFile);
}
}
public void OnSettingsButtonRead(Office.IRibbonControl control)
{
Globals.OutlookPrivacyPlugin.Settings();
}
public void OnSettingsButtonNew(Office.IRibbonControl control)
{
Globals.OutlookPrivacyPlugin.Settings();
// Force an update of button state:
ribbon.InvalidateControl(SignButton.Id);
ribbon.InvalidateControl(EncryptButton.Id);
}
public void OnAboutButton(Office.IRibbonControl control)
{
Globals.OutlookPrivacyPlugin.About();
}
public stdole.IPictureDisp
GetCustomImage(Office.IRibbonControl control)
{
stdole.IPictureDisp pictureDisp = null;
switch (control.Id)
{
case "settingsButtonNew":
case "settingsButtonRead":
pictureDisp = ImageConverter.Convert(global::OutlookPrivacyPlugin.Properties.Resources.database_gear);
break;
case "aboutButtonNew":
case "aboutButtonRead":
pictureDisp = ImageConverter.Convert(global::OutlookPrivacyPlugin.Properties.Resources.Logo);
break;
case "attachPublicKeyButton":
pictureDisp = ImageConverter.Convert(global::OutlookPrivacyPlugin.Properties.Resources.attach);
break;
default:
if ((control.Id == EncryptButton.Id) || (control.Id == DecryptButton.Id))
pictureDisp = ImageConverter.Convert(global::OutlookPrivacyPlugin.Properties.Resources.lock_edit);
if ((control.Id == SignButton.Id) || (control.Id == VerifyButton.Id))
pictureDisp = ImageConverter.Convert(global::OutlookPrivacyPlugin.Properties.Resources.link_edit);
break;
}
return pictureDisp;
}
public bool GetPressed(Office.IRibbonControl control)
{
logger.Trace("GetPressed("+control.Id+")");
if (control.Id == SignButton.Id)
{
Outlook.MailItem mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
return (bool)OutlookPrivacyPlugin.GetProperty(mailItem, "GnuPGSetting.Sign", false);
}
else if (control.Id == EncryptButton.Id)
{
Outlook.MailItem mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
return (bool)OutlookPrivacyPlugin.GetProperty(mailItem, "GnuPGSetting.Encrypt", false);
}
else
logger.Trace("GetPressed: Button did not match encrypt or sign!");
if (Buttons.ContainsKey(control.Id))
return Buttons[control.Id].Checked;
return false;
}
public bool GetEnabled(Office.IRibbonControl control)
{
if (Buttons.ContainsKey(control.Id))
return Buttons[control.Id].Enabled;
return false;
}
#endregion
#region Helpers
private static string GetResourceText(string resourceName)
{
Assembly asm = Assembly.GetExecutingAssembly();
string[] resourceNames = asm.GetManifestResourceNames();
for (int i = 0; i < resourceNames.Length; ++i)
{
if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
{
using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
{
if (resourceReader != null)
{
return resourceReader.ReadToEnd();
}
}
}
}
return null;
}
#endregion
}
internal class ImageConverter : System.Windows.Forms.AxHost
{
private ImageConverter()
: base(null)
{
}
public static stdole.IPictureDisp Convert(System.Drawing.Image image)
{
return (stdole.IPictureDisp)AxHost.GetIPictureDispFromPicture(image);
}
}
public class GnuPGToggleButton
{
private bool m_Checked = false;
public bool Checked
{
get { return m_Checked; }
set { m_Checked = value; }
}
private bool m_Enabled = true;
public bool Enabled
{
get { return m_Enabled; }
set { m_Enabled = value; }
}
private string m_ControlId = "unknown";
public string Id
{
get { return m_ControlId; }
set { m_ControlId = value; }
}
public GnuPGToggleButton(string controlId)
{
Id = controlId;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace GetSocialSdk.Core
{
public static class Communities
{
#region Activities
public static void GetAnnouncements(AnnouncementsQuery query, Action<List<Activity>> onSuccess,
Action<GetSocialError> onFailure)
{
GetSocialFactory.Bridge.GetAnnouncements(query, onSuccess, onFailure);
}
public static void GetActivities(PagingQuery<ActivitiesQuery> query, Action<PagingResult<Activity>> onSuccess,
Action<GetSocialError> onFailure)
{
GetSocialFactory.Bridge.GetActivities(query, onSuccess, onFailure);
}
public static void GetActivity(string id, Action<Activity> onSuccess, Action<GetSocialError> onFailure)
{
GetSocialFactory.Bridge.GetActivity(id, onSuccess, onFailure);
}
public static void PostActivity(ActivityContent content, PostActivityTarget target, Action<Activity> onSuccess,
Action<GetSocialError> onFailure)
{
GetSocialFactory.Bridge.PostActivity(content, target, onSuccess, onFailure);
}
public static void UpdateActivity(string id, ActivityContent content, Action<Activity> onSuccess,
Action<GetSocialError> onFailure)
{
GetSocialFactory.Bridge.UpdateActivity(id, content, onSuccess, onFailure);
}
public static void RemoveActivities(RemoveActivitiesQuery query, Action onSuccess,
Action<GetSocialError> onFailure)
{
GetSocialFactory.Bridge.RemoveActivities(query, onSuccess, onFailure);
}
public static void AddReaction(string reaction, string activityId, Action success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.AddReaction(reaction, activityId, success, failure);
}
public static void RemoveReaction(string reaction, string activityId, Action success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.RemoveReaction(reaction, activityId, success, failure);
}
public static void GetReactions(PagingQuery<ReactionsQuery> query, Action<PagingResult<UserReactions>> onSuccess,
Action<GetSocialError> onFailure)
{
GetSocialFactory.Bridge.GetReactions(query, onSuccess, onFailure);
}
public static void GetTags(TagsQuery query, Action<List<string>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetTags(query, success, failure);
}
public static void ReportActivity(string activityId, ReportingReason reason, string explanation, Action onSuccess, Action<GetSocialError> onError)
{
GetSocialFactory.Bridge.ReportActivity(activityId, reason, explanation, onSuccess, onError);
}
#endregion
#region Polls
public static void AddVotes(HashSet<string> pollOptionIds, string activityId, Action onSuccess, Action<GetSocialError> onError)
{
GetSocialFactory.Bridge.AddVotes(pollOptionIds, activityId, onSuccess, onError);
}
public static void SetVotes(HashSet<string> pollOptionIds, string activityId, Action onSuccess, Action<GetSocialError> onError)
{
GetSocialFactory.Bridge.SetVotes(pollOptionIds, activityId, onSuccess, onError);
}
public static void RemoveVotes(HashSet<string> pollOptionIds, string activityId, Action onSuccess, Action<GetSocialError> onError)
{
GetSocialFactory.Bridge.RemoveVotes(pollOptionIds, activityId, onSuccess, onError);
}
public static void GetVotes(PagingQuery<VotesQuery> query, Action<PagingResult<UserVotes>> onSuccess, Action<GetSocialError> onError)
{
GetSocialFactory.Bridge.GetVotes(query, onSuccess, onError);
}
#endregion
#region Users
public static void GetUsers(PagingQuery<UsersQuery> query, Action<PagingResult<User>> onSuccess,
Action<GetSocialError> onFailure)
{
GetSocialFactory.Bridge.GetUsers(query, onSuccess, onFailure);
}
public static void GetUsersCount(UsersQuery query, Action<int> success, Action<GetSocialError> error)
{
GetSocialFactory.Bridge.GetUsersCount(query, success, error);
}
public static void GetUsers(UserIdList list, Action<Dictionary<string, User>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetUsers(list, success, failure);
}
public static void GetUser(UserId userId, Action<User> success, Action<GetSocialError> failure)
{
GetUsers(UserIdList.CreateWithProvider(userId.Provider, userId.Id), result =>
{
if (result.Count == 1)
{
success(result.First().Value);
}
else
{
failure(new GetSocialError(ErrorCodes.IllegalArgument, $"User does not exist: {userId}"));
}
}, failure);
}
#endregion
#region Friends
public static void SetFriends(UserIdList userIds, Action<int> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.SetFriends(userIds, success, failure);
}
public static void AddFriends(UserIdList userIds, Action<int> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.AddFriends(userIds, success, failure);
}
public static void RemoveFriends(UserIdList userIds, Action<int> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.RemoveFriends(userIds, success, failure);
}
public static void GetFriends(PagingQuery<FriendsQuery> query, Action<PagingResult<User>> success,
Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetFriends(query, success, failure);
}
public static void GetFriendsCount(FriendsQuery query, Action<int> success,
Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetFriendsCount(query, success, failure);
}
public static void AreFriends(UserIdList userIds, Action<Dictionary<string, bool>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.AreFriends(userIds, success, failure);
}
public static void IsFriend(UserId userId, Action<bool> success, Action<GetSocialError> failure)
{
AreFriends(UserIdList.CreateWithProvider(userId.Provider, userId.Id), result =>
{
if (result.ContainsKey(userId.Id))
{
success(result[userId.Id]);
}
else
{
failure(new GetSocialError(ErrorCodes.IllegalArgument, $"User does not exist: {userId}"));
}
}, failure);
}
public static void GetSuggestedFriends(SimplePagingQuery query, Action<PagingResult<SuggestedFriend>> success,
Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetSuggestedFriends(query, success, failure);
}
#endregion
#region Topics
public static void GetTopic(string topic, Action<Topic> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetTopic(topic, success, failure);
}
public static void GetTopics(PagingQuery<TopicsQuery> pagingQuery, Action<PagingResult<Topic>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetTopics(pagingQuery, success, failure);
}
public static void GetTopicsCount(TopicsQuery query, Action<int> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetTopicsCount(query, success, failure);
}
#endregion
#region Groups
public static void CreateGroup(GroupContent content, Action<Group> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.CreateGroup(content, success, failure);
}
public static void UpdateGroup(string groupId, GroupContent content, Action<Group> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.UpdateGroup(groupId, content, success, failure);
}
public static void RemoveGroups(List<string> groupIds, Action success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.RemoveGroups(groupIds, success, failure);
}
public static void GetGroupMembers(PagingQuery<MembersQuery> pagingQuery, Action<PagingResult<GroupMember>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetGroupMembers(pagingQuery, success, failure);
}
public static void GetGroups(PagingQuery<GroupsQuery> pagingQuery, Action<PagingResult<Group>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetGroups(pagingQuery, success, failure);
}
public static void GetGroupsCount(GroupsQuery query, Action<int> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetGroupsCount(query, success, failure);
}
public static void GetGroup(string groupId, Action<Group> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetGroup(groupId, success, failure);
}
public static void UpdateGroupMembers(UpdateGroupMembersQuery query, Action<List<GroupMember>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.UpdateGroupMembers(query, success, failure);
}
public static void AddGroupMembers(AddGroupMembersQuery query, Action<List<GroupMember>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.AddGroupMembers(query, success, failure);
}
public static void JoinGroup(JoinGroupQuery query, Action<GroupMember> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.JoinGroup(query, success, failure);
}
public static void RemoveGroupMembers(RemoveGroupMembersQuery query, Action success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.RemoveGroupMembers(query, success, failure);
}
public static void AreGroupMembers(string groupId, UserIdList userIdList, Action<Dictionary<String, Membership>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.AreGroupMembers(groupId, userIdList, success, failure);
}
#endregion
#region Chat
public static void SendChatMessage(ChatMessageContent content, ChatId target, Action<ChatMessage> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.SendChatMessage(content, target, success, failure);
}
public static void GetChatMessages(ChatMessagesPagingQuery pagingQuery, Action<ChatMessagesPagingResult> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetChatMessages(pagingQuery, success, failure);
}
public static void GetChats(SimplePagingQuery pagingQuery, Action<PagingResult<Chat>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetChats(pagingQuery, success, failure);
}
public static void GetChat(ChatId chatId, Action<Chat> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetChat(chatId, success, failure);
}
#endregion
#region Follow/Unfollow
public static void Follow(FollowQuery query, Action<int> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.Follow(query, success, failure);
}
public static void Unfollow(FollowQuery query, Action<int> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.Unfollow(query, success, failure);
}
public static void IsFollowing(UserId userId, FollowQuery query, Action<Dictionary<string, bool>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.IsFollowing(userId, query, success, failure);
}
public static void GetFollowers(PagingQuery<FollowersQuery> query, Action<PagingResult<User>> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetFollowers(query, success, failure);
}
public static void GetFollowersCount(FollowersQuery query, Action<int> success, Action<GetSocialError> failure)
{
GetSocialFactory.Bridge.GetFollowersCount(query, success, failure);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using JetBrains.DataFlow;
using JetBrains.Metadata.Reader.API;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.TaskRunnerFramework;
using JetBrains.ReSharper.TestFramework.Components.UnitTestSupport;
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Util;
using JetBrains.Util.Logging;
namespace XunitContrib.Runner.ReSharper.Tests.AcceptanceTests
{
public abstract partial class UnitTestTaskRunnerTestBase
{
private int GetServerPortNumber()
{
var unitTestServer = Solution.GetComponent<UnitTestServerTestImpl>();
return unitTestServer.PortNumber;
}
private IRemoteChannel GetRemoteChannel()
{
var unitTestServer = Solution.GetComponent<UnitTestServerTestImpl>();
return unitTestServer.RemoteChannel;
}
public abstract IUnitTestElementsSource MetadataExplorer { get; }
protected virtual ICollection<IUnitTestElement> GetUnitTestElements(IProject testProject, string assemblyLocation)
{
var observer = new TestUnitTestElementObserver();
var resolver = new DefaultAssemblyResolver();
resolver.AddPath(FileSystemPath.Parse(assemblyLocation).Directory);
using (var loader = new MetadataLoader(resolver))
{
MetadataExplorer.ExploreProjects(
new Dictionary<IProject, FileSystemPath>
{
{testProject, FileSystemPath.Parse(assemblyLocation)}
},
loader, observer);
}
return observer.Elements;
}
protected virtual ITaskRunnerHostController CreateTaskRunnerHostController(IUnitTestLaunchManager launchManager, IUnitTestResultManager resultManager, IUnitTestAgentManager agentManager, TextWriter output, IUnitTestLaunch launch, int port, TestRemoteChannelMessageListener msgListener)
{
return new ProcessTaskRunnerHostController(Logger.GetLogger(typeof(UnitTestTaskRunnerTestBase)), launchManager, resultManager, agentManager, launch, port, null);
}
// 9.1 RTM SDK has a nasty little bug where each test takes 30 seconds to run
// The issue is that TaskRunnerHostControllerBase.FinishRun calls IUnitTestLaunch.FinishRun,
// but the implementation, in UnitTestSessionTestImpl, does nothing. Instead, it's expecting
// a call to UnitTestSessionTestImpl.Finish, which will run the action we pass to OnFinish
// and signal the event. Because the event doesn't get signalled, we have to wait 30 seconds
// for the timeout. This wrapper class implements IUnitTestLaunch by deferring to
// UnitTestSessionTestImpl, and implementing FinishRun by calling UnitTestSessionTestImpl.Finish
// https://youtrack.jetbrains.com/issue/RSRP-437172
private static IUnitTestLaunch GetUnitTestLaunch(UnitTestSessionTestImpl session)
{
return new FinishRunFixingLaunch(session);
}
private class FinishRunFixingLaunch : IUnitTestLaunch
{
private readonly IUnitTestLaunch session;
public FinishRunFixingLaunch(IUnitTestLaunch session)
{
this.session = session;
}
public void FinishRun(IUnitTestRun run)
{
session.Finish();
}
#region Boring
public void PutData<T>(Key<T> key, T value) where T : class
{
session.PutData(key, value);
}
public T GetData<T>(Key<T> key) where T : class
{
return session.GetData(key);
}
public IEnumerable<KeyValuePair<object, object>> EnumerateData()
{
return session.EnumerateData();
}
public IUnitTestRun GetRun(string id)
{
return session.GetRun(id);
}
public RemoteTask GetRemoteTaskForElement(IUnitTestElement element)
{
return session.GetRemoteTaskForElement(element);
}
public void Run(IUnitTestElements elements, IEnumerable<IProject> projects, IHostProvider provider,
PlatformType automatic,
PlatformVersion frameworkVersion)
{
session.Run(elements, projects, provider, automatic, frameworkVersion);
}
public void TaskStarting(IUnitTestRun run, RemoteTask remoteTask)
{
session.TaskStarting(run, remoteTask);
}
public void TaskOutput(IUnitTestRun run, RemoteTask remoteTask, string text, TaskOutputType type)
{
session.TaskOutput(run, remoteTask, text, type);
}
public void TaskException(IUnitTestRun run, RemoteTask remoteTask, TaskException[] exceptions)
{
session.TaskException(run, remoteTask, exceptions);
}
public void TaskFinished(IUnitTestRun run, RemoteTask remoteTask, string message, TaskResult result)
{
session.TaskFinished(run, remoteTask, message, result);
}
public void TaskDuration(IUnitTestRun run, RemoteTask remoteTask, TimeSpan duration)
{
session.TaskDuration(run, remoteTask, duration);
}
public void TaskDiscovered(IUnitTestRun run, RemoteTask task)
{
session.TaskDiscovered(run, task);
}
public void ShowNotification(string message, string description)
{
session.ShowNotification(message, description);
}
public void ShowNotification(string message, Action action)
{
session.ShowNotification(message, action);
}
public void HideHotification()
{
session.HideHotification();
}
public void Finish()
{
session.Finish();
}
public void Abort()
{
session.Abort();
}
public IUnitTestRun CreateRun(RuntimeEnvironment runtimeEnvironment)
{
return session.CreateRun(runtimeEnvironment);
}
public string Id
{
get { return session.Id; }
}
public Lifetime Lifetime
{
get { return session.Lifetime; }
}
public IProperty<UnitTestSessionState> State
{
get { return session.State; }
}
public IEnumerable<IUnitTestRun> Runs
{
get { return session.Runs; }
}
public IEnumerable<IUnitTestElement> Elements
{
get { return session.Elements; }
}
public DateTime DateTimeStarted
{
get { return session.DateTimeStarted; }
}
public IUnitTestElement LastStartedElement
{
get { return session.LastStartedElement; }
}
#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.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysisFramework;
using Internal.IL;
using Internal.IL.Stubs;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler
{
public abstract class Compilation : ICompilation
{
protected readonly DependencyAnalyzerBase<NodeFactory> _dependencyGraph;
protected readonly NodeFactory _nodeFactory;
protected readonly Logger _logger;
public NameMangler NameMangler => _nodeFactory.NameMangler;
public NodeFactory NodeFactory => _nodeFactory;
public CompilerTypeSystemContext TypeSystemContext => NodeFactory.TypeSystemContext;
public Logger Logger => _logger;
internal PInvokeILProvider PInvokeILProvider { get; }
protected abstract bool GenerateDebugInfo { get; }
private readonly TypeGetTypeMethodThunkCache _typeGetTypeMethodThunks;
private readonly AssemblyGetExecutingAssemblyMethodThunkCache _assemblyGetExecutingAssemblyMethodThunks;
private readonly MethodBaseGetCurrentMethodThunkCache _methodBaseGetCurrentMethodThunks;
protected Compilation(
DependencyAnalyzerBase<NodeFactory> dependencyGraph,
NodeFactory nodeFactory,
IEnumerable<ICompilationRootProvider> compilationRoots,
Logger logger)
{
_dependencyGraph = dependencyGraph;
_nodeFactory = nodeFactory;
_logger = logger;
_dependencyGraph.ComputeDependencyRoutine += ComputeDependencyNodeDependencies;
NodeFactory.AttachToDependencyGraph(_dependencyGraph);
var rootingService = new RootingServiceProvider(dependencyGraph, nodeFactory);
foreach (var rootProvider in compilationRoots)
rootProvider.AddCompilationRoots(rootingService);
MetadataType globalModuleGeneratedType = nodeFactory.CompilationModuleGroup.GeneratedAssembly.GetGlobalModuleType();
_typeGetTypeMethodThunks = new TypeGetTypeMethodThunkCache(globalModuleGeneratedType);
_assemblyGetExecutingAssemblyMethodThunks = new AssemblyGetExecutingAssemblyMethodThunkCache(globalModuleGeneratedType);
_methodBaseGetCurrentMethodThunks = new MethodBaseGetCurrentMethodThunkCache();
bool? forceLazyPInvokeResolution = null;
// TODO: Workaround lazy PInvoke resolution not working with CppCodeGen yet
// https://github.com/dotnet/corert/issues/2454
// https://github.com/dotnet/corert/issues/2149
if (nodeFactory.IsCppCodegenTemporaryWorkaround) forceLazyPInvokeResolution = false;
PInvokeILProvider = new PInvokeILProvider(new PInvokeILEmitterConfiguration(forceLazyPInvokeResolution), nodeFactory.InteropStubManager.InteropStateManager);
_methodILCache = new ILProvider(PInvokeILProvider);
}
private ILProvider _methodILCache;
public MethodIL GetMethodIL(MethodDesc method)
{
// Flush the cache when it grows too big
if (_methodILCache.Count > 1000)
_methodILCache = new ILProvider(PInvokeILProvider);
return _methodILCache.GetMethodIL(method);
}
protected abstract void ComputeDependencyNodeDependencies(List<DependencyNodeCore<NodeFactory>> obj);
protected abstract void CompileInternal(string outputFile, ObjectDumper dumper);
public DelegateCreationInfo GetDelegateCtor(TypeDesc delegateType, MethodDesc target, bool followVirtualDispatch)
{
return DelegateCreationInfo.Create(delegateType, target, NodeFactory, followVirtualDispatch);
}
/// <summary>
/// Gets an object representing the static data for RVA mapped fields from the PE image.
/// </summary>
public ObjectNode GetFieldRvaData(FieldDesc field)
{
if (field.GetType() == typeof(PInvokeLazyFixupField))
{
var pInvokeFixup = (PInvokeLazyFixupField)field;
PInvokeMetadata metadata = pInvokeFixup.PInvokeMetadata;
return NodeFactory.PInvokeMethodFixup(metadata.Module, metadata.Name);
}
else
{
// Use the typical field definition in case this is an instantiated generic type
field = field.GetTypicalFieldDefinition();
return NodeFactory.ReadOnlyDataBlob(NameMangler.GetMangledFieldName(field),
((EcmaField)field).GetFieldRvaData(), NodeFactory.Target.PointerSize);
}
}
public bool HasLazyStaticConstructor(TypeDesc type)
{
return TypeSystemContext.HasLazyStaticConstructor(type);
}
public MethodDebugInformation GetDebugInfo(MethodIL methodIL)
{
if (!GenerateDebugInfo)
return MethodDebugInformation.None;
// This method looks odd right now, but it's an extensibility point that lets us generate
// fake debugging information for things that don't have physical symbols.
return methodIL.GetDebugInfo();
}
/// <summary>
/// Resolves a reference to an intrinsic method to a new method that takes it's place in the compilation.
/// This is used for intrinsics where the intrinsic expansion depends on the callsite.
/// </summary>
/// <param name="intrinsicMethod">The intrinsic method called.</param>
/// <param name="callsiteMethod">The callsite that calls the intrinsic.</param>
/// <returns>The intrinsic implementation to be called for this specific callsite.</returns>
public MethodDesc ExpandIntrinsicForCallsite(MethodDesc intrinsicMethod, MethodDesc callsiteMethod)
{
Debug.Assert(intrinsicMethod.IsIntrinsic);
var intrinsicOwningType = intrinsicMethod.OwningType as MetadataType;
if (intrinsicOwningType == null)
return intrinsicMethod;
if (intrinsicOwningType.Module != TypeSystemContext.SystemModule)
return intrinsicMethod;
if (intrinsicOwningType.Name == "Type" && intrinsicOwningType.Namespace == "System")
{
if (intrinsicMethod.Signature.IsStatic && intrinsicMethod.Name == "GetType")
{
ModuleDesc callsiteModule = (callsiteMethod.OwningType as MetadataType)?.Module;
if (callsiteModule != null)
{
Debug.Assert(callsiteModule is IAssemblyDesc, "Multi-module assemblies");
return _typeGetTypeMethodThunks.GetHelper(intrinsicMethod, ((IAssemblyDesc)callsiteModule).GetName().FullName);
}
}
}
else if (intrinsicOwningType.Name == "Assembly" && intrinsicOwningType.Namespace == "System.Reflection")
{
if (intrinsicMethod.Signature.IsStatic && intrinsicMethod.Name == "GetExecutingAssembly")
{
ModuleDesc callsiteModule = (callsiteMethod.OwningType as MetadataType)?.Module;
if (callsiteModule != null)
{
Debug.Assert(callsiteModule is IAssemblyDesc, "Multi-module assemblies");
return _assemblyGetExecutingAssemblyMethodThunks.GetHelper((IAssemblyDesc)callsiteModule);
}
}
}
else if (intrinsicOwningType.Name == "MethodBase" && intrinsicOwningType.Namespace == "System.Reflection")
{
if (intrinsicMethod.Signature.IsStatic && intrinsicMethod.Name == "GetCurrentMethod")
{
return _methodBaseGetCurrentMethodThunks.GetHelper(callsiteMethod).InstantiateAsOpen();
}
}
return intrinsicMethod;
}
public bool HasFixedSlotVTable(TypeDesc type)
{
return NodeFactory.VTable(type).HasFixedSlots;
}
CompilationResults ICompilation.Compile(string outputFile, ObjectDumper dumper)
{
if (dumper != null)
{
dumper.Begin();
}
// In multi-module builds, set the compilation unit prefix to prevent ambiguous symbols in linked object files
NameMangler.CompilationUnitPrefix = _nodeFactory.CompilationModuleGroup.IsSingleFileCompilation ? "" : Path.GetFileNameWithoutExtension(outputFile);
CompileInternal(outputFile, dumper);
if (dumper != null)
{
dumper.End();
}
return new CompilationResults(_dependencyGraph, _nodeFactory);
}
private class RootingServiceProvider : IRootingServiceProvider
{
private DependencyAnalyzerBase<NodeFactory> _graph;
private NodeFactory _factory;
public RootingServiceProvider(DependencyAnalyzerBase<NodeFactory> graph, NodeFactory factory)
{
_graph = graph;
_factory = factory;
}
public void AddCompilationRoot(MethodDesc method, string reason, string exportName = null)
{
IMethodNode methodEntryPoint = _factory.CanonicalEntrypoint(method);
_graph.AddRoot(methodEntryPoint, reason);
if (exportName != null)
_factory.NodeAliases.Add(methodEntryPoint, exportName);
}
public void AddCompilationRoot(TypeDesc type, string reason)
{
if (!ConstructedEETypeNode.CreationAllowed(type))
{
_graph.AddRoot(_factory.NecessaryTypeSymbol(type), reason);
}
else
{
_graph.AddRoot(_factory.ConstructedTypeSymbol(type), reason);
}
}
public void RootStaticBasesForType(TypeDesc type, string reason)
{
Debug.Assert(!type.IsGenericDefinition);
MetadataType metadataType = type as MetadataType;
if (metadataType != null)
{
if (metadataType.ThreadStaticFieldSize.AsInt > 0)
{
_graph.AddRoot(_factory.TypeThreadStaticIndex(metadataType), reason);
}
if (metadataType.GCStaticFieldSize.AsInt > 0)
{
_graph.AddRoot(_factory.TypeGCStaticsSymbol(metadataType), reason);
}
if (metadataType.NonGCStaticFieldSize.AsInt > 0)
{
_graph.AddRoot(_factory.TypeNonGCStaticsSymbol(metadataType), reason);
}
}
}
public void RootVirtualMethodForReflection(MethodDesc method, string reason)
{
Debug.Assert(method.IsVirtual);
if (!_factory.VTable(method.OwningType).HasFixedSlots)
_graph.AddRoot(_factory.VirtualMethodUse(method), reason);
if (method.IsAbstract)
{
_graph.AddRoot(_factory.ReflectableMethod(method), reason);
}
}
}
}
// Interface under which Compilation is exposed externally.
public interface ICompilation
{
CompilationResults Compile(string outputFileName, ObjectDumper dumper);
}
public class CompilationResults
{
private readonly DependencyAnalyzerBase<NodeFactory> _graph;
private readonly NodeFactory _factory;
protected ImmutableArray<DependencyNodeCore<NodeFactory>> MarkedNodes
{
get
{
return _graph.MarkedNodeList;
}
}
internal CompilationResults(DependencyAnalyzerBase<NodeFactory> graph, NodeFactory factory)
{
_graph = graph;
_factory = factory;
}
public void WriteDependencyLog(string fileName)
{
using (FileStream dgmlOutput = new FileStream(fileName, FileMode.Create))
{
DgmlWriter.WriteDependencyGraphToStream(dgmlOutput, _graph, _factory);
dgmlOutput.Flush();
}
}
public IEnumerable<MethodDesc> CompiledMethodBodies
{
get
{
foreach (var node in MarkedNodes)
{
if (node is IMethodBodyNode)
yield return ((IMethodBodyNode)node).Method;
}
}
}
public IEnumerable<TypeDesc> ConstructedEETypes
{
get
{
foreach (var node in MarkedNodes)
{
if (node is ConstructedEETypeNode || node is CanonicalEETypeNode)
{
yield return ((IEETypeNode)node).Type;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Management.Automation;
using System.Text;
using System.Windows.Documents;
namespace Microsoft.Management.UI.Internal
{
/// <summary>
/// Builds a help paragraph for a cmdlet.
/// </summary>
internal class HelpParagraphBuilder : ParagraphBuilder
{
/// <summary>
/// Indentation size.
/// </summary>
internal const int IndentSize = 4;
/// <summary>
/// new line separators.
/// </summary>
private static readonly string[] Separators = new[] { "\r\n", "\n" };
/// <summary>
/// Object with the cmdelt.
/// </summary>
private readonly PSObject psObj;
/// <summary>
/// Initializes a new instance of the HelpParagraphBuilder class.
/// </summary>
/// <param name="paragraph">Paragraph being built.</param>
/// <param name="psObj">Object with help information.</param>
internal HelpParagraphBuilder(Paragraph paragraph, PSObject psObj)
: base(paragraph)
{
this.psObj = psObj;
this.AddTextToParagraphBuilder();
}
/// <summary>
/// Enum for category of Help.
/// </summary>
private enum HelpCategory
{
Default,
DscResource,
Class
}
/// <summary>
/// Gets the string value of a property or null if it could not be retrieved.
/// </summary>
/// <param name="psObj">Object with the property.</param>
/// <param name="propertyName">Property name.</param>
/// <returns>The string value of a property or null if it could not be retrieved.</returns>
internal static string GetPropertyString(PSObject psObj, string propertyName)
{
Debug.Assert(psObj != null, "ensured by caller");
object value = GetPropertyObject(psObj, propertyName);
if (value == null)
{
return null;
}
return value.ToString();
}
/// <summary>
/// Adds the help text to the paragraph.
/// </summary>
internal void AddTextToParagraphBuilder()
{
this.ResetAllText();
string strCategory = HelpParagraphBuilder.GetProperty(this.psObj, "Category").Value.ToString();
HelpCategory category = HelpCategory.Default;
if (string.Equals(strCategory, "DscResource", StringComparison.OrdinalIgnoreCase))
{
category = HelpCategory.DscResource;
}
else if (string.Equals(strCategory, "Class", StringComparison.OrdinalIgnoreCase))
{
category = HelpCategory.Class;
}
if (HelpParagraphBuilder.GetProperty(this.psObj, "Syntax") == null)
{
if (category == HelpCategory.Default)
{
// if there is no syntax, this is not the standard help
// it might be an about page
this.AddText(this.psObj.ToString(), false);
return;
}
}
switch (category)
{
case HelpCategory.Class:
this.AddDescription(HelpWindowSettings.Default.HelpSynopsysDisplayed, HelpWindowResources.SynopsisTitle, "Introduction");
this.AddMembers(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.PropertiesTitle);
this.AddMembers(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.MethodsTitle);
break;
case HelpCategory.DscResource:
this.AddStringSection(HelpWindowSettings.Default.HelpSynopsysDisplayed, "Synopsis", HelpWindowResources.SynopsisTitle);
this.AddDescription(HelpWindowSettings.Default.HelpDescriptionDisplayed, HelpWindowResources.DescriptionTitle, "Description");
this.AddParameters(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.PropertiesTitle, "Properties", HelpCategory.DscResource);
break;
default:
this.AddStringSection(HelpWindowSettings.Default.HelpSynopsysDisplayed, "Synopsis", HelpWindowResources.SynopsisTitle);
this.AddDescription(HelpWindowSettings.Default.HelpDescriptionDisplayed, HelpWindowResources.DescriptionTitle, "Description");
this.AddParameters(HelpWindowSettings.Default.HelpParametersDisplayed, HelpWindowResources.ParametersTitle, "Parameters", HelpCategory.Default);
this.AddSyntax(HelpWindowSettings.Default.HelpSyntaxDisplayed, HelpWindowResources.SyntaxTitle);
break;
}
this.AddInputOrOutputEntries(HelpWindowSettings.Default.HelpInputsDisplayed, HelpWindowResources.InputsTitle, "inputTypes", "inputType");
this.AddInputOrOutputEntries(HelpWindowSettings.Default.HelpOutputsDisplayed, HelpWindowResources.OutputsTitle, "returnValues", "returnValue");
this.AddNotes(HelpWindowSettings.Default.HelpNotesDisplayed, HelpWindowResources.NotesTitle);
this.AddExamples(HelpWindowSettings.Default.HelpExamplesDisplayed, HelpWindowResources.ExamplesTitle);
this.AddNavigationLink(HelpWindowSettings.Default.HelpRelatedLinksDisplayed, HelpWindowResources.RelatedLinksTitle);
this.AddStringSection(HelpWindowSettings.Default.HelpRemarksDisplayed, "Remarks", HelpWindowResources.RemarksTitle);
}
/// <summary>
/// Gets the object property or null if it could not be retrieved.
/// </summary>
/// <param name="psObj">Object with the property.</param>
/// <param name="propertyName">Property name.</param>
/// <returns>The object property or null if it could not be retrieved.</returns>
private static PSPropertyInfo GetProperty(PSObject psObj, string propertyName)
{
Debug.Assert(psObj != null, "ensured by caller");
return psObj.Properties[propertyName];
}
/// <summary>
/// Gets a PSObject and then a value from it or null if the value could not be retrieved.
/// </summary>
/// <param name="psObj">PSObject that contains another PSObject as a property.</param>
/// <param name="psObjectName">Property name that contains the PSObject.</param>
/// <param name="propertyName">Property name in thye inner PSObject.</param>
/// <returns>The string from the inner psObject property or null if it could not be retrieved.</returns>
private static string GetInnerPSObjectPropertyString(PSObject psObj, string psObjectName, string propertyName)
{
Debug.Assert(psObj != null, "ensured by caller");
PSObject innerPsObj = GetPropertyObject(psObj, psObjectName) as PSObject;
if (innerPsObj == null)
{
return null;
}
object value = GetPropertyObject(innerPsObj, propertyName);
if (value == null)
{
return null;
}
return value.ToString();
}
/// <summary>
/// Gets the value of a property or null if the value could not be retrieved.
/// </summary>
/// <param name="psObj">Object with the property.</param>
/// <param name="propertyName">Property name.</param>
/// <returns>The value of a property or null if the value could not be retrieved.</returns>
private static object GetPropertyObject(PSObject psObj, string propertyName)
{
Debug.Assert(psObj != null, "ensured by caller");
PSPropertyInfo property = HelpParagraphBuilder.GetProperty(psObj, propertyName);
if (property == null)
{
return null;
}
object value = null;
try
{
value = property.Value;
}
catch (ExtendedTypeSystemException)
{
// ignore this exception
}
return value;
}
/// <summary>
/// Gets the text from a property of type PSObject[] where the first object has a text property.
/// </summary>
/// <param name="psObj">Objhect to get text from.</param>
/// <param name="propertyText">Property with PSObject[] containing text.</param>
/// <returns>The text from a property of type PSObject[] where the first object has a text property.</returns>
private static string GetTextFromArray(PSObject psObj, string propertyText)
{
PSObject[] introductionObjects = HelpParagraphBuilder.GetPropertyObject(psObj, propertyText) as PSObject[];
if (introductionObjects != null && introductionObjects.Length > 0)
{
return GetPropertyString(introductionObjects[0], "text");
}
return null;
}
/// <summary>
/// Returns the largest size of a group of strings.
/// </summary>
/// <param name="strs">Strings to evaluate the largest size from.</param>
/// <returns>The largest size of a group of strings.</returns>
private static int LargestSize(params string[] strs)
{
int returnValue = 0;
foreach (string str in strs)
{
if (str != null && str.Length > returnValue)
{
returnValue = str.Length;
}
}
return returnValue;
}
/// <summary>
/// Splits the string adding indentation before each line.
/// </summary>
/// <param name="str">String to add indentation to.</param>
/// <returns>The string indented.</returns>
private static string AddIndent(string str)
{
return HelpParagraphBuilder.AddIndent(str, 1);
}
/// <summary>
/// Splits the string adding indentation before each line.
/// </summary>
/// <param name="str">String to add indentation to.</param>
/// <param name="numberOfIdents">Number of indentations.</param>
/// <returns>The string indented.</returns>
private static string AddIndent(string str, int numberOfIdents)
{
StringBuilder indent = new StringBuilder();
indent.Append(' ', numberOfIdents * HelpParagraphBuilder.IndentSize);
return HelpParagraphBuilder.AddIndent(str, indent.ToString());
}
/// <summary>
/// Splits the string adding indentation before each line.
/// </summary>
/// <param name="str">String to add indentation to.</param>
/// <param name="indentString">Indentation string.</param>
/// <returns>The string indented.</returns>
private static string AddIndent(string str, string indentString)
{
if (str == null)
{
return string.Empty;
}
string[] lines = str.Split(Separators, StringSplitOptions.None);
StringBuilder returnValue = new StringBuilder();
foreach (string line in lines)
{
// Indentation is not localized
returnValue.AppendFormat("{0}{1}\r\n", indentString, line);
}
if (returnValue.Length > 2)
{
// remove the last \r\n
returnValue.Remove(returnValue.Length - 2, 2);
}
return returnValue.ToString();
}
/// <summary>
/// Get the object array value of a property.
/// </summary>
/// <param name="obj">Object containing the property.</param>
/// <param name="propertyName">Property with the array value.</param>
/// <returns>The object array value of a property.</returns>
private static object[] GetPropertyObjectArray(PSObject obj, string propertyName)
{
object innerObject;
if ((innerObject = HelpParagraphBuilder.GetPropertyObject(obj, propertyName)) == null)
{
return null;
}
if (innerObject is PSObject)
{
return new[] { innerObject };
}
object[] innerObjectArray = innerObject as object[];
return innerObjectArray;
}
/// <summary>
/// Adds a section that contains only a string.
/// </summary>
/// <param name="setting">True if it should add the segment.</param>
/// <param name="sectionName">Name of the section to add.</param>
/// <param name="sectionTitle">Title of the section.</param>
private void AddStringSection(bool setting, string sectionName, string sectionTitle)
{
string propertyValue;
if (!setting || (propertyValue = HelpParagraphBuilder.GetPropertyString(this.psObj, sectionName)) == null)
{
return;
}
this.AddText(sectionTitle, true);
this.AddText("\r\n", false);
this.AddText(HelpParagraphBuilder.AddIndent(propertyValue), false);
this.AddText("\r\n\r\n", false);
}
/// <summary>
/// Adds the help syntax segment.
/// </summary>
/// <param name="setting">True if it should add the segment.</param>
/// <param name="sectionTitle">Title of the section.</param>
private void AddSyntax(bool setting, string sectionTitle)
{
PSObject syntaxObject;
if (!setting || (syntaxObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "Syntax") as PSObject) == null)
{
return;
}
object[] syntaxItemsObj = HelpParagraphBuilder.GetPropertyObjectArray(syntaxObject, "syntaxItem");
if (syntaxItemsObj == null || syntaxItemsObj.Length == 0)
{
return;
}
this.AddText(sectionTitle, true);
this.AddText("\r\n", false);
foreach (object syntaxItemObj in syntaxItemsObj)
{
PSObject syntaxItem = syntaxItemObj as PSObject;
if (syntaxItem == null)
{
continue;
}
string commandName = GetPropertyString(syntaxItem, "name");
object[] parameterObjs = HelpParagraphBuilder.GetPropertyObjectArray(syntaxItem, "parameter");
if (commandName == null || parameterObjs == null || parameterObjs.Length == 0)
{
continue;
}
string commandStart = string.Format(CultureInfo.CurrentCulture, "{0} ", commandName);
this.AddText(HelpParagraphBuilder.AddIndent(commandStart), false);
foreach (object parameterObj in parameterObjs)
{
PSObject parameter = parameterObj as PSObject;
if (parameter == null)
{
continue;
}
string parameterValue = GetPropertyString(parameter, "parameterValue");
string position = GetPropertyString(parameter, "position");
string required = GetPropertyString(parameter, "required");
string parameterName = GetPropertyString(parameter, "name");
if (position == null || required == null || parameterName == null)
{
continue;
}
string parameterType = parameterValue == null ? string.Empty : string.Format(CultureInfo.CurrentCulture, "<{0}>", parameterValue);
string parameterOptionalOpenBrace, parameterOptionalCloseBrace;
if (string.Equals(required, "true", StringComparison.OrdinalIgnoreCase))
{
parameterOptionalOpenBrace = string.Empty;
parameterOptionalCloseBrace = string.Empty;
}
else
{
parameterOptionalOpenBrace = "[";
parameterOptionalCloseBrace = "]";
}
string parameterNameOptionalOpenBrace, parameterNameOptionalCloseBrace;
if (string.Equals(position, "named", StringComparison.OrdinalIgnoreCase))
{
parameterNameOptionalOpenBrace = parameterNameOptionalCloseBrace = string.Empty;
}
else
{
parameterNameOptionalOpenBrace = "[";
parameterNameOptionalCloseBrace = "]";
}
string paramterPrefix = string.Format(
CultureInfo.CurrentCulture,
"{0}{1}-",
parameterOptionalOpenBrace,
parameterNameOptionalOpenBrace);
this.AddText(paramterPrefix, false);
this.AddText(parameterName, true);
string paramterSuffix = string.Format(
CultureInfo.CurrentCulture,
"{0} {1}{2} ",
parameterNameOptionalCloseBrace,
parameterType,
parameterOptionalCloseBrace);
this.AddText(paramterSuffix, false);
}
string commonParametersText = string.Format(
CultureInfo.CurrentCulture,
"[<{0}>]\r\n\r\n",
HelpWindowResources.CommonParameters);
this.AddText(commonParametersText, false);
}
this.AddText("\r\n", false);
}
/// <summary>
/// Adds the help description segment.
/// </summary>
/// <param name="setting">True if it should add the segment.</param>
/// <param name="sectionTitle">Title of the section.</param>
/// <param name="propertyName">PropertyName that has description.</param>
private void AddDescription(bool setting, string sectionTitle, string propertyName)
{
PSObject[] descriptionObjects;
if (!setting ||
(descriptionObjects = HelpParagraphBuilder.GetPropertyObject(this.psObj, propertyName) as PSObject[]) == null ||
descriptionObjects.Length == 0)
{
return;
}
this.AddText(sectionTitle, true);
this.AddText("\r\n", false);
foreach (PSObject description in descriptionObjects)
{
string descriptionText = GetPropertyString(description, "text");
this.AddText(HelpParagraphBuilder.AddIndent(descriptionText), false);
this.AddText("\r\n", false);
}
this.AddText("\r\n\r\n", false);
}
/// <summary>
/// Adds the help examples segment.
/// </summary>
/// <param name="setting">True if it should add the segment.</param>
/// <param name="sectionTitle">Title of the section.</param>
private void AddExamples(bool setting, string sectionTitle)
{
if (!setting)
{
return;
}
PSObject exampleRootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "Examples") as PSObject;
if (exampleRootObject == null)
{
return;
}
object[] exampleObjects = HelpParagraphBuilder.GetPropertyObjectArray(exampleRootObject, "example");
if (exampleObjects == null || exampleObjects.Length == 0)
{
return;
}
this.AddText(sectionTitle, true);
this.AddText("\r\n", false);
foreach (object exampleObj in exampleObjects)
{
PSObject example = exampleObj as PSObject;
if (example == null)
{
continue;
}
string introductionText = null;
introductionText = GetTextFromArray(example, "introduction");
string codeText = GetPropertyString(example, "code");
string title = GetPropertyString(example, "title");
if (codeText == null)
{
continue;
}
if (title != null)
{
this.AddText(HelpParagraphBuilder.AddIndent(title), false);
this.AddText("\r\n", false);
}
string codeLine = string.Format(
CultureInfo.CurrentCulture,
"{0}{1}\r\n\r\n",
introductionText,
codeText);
this.AddText(HelpParagraphBuilder.AddIndent(codeLine), false);
PSObject[] remarks = HelpParagraphBuilder.GetPropertyObject(example, "remarks") as PSObject[];
if (remarks == null)
{
continue;
}
foreach (PSObject remark in remarks)
{
string remarkText = GetPropertyString(remark, "text");
if (remarkText == null)
{
continue;
}
this.AddText(remarkText, false);
this.AddText("\r\n", false);
}
}
this.AddText("\r\n\r\n", false);
}
private void AddMembers(bool setting, string sectionTitle)
{
if (!setting || string.IsNullOrEmpty(sectionTitle))
{
return;
}
PSObject memberRootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "Members") as PSObject;
if (memberRootObject == null)
{
return;
}
object[] memberObjects = HelpParagraphBuilder.GetPropertyObjectArray(memberRootObject, "member");
if (memberObjects == null)
{
return;
}
this.AddText(sectionTitle, true);
this.AddText("\r\n", false);
foreach (object memberObj in memberObjects)
{
string description = null;
string memberText = null;
PSObject member = memberObj as PSObject;
if (member == null)
{
continue;
}
string name = GetPropertyString(member, "title");
string type = GetPropertyString(member, "type");
string propertyType = null;
if (string.Equals("field", type, StringComparison.OrdinalIgnoreCase))
{
PSObject fieldData = HelpParagraphBuilder.GetPropertyObject(member, "fieldData") as PSObject;
if (fieldData != null)
{
PSObject propertyTypeObject = HelpParagraphBuilder.GetPropertyObject(fieldData, "type") as PSObject;
if (propertyTypeObject != null)
{
propertyType = GetPropertyString(propertyTypeObject, "name");
description = GetPropertyString(propertyTypeObject, "description");
}
memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}\r\n", propertyType, name);
}
}
else if (string.Equals("method", type, StringComparison.OrdinalIgnoreCase))
{
FormatMethodData(member, name, out memberText, out description);
}
if (!string.IsNullOrEmpty(memberText))
{
this.AddText(HelpParagraphBuilder.AddIndent(string.Empty), false);
this.AddText(memberText, true);
if (description != null)
{
this.AddText(HelpParagraphBuilder.AddIndent(description, 2), false);
this.AddText("\r\n", false);
}
this.AddText("\r\n", false);
}
}
}
private static void FormatMethodData(PSObject member, string name, out string memberText, out string description)
{
memberText = null;
description = null;
if (member == null || string.IsNullOrEmpty(name))
{
return;
}
string returnType = null;
StringBuilder parameterText = new StringBuilder();
// Get method return type
PSObject returnTypeObject = HelpParagraphBuilder.GetPropertyObject(member, "returnValue") as PSObject;
if (returnTypeObject != null)
{
PSObject returnTypeData = HelpParagraphBuilder.GetPropertyObject(returnTypeObject, "type") as PSObject;
if (returnTypeData != null)
{
returnType = GetPropertyString(returnTypeData, "name");
}
}
// Get method description.
PSObject[] methodDescriptions = HelpParagraphBuilder.GetPropertyObject(member, "introduction") as PSObject[];
if (methodDescriptions != null)
{
foreach (var methodDescription in methodDescriptions)
{
description = GetPropertyString(methodDescription, "Text");
// If we get an text we do not need to iterate more.
if (!string.IsNullOrEmpty(description))
{
break;
}
}
}
// Get method parameters.
PSObject parametersObject = HelpParagraphBuilder.GetPropertyObject(member, "parameters") as PSObject;
if (parametersObject != null)
{
PSObject[] paramObject = HelpParagraphBuilder.GetPropertyObject(parametersObject, "parameter") as PSObject[];
if (paramObject != null)
{
foreach (var param in paramObject)
{
string parameterName = GetPropertyString(param, "name");
string parameterType = null;
PSObject parameterTypeData = HelpParagraphBuilder.GetPropertyObject(param, "type") as PSObject;
if (parameterTypeData != null)
{
parameterType = GetPropertyString(parameterTypeData, "name");
// If there is no type for the parameter, we expect it is System.Object
if (string.IsNullOrEmpty(parameterType))
{
parameterType = "object";
}
}
string paramString = string.Format(CultureInfo.CurrentCulture, "[{0}] ${1},", parameterType, parameterName);
parameterText.Append(paramString);
}
if (string.Equals(parameterText[parameterText.Length - 1].ToString(), ",", StringComparison.OrdinalIgnoreCase))
{
parameterText = parameterText.Remove(parameterText.Length - 1, 1);
}
}
}
memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}({2})\r\n", returnType, name, parameterText);
}
/// <summary>
/// Adds the help parameters segment.
/// </summary>
/// <param name="setting">True if it should add the segment.</param>
/// <param name="sectionTitle">Title of the section.</param>
/// <param name="paramPropertyName">Name of the property which has properties.</param>
/// <param name="helpCategory">Category of help.</param>
private void AddParameters(bool setting, string sectionTitle, string paramPropertyName, HelpCategory helpCategory)
{
if (!setting)
{
return;
}
PSObject parameterRootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, paramPropertyName) as PSObject;
if (parameterRootObject == null)
{
return;
}
object[] parameterObjects = null;
// Root object for Class has members not parameters.
if (helpCategory != HelpCategory.Class)
{
parameterObjects = HelpParagraphBuilder.GetPropertyObjectArray(parameterRootObject, "parameter");
}
if (parameterObjects == null || parameterObjects.Length == 0)
{
return;
}
this.AddText(sectionTitle, true);
this.AddText("\r\n", false);
foreach (object parameterObj in parameterObjects)
{
PSObject parameter = parameterObj as PSObject;
if (parameter == null)
{
continue;
}
string parameterValue = GetPropertyString(parameter, "parameterValue");
string name = GetPropertyString(parameter, "name");
string description = GetTextFromArray(parameter, "description");
string required = GetPropertyString(parameter, "required");
string position = GetPropertyString(parameter, "position");
string pipelineinput = GetPropertyString(parameter, "pipelineInput");
string defaultValue = GetPropertyString(parameter, "defaultValue");
string acceptWildcard = GetPropertyString(parameter, "globbing");
if (string.IsNullOrEmpty(name))
{
continue;
}
if (helpCategory == HelpCategory.DscResource)
{
this.AddText(HelpParagraphBuilder.AddIndent(string.Empty), false);
}
else
{
this.AddText(HelpParagraphBuilder.AddIndent("-"), false);
}
this.AddText(name, true);
string parameterText = string.Format(
CultureInfo.CurrentCulture,
" <{0}>\r\n",
parameterValue);
this.AddText(parameterText, false);
if (description != null)
{
this.AddText(HelpParagraphBuilder.AddIndent(description, 2), false);
this.AddText("\r\n", false);
}
this.AddText("\r\n", false);
int largestSize = HelpParagraphBuilder.LargestSize(
HelpWindowResources.ParameterRequired,
HelpWindowResources.ParameterPosition,
HelpWindowResources.ParameterDefaultValue,
HelpWindowResources.ParameterPipelineInput,
HelpWindowResources.ParameterAcceptWildcard);
// justification of parameter values is not localized
string formatString = string.Format(
CultureInfo.CurrentCulture,
"{{0,-{0}}}{{1}}",
largestSize + 2);
string tableLine;
tableLine = string.Format(
CultureInfo.CurrentCulture,
formatString,
HelpWindowResources.ParameterRequired,
required);
this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
this.AddText("\r\n", false);
// these are not applicable for Dsc Resource help
if (helpCategory != HelpCategory.DscResource)
{
tableLine = string.Format(
CultureInfo.CurrentCulture,
formatString,
HelpWindowResources.ParameterPosition,
position);
this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
this.AddText("\r\n", false);
tableLine = string.Format(
CultureInfo.CurrentCulture,
formatString,
HelpWindowResources.ParameterDefaultValue,
defaultValue);
this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
this.AddText("\r\n", false);
tableLine = string.Format(
CultureInfo.CurrentCulture,
formatString,
HelpWindowResources.ParameterPipelineInput,
pipelineinput);
this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
this.AddText("\r\n", false);
tableLine = string.Format(
CultureInfo.CurrentCulture,
formatString,
HelpWindowResources.ParameterAcceptWildcard,
acceptWildcard);
this.AddText(HelpParagraphBuilder.AddIndent(tableLine, 2), false);
}
this.AddText("\r\n\r\n", false);
}
this.AddText("\r\n\r\n", false);
}
/// <summary>
/// Adds the help navigation links segment.
/// </summary>
/// <param name="setting">True if it should add the segment.</param>
/// <param name="sectionTitle">Title of the section.</param>
private void AddNavigationLink(bool setting, string sectionTitle)
{
if (!setting)
{
return;
}
PSObject linkRootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "RelatedLinks") as PSObject;
if (linkRootObject == null)
{
return;
}
PSObject[] linkObjects;
if ((linkObjects = HelpParagraphBuilder.GetPropertyObject(linkRootObject, "navigationLink") as PSObject[]) == null ||
linkObjects.Length == 0)
{
return;
}
this.AddText(sectionTitle, true);
this.AddText("\r\n", false);
foreach (PSObject linkObject in linkObjects)
{
string text = GetPropertyString(linkObject, "linkText");
string uri = GetPropertyString(linkObject, "uri");
string linkLine = string.IsNullOrEmpty(uri) ? text : string.Format(
CultureInfo.CurrentCulture,
HelpWindowResources.LinkTextFormat,
text,
uri);
this.AddText(HelpParagraphBuilder.AddIndent(linkLine), false);
this.AddText("\r\n", false);
}
this.AddText("\r\n\r\n", false);
}
/// <summary>
/// Adds the help input or output segment.
/// </summary>
/// <param name="setting">True if it should add the segment.</param>
/// <param name="sectionTitle">Title of the section.</param>
/// <param name="inputOrOutputProperty">Property with the outter object.</param>
/// <param name="inputOrOutputInnerProperty">Property with the inner object.</param>
private void AddInputOrOutputEntries(bool setting, string sectionTitle, string inputOrOutputProperty, string inputOrOutputInnerProperty)
{
if (!setting)
{
return;
}
PSObject rootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, inputOrOutputProperty) as PSObject;
if (rootObject == null)
{
return;
}
object[] inputOrOutputObjs;
inputOrOutputObjs = HelpParagraphBuilder.GetPropertyObjectArray(rootObject, inputOrOutputInnerProperty);
if (inputOrOutputObjs == null || inputOrOutputObjs.Length == 0)
{
return;
}
this.AddText(sectionTitle, true);
this.AddText("\r\n", false);
foreach (object inputOrOutputObj in inputOrOutputObjs)
{
PSObject inputOrOutput = inputOrOutputObj as PSObject;
if (inputOrOutput == null)
{
continue;
}
string type = HelpParagraphBuilder.GetInnerPSObjectPropertyString(inputOrOutput, "type", "name");
string description = GetTextFromArray(inputOrOutput, "description");
this.AddText(HelpParagraphBuilder.AddIndent(type), false);
this.AddText("\r\n", false);
if (description != null)
{
this.AddText(HelpParagraphBuilder.AddIndent(description), false);
this.AddText("\r\n", false);
}
}
this.AddText("\r\n", false);
}
/// <summary>
/// Adds the help notes segment.
/// </summary>
/// <param name="setting">True if it should add the segment.</param>
/// <param name="sectionTitle">Title of the section.</param>
private void AddNotes(bool setting, string sectionTitle)
{
if (!setting)
{
return;
}
PSObject rootObject = HelpParagraphBuilder.GetPropertyObject(this.psObj, "alertSet") as PSObject;
if (rootObject == null)
{
return;
}
string note = GetTextFromArray(rootObject, "alert");
if (note == null)
{
return;
}
this.AddText(sectionTitle, true);
this.AddText("\r\n", false);
this.AddText(HelpParagraphBuilder.AddIndent(note), false);
this.AddText("\r\n\r\n", false);
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Moq;
using PSycheTest.Exceptions;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.Framework.Results;
using PSycheTest.Runners.Framework.Timers;
using PSycheTest.Runners.Framework.Utilities.Collections;
using Tests.Integration.TestScripts;
using Tests.Support;
using Xunit;
namespace Tests.Integration.PSycheTest.Runners.Framework
{
public class PowerShellTestExecutorTests
{
public PowerShellTestExecutorTests()
{
discoverer = new PowerShellTestDiscoverer(logger.Object);
executor = new PowerShellTestExecutor(logger.Object, () => new StopwatchTimer(), new SynchronousTaskScheduler())
{
OutputDirectory = new DirectoryInfo(Directory.GetCurrentDirectory())
};
}
[Fact]
public async Task Test_ExecuteAsync_Single_File_Single_Test()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasOneTest);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.NotEmpty(results);
Assert.Single(results);
var result = Assert.IsType<FailedResult>(results.Single());
Assert.Equal(TestStatus.Failed, result.Status);
Assert.NotNull(result.Duration);
Assert.True(result.Duration > TimeSpan.Zero);
var reason = Assert.IsType<ExpectedActualException>(result.Reason.Exception);
Assert.Equal(true, reason.Expected);
Assert.Equal(false, reason.Actual);
}
[Fact]
public async Task Test_ExecuteAsync_Single_File_Multiple_Tests()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasMultipleTests);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.Equal(4, results.Count);
var firstResult = Assert.IsType<FailedResult>(results[0]);
Assert.Equal(TestStatus.Failed, firstResult.Status);
Assert.NotNull(firstResult.Duration);
Assert.True(firstResult.Duration > TimeSpan.Zero);
Assert.IsType<ExpectedActualException>(firstResult.Reason.Exception);
var secondResult = Assert.IsType<FailedResult>(results[1]);
Assert.Equal(TestStatus.Failed, secondResult.Status);
Assert.NotNull(secondResult.Duration);
Assert.True(secondResult.Duration > TimeSpan.Zero);
Assert.IsType<ExpectedActualException>(secondResult.Reason.Exception);
var thirdResult = Assert.IsType<PassedResult>(results[2]);
Assert.Equal(TestStatus.Passed, thirdResult.Status);
Assert.NotNull(thirdResult.Duration);
Assert.True(thirdResult.Duration > TimeSpan.Zero);
var fourthResult = Assert.IsType<PassedResult>(results[3]);
Assert.Equal(TestStatus.Passed, fourthResult.Status);
Assert.NotNull(fourthResult.Duration);
Assert.True(fourthResult.Duration > TimeSpan.Zero);
}
[Fact]
public async Task Test_ExecuteAsync_Single_File_Skipped_Test()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasSkippedTest);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.NotEmpty(results);
Assert.Equal(2, results.Count);
var skippedResult = Assert.IsType<SkippedResult>(results.First());
Assert.Equal(TestStatus.Skipped, skippedResult.Status);
Assert.Null(skippedResult.Duration);
var passedResult = Assert.IsType<PassedResult>(results.Last());
Assert.Equal(TestStatus.Passed, passedResult.Status);
Assert.NotNull(passedResult.Duration);
Assert.True(passedResult.Duration > TimeSpan.Zero);
}
[Fact]
public async Task Test_ExecuteAsync_Single_File_Setup_And_Cleanup()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasSetupAndCleanup);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.NotEmpty(results);
Assert.Equal(2, results.Count);
foreach (var result in results)
{
Assert.IsType<PassedResult>(result);
Assert.Equal(TestStatus.Passed, result.Status);
Assert.NotNull(result.Duration);
Assert.True(result.Duration > TimeSpan.Zero);
}
}
[Fact]
public async Task Test_ExecuteAsync_Multiple_Files()
{
// Arrange.
var scripts = discoverer.Discover(new[]
{
ScriptFiles.HasSetupAndCleanup, ScriptFiles.HasMultipleTests
}).ToList();
// Act.
await executor.ExecuteAsync(scripts);
var results = scripts.SelectMany(s => s.Results).ToList();
// Assert.
Assert.Equal(6, results.Count);
Assert.Equal(new[] { TestStatus.Passed, TestStatus.Passed, TestStatus.Failed, TestStatus.Failed, TestStatus.Passed, TestStatus.Passed },
results.Select(r => r.Status));
}
[Fact]
public async Task Test_ExecuteAsync_Tests_Failed_By_NonFunction_Error()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasNonFunctionErrors);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.Equal(2, results.Count);
var firstResult = Assert.IsType<FailedResult>(results[0]);
Assert.Equal(TestStatus.Failed, firstResult.Status);
Assert.NotNull(firstResult.Duration);
Assert.True(firstResult.Duration > TimeSpan.Zero);
Assert.IsType<ExpectedActualException>(firstResult.Reason.Exception);
var secondResult = Assert.IsType<FailedResult>(results[1]);
Assert.Equal(TestStatus.Failed, secondResult.Status);
Assert.NotNull(secondResult.Duration);
Assert.True(secondResult.Duration > TimeSpan.Zero);
Assert.IsType<ExpectedActualException>(secondResult.Reason.Exception);
}
[Fact]
public async Task Test_ExecuteAsync_With_Filter()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasMultipleTests).Value;
// Act.
await executor.ExecuteAsync(testScript.ToEnumerable(), tf => !tf.FunctionName.EndsWith("Failure"));
var results = testScript.Results.ToList();
// Assert.
Assert.Equal(2, results.Count);
foreach (var result in results)
{
var passed = Assert.IsType<PassedResult>(result);
Assert.Equal(TestStatus.Passed, passed.Status);
}
}
[Fact]
public async Task Test_ExecuteAsync_With_External_Script_Reference()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasScriptReferences);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.NotEmpty(results);
Assert.Single(results);
var result = Assert.IsType<PassedResult>(results.Single());
Assert.Equal(TestStatus.Passed, result.Status);
Assert.NotNull(result.Duration);
Assert.True(result.Duration > TimeSpan.Zero);
}
private readonly PowerShellTestExecutor executor;
private readonly PowerShellTestDiscoverer discoverer;
private readonly Mock<ILogger> logger = new Mock<ILogger>();
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Int16Animation.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Utility;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// Animates the value of a Int16 property using linear interpolation
/// between two values. The values are determined by the combination of
/// From, To, or By values that are set on the animation.
/// </summary>
public partial class Int16Animation :
Int16AnimationBase
{
#region Data
/// <summary>
/// This is used if the user has specified From, To, and/or By values.
/// </summary>
private Int16[] _keyValues;
private AnimationType _animationType;
private bool _isAnimationFunctionValid;
#endregion
#region Constructors
/// <summary>
/// Static ctor for Int16Animation establishes
/// dependency properties, using as much shared data as possible.
/// </summary>
static Int16Animation()
{
Type typeofProp = typeof(Int16?);
Type typeofThis = typeof(Int16Animation);
PropertyChangedCallback propCallback = new PropertyChangedCallback(AnimationFunction_Changed);
ValidateValueCallback validateCallback = new ValidateValueCallback(ValidateFromToOrByValue);
FromProperty = DependencyProperty.Register(
"From",
typeofProp,
typeofThis,
new PropertyMetadata((Int16?)null, propCallback),
validateCallback);
ToProperty = DependencyProperty.Register(
"To",
typeofProp,
typeofThis,
new PropertyMetadata((Int16?)null, propCallback),
validateCallback);
ByProperty = DependencyProperty.Register(
"By",
typeofProp,
typeofThis,
new PropertyMetadata((Int16?)null, propCallback),
validateCallback);
EasingFunctionProperty = DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeofThis);
}
/// <summary>
/// Creates a new Int16Animation with all properties set to
/// their default values.
/// </summary>
public Int16Animation()
: base()
{
}
/// <summary>
/// Creates a new Int16Animation that will animate a
/// Int16 property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public Int16Animation(Int16 toValue, Duration duration)
: this()
{
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new Int16Animation that will animate a
/// Int16 property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public Int16Animation(Int16 toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
/// <summary>
/// Creates a new Int16Animation that will animate a
/// Int16 property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public Int16Animation(Int16 fromValue, Int16 toValue, Duration duration)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new Int16Animation that will animate a
/// Int16 property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public Int16Animation(Int16 fromValue, Int16 toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this Int16Animation
/// </summary>
/// <returns>The copy</returns>
public new Int16Animation Clone()
{
return (Int16Animation)base.Clone();
}
//
// Note that we don't override the Clone virtuals (CloneCore, CloneCurrentValueCore,
// GetAsFrozenCore, and GetCurrentValueAsFrozenCore) even though this class has state
// not stored in a DP.
//
// We don't need to clone _animationType and _keyValues because they are the the cached
// results of animation function validation, which can be recomputed. The other remaining
// field, isAnimationFunctionValid, defaults to false, which causes this recomputation to happen.
//
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new Int16Animation();
}
#endregion
#region Methods
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected override Int16 GetCurrentValueCore(Int16 defaultOriginValue, Int16 defaultDestinationValue, AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (!_isAnimationFunctionValid)
{
ValidateAnimationFunction();
}
double progress = animationClock.CurrentProgress.Value;
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
progress = easingFunction.Ease(progress);
}
Int16 from = new Int16();
Int16 to = new Int16();
Int16 accumulated = new Int16();
Int16 foundation = new Int16();
// need to validate the default origin and destination values if
// the animation uses them as the from, to, or foundation values
bool validateOrigin = false;
bool validateDestination = false;
switch(_animationType)
{
case AnimationType.Automatic:
from = defaultOriginValue;
to = defaultDestinationValue;
validateOrigin = true;
validateDestination = true;
break;
case AnimationType.From:
from = _keyValues[0];
to = defaultDestinationValue;
validateDestination = true;
break;
case AnimationType.To:
from = defaultOriginValue;
to = _keyValues[0];
validateOrigin = true;
break;
case AnimationType.By:
// According to the SMIL specification, a By animation is
// always additive. But we don't force this so that a
// user can re-use a By animation and have it replace the
// animations that precede it in the list without having
// to manually set the From value to the base value.
to = _keyValues[0];
foundation = defaultOriginValue;
validateOrigin = true;
break;
case AnimationType.FromTo:
from = _keyValues[0];
to = _keyValues[1];
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
case AnimationType.FromBy:
from = _keyValues[0];
to = AnimatedTypeHelpers.AddInt16(_keyValues[0], _keyValues[1]);
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
default:
Debug.Fail("Unknown animation type.");
break;
}
if (validateOrigin
&& !AnimatedTypeHelpers.IsValidAnimationValueInt16(defaultOriginValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"origin",
defaultOriginValue.ToString(CultureInfo.InvariantCulture)));
}
if (validateDestination
&& !AnimatedTypeHelpers.IsValidAnimationValueInt16(defaultDestinationValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"destination",
defaultDestinationValue.ToString(CultureInfo.InvariantCulture)));
}
if (IsCumulative)
{
double currentRepeat = (double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
Int16 accumulator = AnimatedTypeHelpers.SubtractInt16(to, from);
accumulated = AnimatedTypeHelpers.ScaleInt16(accumulator, currentRepeat);
}
}
// return foundation + accumulated + from + ((to - from) * progress)
return AnimatedTypeHelpers.AddInt16(
foundation,
AnimatedTypeHelpers.AddInt16(
accumulated,
AnimatedTypeHelpers.InterpolateInt16(from, to, progress)));
}
private void ValidateAnimationFunction()
{
_animationType = AnimationType.Automatic;
_keyValues = null;
if (From.HasValue)
{
if (To.HasValue)
{
_animationType = AnimationType.FromTo;
_keyValues = new Int16[2];
_keyValues[0] = From.Value;
_keyValues[1] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.FromBy;
_keyValues = new Int16[2];
_keyValues[0] = From.Value;
_keyValues[1] = By.Value;
}
else
{
_animationType = AnimationType.From;
_keyValues = new Int16[1];
_keyValues[0] = From.Value;
}
}
else if (To.HasValue)
{
_animationType = AnimationType.To;
_keyValues = new Int16[1];
_keyValues[0] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.By;
_keyValues = new Int16[1];
_keyValues[0] = By.Value;
}
_isAnimationFunctionValid = true;
}
#endregion
#region Properties
private static void AnimationFunction_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Int16Animation a = (Int16Animation)d;
a._isAnimationFunctionValid = false;
a.PropertyChanged(e.Property);
}
private static bool ValidateFromToOrByValue(object value)
{
Int16? typedValue = (Int16?)value;
if (typedValue.HasValue)
{
return AnimatedTypeHelpers.IsValidAnimationValueInt16(typedValue.Value);
}
else
{
return true;
}
}
/// <summary>
/// FromProperty
/// </summary>
public static readonly DependencyProperty FromProperty;
/// <summary>
/// From
/// </summary>
public Int16? From
{
get
{
return (Int16?)GetValue(FromProperty);
}
set
{
SetValueInternal(FromProperty, value);
}
}
/// <summary>
/// ToProperty
/// </summary>
public static readonly DependencyProperty ToProperty;
/// <summary>
/// To
/// </summary>
public Int16? To
{
get
{
return (Int16?)GetValue(ToProperty);
}
set
{
SetValueInternal(ToProperty, value);
}
}
/// <summary>
/// ByProperty
/// </summary>
public static readonly DependencyProperty ByProperty;
/// <summary>
/// By
/// </summary>
public Int16? By
{
get
{
return (Int16?)GetValue(ByProperty);
}
set
{
SetValueInternal(ByProperty, value);
}
}
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty;
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
/// <summary>
/// If this property is set to true the animation will add its value to
/// the base value instead of replacing it entirely.
/// </summary>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// It this property is set to true, the animation will accumulate its
/// value over repeats. For instance if you have a From value of 0.0 and
/// a To value of 1.0, the animation return values from 1.0 to 2.0 over
/// the second reteat cycle, and 2.0 to 3.0 over the third, etc.
/// </summary>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Settings/Master/IapItemDisplay.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Settings.Master {
/// <summary>Holder for reflection information generated from POGOProtos/Settings/Master/IapItemDisplay.proto</summary>
public static partial class IapItemDisplayReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Settings/Master/IapItemDisplay.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static IapItemDisplayReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ci9QT0dPUHJvdG9zL1NldHRpbmdzL01hc3Rlci9JYXBJdGVtRGlzcGxheS5w",
"cm90bxIaUE9HT1Byb3Rvcy5TZXR0aW5ncy5NYXN0ZXIaJlBPR09Qcm90b3Mv",
"RW51bXMvSWFwSXRlbUNhdGVnb3J5LnByb3RvGiZQT0dPUHJvdG9zL0ludmVu",
"dG9yeS9JdGVtL0l0ZW1JZC5wcm90byKvAQoOSWFwSXRlbURpc3BsYXkSCwoD",
"c2t1GAEgASgJEjcKCGNhdGVnb3J5GAIgASgOMiUuUE9HT1Byb3Rvcy5FbnVt",
"cy5Ib2xvSWFwSXRlbUNhdGVnb3J5EhIKCnNvcnRfb3JkZXIYAyABKAUSMwoI",
"aXRlbV9pZHMYBCADKA4yIS5QT0dPUHJvdG9zLkludmVudG9yeS5JdGVtLkl0",
"ZW1JZBIOCgZjb3VudHMYBSADKAViBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.IapItemCategoryReflection.Descriptor, global::POGOProtos.Inventory.Item.ItemIdReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.IapItemDisplay), global::POGOProtos.Settings.Master.IapItemDisplay.Parser, new[]{ "Sku", "Category", "SortOrder", "ItemIds", "Counts" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class IapItemDisplay : pb::IMessage<IapItemDisplay> {
private static readonly pb::MessageParser<IapItemDisplay> _parser = new pb::MessageParser<IapItemDisplay>(() => new IapItemDisplay());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<IapItemDisplay> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Settings.Master.IapItemDisplayReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public IapItemDisplay() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public IapItemDisplay(IapItemDisplay other) : this() {
sku_ = other.sku_;
category_ = other.category_;
sortOrder_ = other.sortOrder_;
itemIds_ = other.itemIds_.Clone();
counts_ = other.counts_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public IapItemDisplay Clone() {
return new IapItemDisplay(this);
}
/// <summary>Field number for the "sku" field.</summary>
public const int SkuFieldNumber = 1;
private string sku_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Sku {
get { return sku_; }
set {
sku_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "category" field.</summary>
public const int CategoryFieldNumber = 2;
private global::POGOProtos.Enums.HoloIapItemCategory category_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.HoloIapItemCategory Category {
get { return category_; }
set {
category_ = value;
}
}
/// <summary>Field number for the "sort_order" field.</summary>
public const int SortOrderFieldNumber = 3;
private int sortOrder_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int SortOrder {
get { return sortOrder_; }
set {
sortOrder_ = value;
}
}
/// <summary>Field number for the "item_ids" field.</summary>
public const int ItemIdsFieldNumber = 4;
private static readonly pb::FieldCodec<global::POGOProtos.Inventory.Item.ItemId> _repeated_itemIds_codec
= pb::FieldCodec.ForEnum(34, x => (int) x, x => (global::POGOProtos.Inventory.Item.ItemId) x);
private readonly pbc::RepeatedField<global::POGOProtos.Inventory.Item.ItemId> itemIds_ = new pbc::RepeatedField<global::POGOProtos.Inventory.Item.ItemId>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Inventory.Item.ItemId> ItemIds {
get { return itemIds_; }
}
/// <summary>Field number for the "counts" field.</summary>
public const int CountsFieldNumber = 5;
private static readonly pb::FieldCodec<int> _repeated_counts_codec
= pb::FieldCodec.ForInt32(42);
private readonly pbc::RepeatedField<int> counts_ = new pbc::RepeatedField<int>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<int> Counts {
get { return counts_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as IapItemDisplay);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(IapItemDisplay other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Sku != other.Sku) return false;
if (Category != other.Category) return false;
if (SortOrder != other.SortOrder) return false;
if(!itemIds_.Equals(other.itemIds_)) return false;
if(!counts_.Equals(other.counts_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Sku.Length != 0) hash ^= Sku.GetHashCode();
if (Category != 0) hash ^= Category.GetHashCode();
if (SortOrder != 0) hash ^= SortOrder.GetHashCode();
hash ^= itemIds_.GetHashCode();
hash ^= counts_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Sku.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Sku);
}
if (Category != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) Category);
}
if (SortOrder != 0) {
output.WriteRawTag(24);
output.WriteInt32(SortOrder);
}
itemIds_.WriteTo(output, _repeated_itemIds_codec);
counts_.WriteTo(output, _repeated_counts_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Sku.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Sku);
}
if (Category != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Category);
}
if (SortOrder != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(SortOrder);
}
size += itemIds_.CalculateSize(_repeated_itemIds_codec);
size += counts_.CalculateSize(_repeated_counts_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(IapItemDisplay other) {
if (other == null) {
return;
}
if (other.Sku.Length != 0) {
Sku = other.Sku;
}
if (other.Category != 0) {
Category = other.Category;
}
if (other.SortOrder != 0) {
SortOrder = other.SortOrder;
}
itemIds_.Add(other.itemIds_);
counts_.Add(other.counts_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Sku = input.ReadString();
break;
}
case 16: {
category_ = (global::POGOProtos.Enums.HoloIapItemCategory) input.ReadEnum();
break;
}
case 24: {
SortOrder = input.ReadInt32();
break;
}
case 34:
case 32: {
itemIds_.AddEntriesFrom(input, _repeated_itemIds_codec);
break;
}
case 42:
case 40: {
counts_.AddEntriesFrom(input, _repeated_counts_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Collections;
using System.Security.Cryptography.X509Certificates;
namespace Mono.Cecil.CodeDom
{
public static class NodeEx
{
private static void Visit<T>([NotNull] this CodeDomExpression node, [CanBeNull] Action<T> preorderAction, [CanBeNull] Action<T> postorderAction) where T : CodeDomExpression
{
if (node == null)
throw new ArgumentNullException("node");
T obj = node as T;
if (obj != null && preorderAction != null)
preorderAction(obj);
foreach (var subnode in node.Nodes)
subnode.Visit(preorderAction, postorderAction);
if (obj != null && postorderAction != null)
postorderAction(obj);
}
public static void VisitPreorder<T>([NotNull] this CodeDomExpression node, [NotNull] Action<T> action) where T : CodeDomExpression
{
node.Visit(action, null);
}
public static void VisitPostorder<T>([NotNull] this CodeDomExpression node, [NotNull] Action<T> action) where T : CodeDomExpression
{
node.Visit(null, action);
}
public static T FindFirstPostorder<T>([CanBeNull] this CodeDomExpression node, [NotNull] Predicate<T> predicate = null) where T : CodeDomExpression
{
if (predicate == null)
predicate = _ => true;
if (node == null)
return default (T);
foreach (CodeDomExpression subnode in node.Nodes)
{
var firstPostorder = subnode.FindFirstPostorder(predicate);
if (firstPostorder != null)
return firstPostorder;
}
T obj = node as T;
return (obj == null || !predicate(obj)) ? default(T) : obj;
}
public static T FindNearestAncestor<T>([NotNull] this CodeDomExpression searchFrom, [CanBeNull] CodeDomExpression searchUntil = null, [CanBeNull] Predicate<T> predicate = null) where T : CodeDomExpression
{
if (searchFrom == null)
throw new ArgumentNullException("searchFrom");
for (var node = searchFrom; node != null; node = node.ParentNode)
{
var obj = node as T;
if ((object) obj != null && (predicate == null || predicate(obj)))
return obj;
if (node == searchUntil)
break;
}
return default (T);
}
public static CodeDomExpression GetRightSibling([NotNull] this CodeDomExpression node)
{
if (node == null)
throw new ArgumentNullException("node");
return (node.ParentNode != null) ? node.ParentNode.GetRightSibling() : null;
}
public static CodeDomExpression GetLeftSibling([NotNull] this CodeDomExpression node)
{
if (node == null)
throw new ArgumentNullException("node");
if (node.ParentNode != null)
return node.ParentNode.GetLeftSibling();
else
return null;
}
public static CodeDomExpression GetFirstPostorder([NotNull] this CodeDomExpression node)
{
if (node == null)
throw new ArgumentNullException("node");
while (true)
{
var first = node.Nodes.FirstOrDefault();
if (first != null)
node = first;
else
break;
}
return node;
}
public static CodeDomExpression GetNextPostorder([NotNull] this CodeDomExpression node)
{
if (node == null)
throw new ArgumentNullException("node");
var rightSubling = node.GetRightSibling();
if (rightSubling == null)
return node.ParentNode;
while (true)
{
var firstNode = rightSubling.Nodes.FirstOrDefault();
if (firstNode != null)
rightSubling = firstNode;
else
break;
}
return rightSubling;
}
public static T Detach<T>([CanBeNull] this T node) where T : CodeDomExpression
{
if (node == null)
return default (T);
if (!(node.ParentNode is CodeDomGroupExpression))
{
throw new ArgumentException("this.ParentNode should be group to be able to detach childs");
}
if (node.ParentNode != null)
{
var group = (node.ParentNode as CodeDomGroupExpression);
group.RemoveAt(group.IndexOf(node));
}
return node;
}
public static IEnumerable<T> Detach<T>([NotNull] this IEnumerable<T> list) where T : CodeDomExpression
{
if (list == null)
throw new ArgumentNullException("list");
T[] objArray = list.ToArray();
foreach (T node in objArray)
node.Detach();
return objArray;
}
/*
public static bool DeepEquals(this CodeDomExpression thisNode, CodeDomExpression otherNode)
{
if (thisNode == null && otherNode == null)
return true;
if (thisNode == null || otherNode == null)
return false;
else
return thisNode.DeepEqualityComparer.Equals(thisNode, otherNode);
}
public static bool DeepEquals(this INode[] theseNodes, INode[] otherNodes)
{
if (theseNodes == null && otherNodes == null)
return true;
if (theseNodes == null || otherNodes == null || theseNodes.Length != otherNodes.Length)
return false;
for (int index = 0; index < theseNodes.Length; ++index)
{
if (!NodeEx.DeepEquals(theseNodes[index], otherNodes[index]))
return false;
}
return true;
}
*/
/*
public static void ValidateTree(this CodeDomExpression node)
{
NodeEx.ValidateTree(node, null);
}
private static void ValidateTree(CodeDomExpression node, CodeDomExpression parent)
{
foreach (var child in node.Nodes)
NodeEx.ValidateTree(child, node);
}
/*
public static T TypedClone<T>(this T node) where T : class, CodeDomExpression
{
if ((object) node != null)
return (T) node.Clone();
else
return node;
}
public static T[] TypedClone<T>(this T[] nodes) where T : class, INode
{
if (nodes == null)
return (T[]) null;
T[] objArray = new T[nodes.Length];
for (int index = 0; index < nodes.Length; ++index)
objArray[index] = NodeEx.TypedClone<T>(nodes[index]);
return objArray;
}
public static string ToStringDebug(this INode node)
{
if (node == null)
return "<null>";
StringWriter stringWriter = new StringWriter();
CodeTextWriterAdapter codeWriter = new CodeTextWriterAdapter((TextWriter) stringWriter);
TypeSwitchEx.TypeSwitch<INode>(node).Case<IDecompiledMethod>((Action<IDecompiledMethod>) (x => AstRenderer.RenderMethod((ICodeTextWriter) codeWriter, x))).Case<IStatement>((Action<IStatement>) (x => AstRenderer.RenderStatement((ICodeTextWriter) codeWriter, x, false))).Case<IExpression>((Action<IExpression>) (x => JetBrains.Decompiler.Render.CodeTextWriterEx.AppendNewLine(AstRenderer.RenderExpression((ICodeTextWriter) codeWriter, x)))).Case<ControlFlowBlockNode>((Action<ControlFlowBlockNode>) (x =>
{
AstRenderer.RenderStatement((ICodeTextWriter) codeWriter, (IStatement) x.BlockStatement, false);
if (x.BranchExpression == null)
return;
JetBrains.Decompiler.Render.CodeTextWriterEx.AppendNewLine(AstRenderer.RenderExpression(JetBrains.Decompiler.Render.CodeTextWriterEx.AppendText((ICodeTextWriter) codeWriter, "Branch condition: "), x.BranchExpression));
})).EnsureHandled();
return ((object) stringWriter.GetStringBuilder()).ToString().TrimEnd('\n', '\r');
}
*/
public static HashSet<CodeDomExpression> GetSubTreeNodeSet([NotNull] this CodeDomExpression node)
{
if (node == null)
throw new ArgumentNullException("node");
HashSet<CodeDomExpression> subTree = new HashSet<CodeDomExpression>();
node.VisitPostorder<CodeDomExpression>(subNode => subTree.Add(subNode));
return subTree;
}
public static IEnumerable<TResult> SelectNodes<TResult>(this CodeDomExpression node, Predicate<TResult> checker = null)
where TResult : CodeDomExpression
{
var queue = new Queue<CodeDomExpression>();
queue.Enqueue(node);
while(queue.Count > 0)
{
var current = queue.Dequeue();
var ok = checker == null || checker(current as TResult);
if ((current is TResult) && ok)
{
yield return current as TResult;
}
foreach (var item in current.Nodes)
{
queue.Enqueue(item);
}
}
}
public static IEnumerable<TResult> Parents<TResult>(this CodeDomExpression node, Predicate<TResult> checker = null)
where TResult : CodeDomExpression
{
CodeDomExpression parent = node.ParentNode;
while(parent != null)
{
if(checker((TResult)parent))
yield return (TResult)parent;
parent = parent.ParentNode;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using TracerX.Viewer;
using TracerX.Properties;
//he currently visible records (based on filtering and expanded/collapsed methods) will be exported. The currently visible columns will be exported in the order they are displayed.
namespace TracerX.Forms {
// UI and code for exporting the log file to a comma-separated value file.
// Only the currently visible records are exported (i.e. filtering and collapsing matter).
// Only the currently visible columns are exported, in the order they are displayed.
internal partial class ExportCSVForm : Form {
// Call this method to show the form.
public static DialogResult ShowModal() {
ExportCSVForm form = new ExportCSVForm();
return form.ShowDialog();
}
// Ctor is private. Call ShowModal to display this form.
private ExportCSVForm() {
InitializeComponent();
LoadSettings();
this.Icon = Properties.Resources.scroll_view;
}
private void LoadSettings() {
fileBox.Text = Settings.Default.ExportFile;
indentChk.Checked = Settings.Default.ExportIndentation;
headerChk.Checked = Settings.Default.ExportHeader;
separatorChk.Checked = Settings.Default.ExportSeparators;
omitDupTimeChk.Checked = !Settings.Default.ExportDupTimes;
timeAsIntRad.Checked = !Settings.Default.ExportTimeAsText;
timeAsTextRad.Checked = Settings.Default.ExportTimeAsText;
timeWithBlankChk.Checked = Settings.Default.ExportTimeWithBlank;
}
// Browses for output file.
private void browseBtn_Click(object sender, EventArgs e) {
SaveFileDialog dlg = new SaveFileDialog();
dlg.AddExtension = true;
dlg.DefaultExt = ".csv";
dlg.OverwritePrompt = false;
dlg.CheckPathExists = false;
dlg.Filter = "CSV files|*.csv|All files|*.*";
dlg.FilterIndex = 0;
dlg.InitialDirectory = fileBox.Text;
if (DialogResult.OK == dlg.ShowDialog()) {
fileBox.Text = dlg.FileName;
}
}
//// Returns the specified directory if it exists, else checks the parent directories
//// recursively and returns the "lowest" existing directory found. Returns null if none
//// exist or the specified directory has invalid syntax (e.g. an empty string).
//private static string GetLowestExistingDir(string dir) {
// try {
// while (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) {
// dir = Path.GetDirectoryName(dir); // Can return null. Throws exception if format is bad.
// }
// return dir;
// } catch (Exception) {
// // Happens when dir format is invalid.
// return null;
// }
//}
// OK button validates the output file and calls the Export method.
private void okBtn_Click(object sender, EventArgs e) {
Cursor originalCursor = this.Cursor;
this.Cursor = Cursors.WaitCursor;
try {
if (ValidFile()) {
SaveSettings();
Export();
} else {
DialogResult = DialogResult.None;
}
} catch (Exception ex) {
MessageBox.Show(ex.ToString());
DialogResult = DialogResult.None;
} finally {
this.Cursor = originalCursor;
}
}
private void SaveSettings() {
Settings.Default.ExportFile = fileBox.Text;
Settings.Default.ExportIndentation = indentChk.Checked;
Settings.Default.ExportHeader = headerChk.Checked;
Settings.Default.ExportSeparators = separatorChk.Checked;
Settings.Default.ExportDupTimes = !omitDupTimeChk.Checked;
Settings.Default.ExportTimeAsText = timeAsTextRad.Checked;
Settings.Default.ExportTimeWithBlank = timeWithBlankChk.Checked;
}
// Returns true if the output file is valid.
// Asks for permission to replace existing output file.
// Asks for permission to create new directory.
private bool ValidFile() {
bool result = true;
if (fileBox.Text.Trim() == string.Empty) {
MessageBox.Show("A file name is required.");
result = false;
} else if (File.Exists(fileBox.Text)) {
if (DialogResult.Yes != MessageBox.Show("Replace existing file?", "TracerX", MessageBoxButtons.YesNo)) {
result = false;
}
} else if (!Directory.Exists(Path.GetDirectoryName(fileBox.Text))) {
if (DialogResult.Yes == MessageBox.Show("The specified directory does not exist. Create it?", "TracerX", MessageBoxButtons.YesNo)) {
Directory.CreateDirectory(Path.GetDirectoryName(fileBox.Text));
} else {
result = false;
}
}
return result;
}
// Modifies a string for CSV format. Doubles any quotes.
// Adds quotes if leading blanks, trailing blanks, quotes,
// commas, or newlines are found.
private string EscapeForCSV(string str, bool forceQuotes) {
if (str.Contains("\"")) {
forceQuotes = true;
str = str.Replace("\"", "\"\"");
}
if (!forceQuotes) {
if (str.StartsWith(" ") ||
str.EndsWith(" ") ||
str.Contains(",") ||
str.Contains("\n"))//
{
forceQuotes = true;
}
}
if (forceQuotes) str = "\"" + str + "\"";
return str;
}
// Extracts the visible fields/columns from the specified Row and puts them in the
// fields array according to their DisplayIndex. Honors the various checkboxes
// that control indentation, duplicates, etc. Calls EscapeForCSV as needed.
private void SetFields(string[] fields, Row row, Row previousRow, int indentAmount) {
MainForm mainForm = MainForm.TheMainForm;
Record Rec = row.Rec;
Record previousRec = previousRow == null ? null : previousRow.Rec;
string temp;
// If a column has been removed from the ListView,
// its ListView property will be null.
if (mainForm.headerText.ListView != null) {
// Since many values in the Text column will need quotes, force all
// of them to have quotes for consistency.
temp = Rec.GetLine(row.Line, Settings.Default.IndentChar, indentAmount, false);
fields[mainForm.headerText.DisplayIndex] = EscapeForCSV(temp, true);
}
if (mainForm.headerSession.ListView != null) {
if (previousRec != null && previousRec.Session == Rec.Session) {
// Same value as previous record.
// Just leave the previous string value in place.
} else {
// Value is different from previous record.
fields[mainForm.headerSession.DisplayIndex] = Rec.Session.Name;
}
}
if (mainForm.headerLine.ListView != null) {
temp = Rec.GetRecordNum(row.Line, separatorChk.Checked);
if (separatorChk.Checked) temp = EscapeForCSV(temp, false);
fields[mainForm.headerLine.DisplayIndex] = temp;
}
if (mainForm.headerLevel.ListView != null) {
if (previousRec != null && previousRec.Level == Rec.Level) {
// Same value as previous record.
// Just leave the previous string value in place.
} else {
// Value is different from previous record.
fields[mainForm.headerLevel.DisplayIndex] = Enum.GetName(typeof(TraceLevel), Rec.Level);
}
}
if (mainForm.headerLogger.ListView != null) {
if (previousRec != null && previousRec.Logger == Rec.Logger) {
// Same value as previous record.
// Just leave the previous string value in place.
} else {
// Value is different from previous record.
fields[mainForm.headerLogger.DisplayIndex] = EscapeForCSV(Rec.Logger.Name, false);
}
}
if (mainForm.headerThreadId.ListView != null) {
if (previousRec != null && previousRec.ThreadId == Rec.ThreadId) {
// Same value as previous record.
// Just leave the previous string value in place.
} else {
// Value is different from previous record.
fields[mainForm.headerThreadId.DisplayIndex] = Rec.ThreadId.ToString();
}
}
if (mainForm.headerThreadName.ListView != null) {
if (previousRec != null && previousRec.ThreadName == Rec.ThreadName) {
// Same value as previous record.
// Just leave the previous string value in place.
} else {
// Value is different from previous record.
fields[mainForm.headerThreadName.DisplayIndex] = EscapeForCSV(Rec.ThreadName.Name, false);
}
}
if (mainForm.headerMethod.ListView != null) {
if (previousRec != null && previousRec.MethodName == Rec.MethodName) {
// Same value as previous record.
// Just leave the previous string value in place.
} else {
// Value is different from previous record.
fields[mainForm.headerMethod.DisplayIndex] = EscapeForCSV(Rec.MethodName.Name, false);
}
}
if (mainForm.headerTime.ListView != null) {
if (previousRec != null && previousRec.Time == Rec.Time) {
// Same value as previous record.
if (omitDupTimeChk.Checked) {
fields[mainForm.headerTime.DisplayIndex] = string.Empty;
} else {
// Just leave the previous string value in place.
}
} else {
// Value is different from previous record.
if (timeAsTextRad.Checked) {
if (timeWithBlankChk.Checked) {
// Include a leading blank so Excel treats it as text.
if (Settings.Default.RelativeTime) {
fields[mainForm.headerTime.DisplayIndex] = string.Format("\" {0}\"", Program.FormatTimeSpan(Rec.Time - MainForm.ZeroTime));
} else {
fields[mainForm.headerTime.DisplayIndex] = string.Format("\" {0}\"", Rec.Time.ToLocalTime().ToString(@"MM/dd/yy HH:mm:ss.fff"));
}
} else {
if (Settings.Default.RelativeTime) {
fields[mainForm.headerTime.DisplayIndex] = Program.FormatTimeSpan(Rec.Time - MainForm.ZeroTime);
} else {
fields[mainForm.headerTime.DisplayIndex] = Rec.Time.ToLocalTime().ToString(@"MM/dd/yy HH:mm:ss.fff");
}
}
} else if (timeAsIntRad.Checked) {
fields[mainForm.headerTime.DisplayIndex] = Rec.Time.Ticks.ToString();
}
}
}
}
// Opens the output file, writes the output, closes the file.
private void Export() {
string[] fields = new string[MainForm.TheMainForm.TheListView.Columns.Count];
int indentAmount = Settings.Default.IndentAmount;
Row previousRow = null;
if (!indentChk.Checked) indentAmount = 0;
using (StreamWriter writer = File.CreateText(fileBox.Text)) {
if (headerChk.Checked) {
foreach (ColumnHeader col in MainForm.TheMainForm.TheListView.Columns) {
fields[col.DisplayIndex] = col.Text;
}
writer.WriteLine(string.Join(",", fields));
}
for (int i = 0; i < MainForm.TheMainForm.NumRows; ++i) {
Row row = MainForm.TheMainForm.Rows[i];
SetFields(fields, row, previousRow, indentAmount);
writer.WriteLine(string.Join(",", fields));
previousRow = row;
}
}
}
private void timeAsIntRad_CheckedChanged(object sender, EventArgs e) {
timeWithBlankChk.Enabled = timeAsTextRad.Checked;
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A crematorium.
/// </summary>
public class Crematorium_Core : TypeCore, ICivicStructure
{
public Crematorium_Core()
{
this._TypeId = 79;
this._Id = "Crematorium";
this._Schema_Org_Url = "http://schema.org/Crematorium";
string label = "";
GetLabel(out label, "Crematorium", typeof(Crematorium_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,62};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{62};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Locks.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Azure.Management.Locks.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System.Text;
using System;
using System.Linq;
using Microsoft.Rest.Azure;
/// <summary>
/// Implementation for ManagementLocks.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmxvY2tzLmltcGxlbWVudGF0aW9uLk1hbmFnZW1lbnRMb2Nrc0ltcGw=
internal partial class ManagementLocksImpl :
CreatableResources<IManagementLock, ManagementLockImpl, Models.ManagementLockObjectInner>,
IManagementLocks
{
private IAuthorizationManager manager;
///GENMHASH:836797384EAD11F4F592C5C904884C2A:D544D70B59C64F2C67EC02DE16CBAEF6
internal ManagementLocksImpl(IAuthorizationManager manager)
{
this.manager = manager;
}
IManagementLocksOperations IHasInner<IManagementLocksOperations>.Inner
{
get
{
return Inner();
}
}
///GENMHASH:B6961E0C7CB3A9659DE0E1489F44A936:168EFDB95EECDB98D4BDFCCA32101AC1
public IAuthorizationManager Manager()
{
return manager;
}
#region Get
///GENMHASH:7D93B4EC99C64989F97B3D17F88C3F2C:45E96D80A053DE48AD3DD26FC5CD83FF
public IManagementLock GetByResourceGroup(string resourceGroupName, string name)
{
return Extensions.Synchronize(() => GetByResourceGroupAsync(resourceGroupName, name));
}
///GENMHASH:5002116800CBAC02BBC1B4BF62BC4942:E5DB8B81D366BCF6A1B75F4B1D85B1F1
public IManagementLock GetById(string id)
{
return Extensions.Synchronize(() => GetByIdAsync(id));
}
///GENMHASH:E776888E46F8A3FC56D24DF4A74E5B74:FC67528805BD588653B69DE503549F4C
public async Task<IManagementLock> GetByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
{
string resourceId = ResourceIdFromLockId(id);
string lockName = ResourceUtils.NameFromResourceId(id);
IManagementLock l = null;
if (resourceId != null && lockName != null)
{
l = WrapModel(await Inner().GetByScopeAsync(resourceId, lockName, cancellationToken));
}
return l;
}
///GENMHASH:2B19D171A02814189E0329A91320316B:E509DF22AA2F28442E1D34ACD9FCD647
public async Task<IManagementLock> GetByResourceGroupAsync(string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
return WrapModel(await Inner().GetAtResourceGroupLevelAsync(resourceGroupName, name, cancellationToken));
}
#endregion
#region Delete
public override void DeleteById(string id)
{
Extensions.Synchronize(() => DeleteByIdAsync(id));
}
///GENMHASH:4D33A73A344E127F784620E76B686786:DF0ACE79B69D4230630060F3C796E8A9
public async override Task DeleteByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
{
string scope = ResourceIdFromLockId(id);
string lockName = ResourceUtils.NameFromResourceId(id);
if (scope != null && lockName != null)
{
await Inner().DeleteByScopeAsync(scope, lockName, cancellationToken);
}
}
///GENMHASH:782853D3A86D961975AF25BD353144CE:F42FD335BA3F56DE82610403C83DB1CD
public async Task<IEnumerable<string>> DeleteByIdsAsync(IList<string> ids, CancellationToken cancellationToken = default(CancellationToken))
{
if (ids == null || ids.Count == 0)
{
return new List<string>();
}
IEnumerable<Task<string>> tasks = new List<Task<string>>();
List<string> ids1 = new List<string>();
var tts = new List<Task>();
foreach (var id in ids)
{
string lockName = ResourceUtils.NameFromResourceId(id);
string scopeName = ResourceIdFromLockId(id);
if (lockName != null && scopeName != null)
{
tts.Add(Task.Run(async () =>
{
try
{
await Inner().DeleteByScopeAsync(scopeName, lockName, cancellationToken);
}
catch(CloudException)
{
}
ids1.Add(id);
}));
}
}
await Task.WhenAll(tts);
return ids1;
}
///GENMHASH:6761F083A3838E34703AD0305B873679:E05AE73A1CA90E964ED86C07093D463F
public async Task<IEnumerable<string>> DeleteByIdsAsync(string[] ids, CancellationToken cancellationToken = default(CancellationToken))
{
return await DeleteByIdsAsync(new List<string>(ids), cancellationToken);
}
///GENMHASH:8B5750E68FCC626D3009EA1EAACB3C16:8E4631EFC6068BB521E67D3178D6E7B8
public void DeleteByIds(IList<string> ids)
{
Extensions.Synchronize(() => DeleteByIdsAsync(ids));
}
///GENMHASH:F65FF3868FDEB2B4896429AE1A0F14F4:8E4631EFC6068BB521E67D3178D6E7B8
public void DeleteByIds(params string[] ids)
{
Extensions.Synchronize(() => DeleteByIdsAsync(ids));
}
///GENMHASH:DE94604AE39A5722E2DA0AC4017FC2B9:EAFF99EE2BE784A51EF82B7277636D2B
public void DeleteByResourceGroup(string resourceGroupName, string name)
{
Extensions.Synchronize(() => DeleteByResourceGroupAsync(resourceGroupName, name));
}
///GENMHASH:9D38835F71DF2C39BF88CBB588420D30:FD7FA95DB661326602615F08FEA599EC
public async Task DeleteByResourceGroupAsync(string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await Inner().DeleteAtResourceGroupLevelAsync(resourceGroupName, name, cancellationToken);
}
#endregion
#region List
///GENMHASH:7D6013E8B95E991005ED921F493EFCE4:EFF74B68F06CBC4611C3EEE115E1A032
public IEnumerable<IManagementLock> List()
{
return WrapList(Extensions.Synchronize(() => Inner().ListAtSubscriptionLevelAsync()));
}
///GENMHASH:7F5BEBF638B801886F5E13E6CCFF6A4E:0984AC2110E1EAA73B752279C293E987
public async Task<IPagedCollection<IManagementLock>> ListAsync(bool loadAllPages = true, CancellationToken cancellationToken = default(CancellationToken))
{
return await PagedCollection<IManagementLock, ManagementLockObjectInner>.LoadPage(
async (cancellation) => await Inner().ListAtSubscriptionLevelAsync(null, cancellationToken),
Inner().ListAtSubscriptionLevelNextAsync,
WrapModel,
loadAllPages,
cancellationToken);
}
///GENMHASH:9C5B42FF47E71D8582BAB26BBDEC1E0B:6A20423BC9EF8328BE93DB0B8D897A58
public async Task<IPagedCollection<IManagementLock>> ListByResourceGroupAsync(string resourceGroupName, bool loadAllPages = true, CancellationToken cancellationToken = default(CancellationToken))
{
return await PagedCollection<IManagementLock, ManagementLockObjectInner>.LoadPage(
async (cancellation) => await Inner().ListAtResourceGroupLevelAsync(resourceGroupName, null, cancellationToken),
Inner().ListAtResourceLevelNextAsync,
WrapModel,
loadAllPages,
cancellationToken);
}
///GENMHASH:B41D0AFC2CE2E06B4071C02D9A475F18:3920DBCA07E0C928C7377009441C02F1
public IEnumerable<IManagementLock> ListForResource(string resourceId)
{
var inners = Extensions.Synchronize(() => Inner().ListAtResourceLevelAsync(
ResourceUtils.GroupFromResourceId(resourceId),
ResourceUtils.ResourceProviderFromResourceId(resourceId),
ResourceUtils.ParentRelativePathFromResourceId(resourceId),
ResourceUtils.ResourceTypeFromResourceId(resourceId),
ResourceUtils.NameFromResourceId(resourceId)));
return WrapList(inners);
}
///GENMHASH:75FEDF335D513029A4BA866C3E6BE131:B6A4EBD0DC3C36F9588173D7B2A63BA9
public async Task<IPagedCollection<IManagementLock>> ListForResourceAsync(string resourceId, CancellationToken cancellationToken = default(CancellationToken))
{
return await PagedCollection<IManagementLock, ManagementLockObjectInner>.LoadPage(
async (cancellation) => await Inner().ListAtResourceLevelAsync(
ResourceUtils.GroupFromResourceId(resourceId),
ResourceUtils.ResourceProviderFromResourceId(resourceId),
ResourceUtils.ParentRelativePathFromResourceId(resourceId),
ResourceUtils.ResourceTypeFromResourceId(resourceId),
ResourceUtils.NameFromResourceId(resourceId),
null,
cancellationToken),
Inner().ListAtResourceLevelNextAsync,
WrapModel,
false,
cancellationToken);
}
///GENMHASH:178BF162835B0E3978203EDEF988B6EB:2AF1AED874591A3A597F23BBE3B7C5CD
public IEnumerable<IManagementLock> ListByResourceGroup(string resourceGroupName)
{
return WrapList(Extensions.Synchronize(() => Inner().ListAtResourceGroupLevelAsync(resourceGroupName)));
}
#endregion
///GENMHASH:CDBF9872F7A9C39DD4A1208B299D0D3E:133DC84E85B4401A0AB6374FF91C26A8
internal static string[] LockIdParts(string lockId)
{
if (lockId == null)
{
return null;
}
// Format examples:
// /subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/resourceGroups/anu-abc/providers/Microsoft.Authorization/locks/lock-1
// /subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/resourceGroups/anu-abc/providers/Microsoft.Storage/storageAccounts/anustg234/providers/Microsoft.Authorization/locks/lock-2
var parts = lockId.Split('/');
if (parts.Length < 4)
{
// ID too short to be possibly a lock ID
return null;
}
else if (!parts[parts.Length - 2].Equals("locks", StringComparison.OrdinalIgnoreCase)
|| !parts[parts.Length - 3].Equals("Microsoft.Authorization", StringComparison.OrdinalIgnoreCase)
|| !parts[parts.Length - 4].Equals("providers", StringComparison.OrdinalIgnoreCase))
{
// Not a lock ID
return null;
}
else
{
return parts;
}
}
/// <summary>
/// Returns the part of the specified management lock resource ID representing the resource the lock is associated with.
/// </summary>
/// <param name="lockId">A lock resource ID.</param>
/// <return>A resource ID.</return>
///GENMHASH:22CE38B390E4B2A046F6AA5EE62DD739:5AC7B757940FA1BFC39F298158A50C9B
public static string ResourceIdFromLockId(string lockId)
{
var lockIdParts = LockIdParts(lockId);
if (lockIdParts == null)
{
return null;
}
StringBuilder resourceId = new StringBuilder();
for (int i = 0; i < lockIdParts.Length - 4; i++)
{
if (lockIdParts[i] != string.Empty) {
resourceId.Append("/").Append(lockIdParts[i]);
}
}
return resourceId.ToString();
}
///GENMHASH:C852FF1A7022E39B3C33C4B996B5E6D6:1623EDA2C355562842B44FD2E687707B
public IManagementLocksOperations Inner()
{
return manager.Inner.ManagementLocks;
}
///GENMHASH:8ACFB0E23F5F24AD384313679B65F404:AD7C28D26EC1F237B93E54AD31899691
public ManagementLockImpl Define(string name)
{
return WrapModel(name);
}
///GENMHASH:2FE8C4C2D5EAD7E37787838DE0B47D92:56A9C5490F20084DBFD636B932B7F06B
protected override ManagementLockImpl WrapModel(string name)
{
return new ManagementLockImpl(name, new ManagementLockObjectInner(), Manager());
}
///GENMHASH:A461D6864EB7CB1DB406AFD2F9FFEF86:475DF4B0DBDD12D825C5DB54678ADA4A
protected override IManagementLock WrapModel(ManagementLockObjectInner inner)
{
return (inner != null) ? new ManagementLockImpl(inner.Id, inner, Manager()) : null;
}
}
}
| |
//
// System.Net.ChunkStream
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2003 Ximian, Inc (http://www.ximian.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Net;
using System;
namespace HTTP.Net
{
internal class ChunkStream
{
enum State {
None,
Body,
BodyFinished,
Trailer
}
class Chunk {
public byte [] Bytes;
public int Offset;
public Chunk (byte [] chunk)
{
this.Bytes = chunk;
}
public int Read (byte [] buffer, int offset, int size)
{
int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
Buffer.BlockCopy (Bytes, Offset, buffer, offset, nread);
Offset += nread;
return nread;
}
}
internal WebHeaderCollection headers;
int chunkSize;
int chunkRead;
State state;
//byte [] waitBuffer;
StringBuilder saved;
bool sawCR;
bool gotit;
int trailerState;
ArrayList chunks;
public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers)
: this (headers)
{
Write (buffer, offset, size);
}
public ChunkStream (WebHeaderCollection headers)
{
this.headers = headers;
saved = new StringBuilder ();
chunks = new ArrayList ();
chunkSize = -1;
}
public void ResetBuffer ()
{
chunkSize = -1;
chunkRead = 0;
chunks.Clear ();
}
public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read)
{
if (offset + read > 0)
Write (buffer, offset, offset+read);
read = Read (buffer, offset, size);
}
public int Read (byte [] buffer, int offset, int size)
{
return ReadFromChunks (buffer, offset, size);
}
int ReadFromChunks (byte [] buffer, int offset, int size)
{
int count = chunks.Count;
int nread = 0;
for (int i = 0; i < count; i++) {
Chunk chunk = (Chunk) chunks [i];
if (chunk == null)
continue;
if (chunk.Offset == chunk.Bytes.Length) {
chunks [i] = null;
continue;
}
nread += chunk.Read (buffer, offset + nread, size - nread);
if (nread == size)
break;
}
return nread;
}
public void Write (byte [] buffer, int offset, int size)
{
InternalWrite (buffer, ref offset, size);
}
void InternalWrite (byte [] buffer, ref int offset, int size)
{
if (state == State.None) {
state = GetChunkSize (buffer, ref offset, size);
if (state == State.None)
return;
saved.Length = 0;
sawCR = false;
gotit = false;
}
if (state == State.Body && offset < size) {
state = ReadBody (buffer, ref offset, size);
if (state == State.Body)
return;
}
if (state == State.BodyFinished && offset < size) {
state = ReadCRLF (buffer, ref offset, size);
if (state == State.BodyFinished)
return;
sawCR = false;
}
if (state == State.Trailer && offset < size) {
state = ReadTrailer (buffer, ref offset, size);
if (state == State.Trailer)
return;
saved.Length = 0;
sawCR = false;
gotit = false;
}
if (offset < size)
InternalWrite (buffer, ref offset, size);
}
public bool WantMore {
get { return (chunkRead != chunkSize || chunkSize != 0 || state != State.None); }
}
public int ChunkLeft {
get { return chunkSize - chunkRead; }
}
State ReadBody (byte [] buffer, ref int offset, int size)
{
if (chunkSize == 0)
return State.BodyFinished;
int diff = size - offset;
if (diff + chunkRead > chunkSize)
diff = chunkSize - chunkRead;
byte [] chunk = new byte [diff];
Buffer.BlockCopy (buffer, offset, chunk, 0, diff);
chunks.Add (new Chunk (chunk));
offset += diff;
chunkRead += diff;
return (chunkRead == chunkSize) ? State.BodyFinished : State.Body;
}
State GetChunkSize (byte [] buffer, ref int offset, int size)
{
char c = '\0';
while (offset < size) {
c = (char) buffer [offset++];
if (c == '\r') {
if (sawCR)
ThrowProtocolViolation ("2 CR found");
sawCR = true;
continue;
}
if (sawCR && c == '\n')
break;
if (c == ' ')
gotit = true;
if (!gotit)
saved.Append (c);
if (saved.Length > 20)
ThrowProtocolViolation ("chunk size too long.");
}
if (!sawCR || c != '\n') {
if (offset < size)
ThrowProtocolViolation ("Missing \\n");
try {
if (saved.Length > 0) {
chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
}
} catch (Exception) {
ThrowProtocolViolation ("Cannot parse chunk size.");
}
return State.None;
}
chunkRead = 0;
try {
chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
} catch (Exception) {
ThrowProtocolViolation ("Cannot parse chunk size.");
}
if (chunkSize == 0) {
trailerState = 2;
return State.Trailer;
}
return State.Body;
}
static string RemoveChunkExtension (string input)
{
int idx = input.IndexOf (';');
if (idx == -1)
return input;
return input.Substring (0, idx);
}
State ReadCRLF (byte [] buffer, ref int offset, int size)
{
if (!sawCR) {
if ((char) buffer [offset++] != '\r')
ThrowProtocolViolation ("Expecting \\r");
sawCR = true;
if (offset == size)
return State.BodyFinished;
}
if (sawCR && (char) buffer [offset++] != '\n')
ThrowProtocolViolation ("Expecting \\n");
return State.None;
}
State ReadTrailer (byte [] buffer, ref int offset, int size)
{
char c = '\0';
// short path
if (trailerState == 2 && (char) buffer [offset] == '\r' && saved.Length == 0) {
offset++;
if (offset < size && (char) buffer [offset] == '\n') {
offset++;
return State.None;
}
offset--;
}
int st = trailerState;
string stString = "\r\n\r";
while (offset < size && st < 4) {
c = (char) buffer [offset++];
if ((st == 0 || st == 2) && c == '\r') {
st++;
continue;
}
if ((st == 1 || st == 3) && c == '\n') {
st++;
continue;
}
if (st > 0) {
saved.Append (stString.Substring (0, saved.Length == 0? st-2: st));
st = 0;
if (saved.Length > 4196)
ThrowProtocolViolation ("Error reading trailer (too long).");
}
}
if (st < 4) {
trailerState = st;
if (offset < size)
ThrowProtocolViolation ("Error reading trailer.");
return State.Trailer;
}
StringReader reader = new StringReader (saved.ToString ());
string line;
while ((line = reader.ReadLine ()) != null && line != "")
headers.Add (line);
return State.None;
}
static void ThrowProtocolViolation (string message)
{
WebException we = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);
throw we;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Collections.Generic;
namespace System.Windows.Input
{
internal static class StylusPointPropertyInfoDefaults
{
/// <summary>
/// X
/// </summary>
internal static readonly StylusPointPropertyInfo X =
new StylusPointPropertyInfo(StylusPointProperties.X,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.Centimeters,
1000.0f);
/// <summary>
/// Y
/// </summary>
internal static readonly StylusPointPropertyInfo Y =
new StylusPointPropertyInfo(StylusPointProperties.Y,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.Centimeters,
1000.0f);
/// <summary>
/// Z
/// </summary>
internal static readonly StylusPointPropertyInfo Z =
new StylusPointPropertyInfo(StylusPointProperties.Z,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.Centimeters,
1000.0f);
/// <summary>
/// Width
/// </summary>
internal static readonly StylusPointPropertyInfo Width =
new StylusPointPropertyInfo(StylusPointProperties.Width,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.Centimeters,
1000.0f);
/// <summary>
/// Height
/// </summary>
internal static readonly StylusPointPropertyInfo Height =
new StylusPointPropertyInfo(StylusPointProperties.Height,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.Centimeters,
1000.0f);
/// <summary>
/// SystemTouch
/// </summary>
internal static readonly StylusPointPropertyInfo SystemTouch =
new StylusPointPropertyInfo(StylusPointProperties.SystemTouch,
0,
1,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// PacketStatus
internal static readonly StylusPointPropertyInfo PacketStatus =
new StylusPointPropertyInfo(StylusPointProperties.PacketStatus,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// SerialNumber
internal static readonly StylusPointPropertyInfo SerialNumber =
new StylusPointPropertyInfo(StylusPointProperties.SerialNumber,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// NormalPressure
/// </summary>
internal static readonly StylusPointPropertyInfo NormalPressure =
new StylusPointPropertyInfo(StylusPointProperties.NormalPressure,
0,
1023,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// TangentPressure
/// </summary>
internal static readonly StylusPointPropertyInfo TangentPressure =
new StylusPointPropertyInfo(StylusPointProperties.TangentPressure,
0,
1023,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// ButtonPressure
/// </summary>
internal static readonly StylusPointPropertyInfo ButtonPressure =
new StylusPointPropertyInfo(StylusPointProperties.ButtonPressure,
0,
1023,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// XTiltOrientation
/// </summary>
internal static readonly StylusPointPropertyInfo XTiltOrientation =
new StylusPointPropertyInfo(StylusPointProperties.XTiltOrientation,
0,
3600,
StylusPointPropertyUnit.Degrees,
10.0f);
/// <summary>
/// YTiltOrientation
/// </summary>
internal static readonly StylusPointPropertyInfo YTiltOrientation =
new StylusPointPropertyInfo(StylusPointProperties.YTiltOrientation,
0,
3600,
StylusPointPropertyUnit.Degrees,
10.0f);
/// <summary>
/// AzimuthOrientation
/// </summary>
internal static readonly StylusPointPropertyInfo AzimuthOrientation =
new StylusPointPropertyInfo(StylusPointProperties.AzimuthOrientation,
0,
3600,
StylusPointPropertyUnit.Degrees,
10.0f);
/// <summary>
/// AltitudeOrientation
/// </summary>
internal static readonly StylusPointPropertyInfo AltitudeOrientation =
new StylusPointPropertyInfo(StylusPointProperties.AltitudeOrientation,
-900,
900,
StylusPointPropertyUnit.Degrees,
10.0f);
/// <summary>
/// TwistOrientation
/// </summary>
internal static readonly StylusPointPropertyInfo TwistOrientation =
new StylusPointPropertyInfo(StylusPointProperties.TwistOrientation,
0,
3600,
StylusPointPropertyUnit.Degrees,
10.0f);
/// <summary>
/// PitchRotation
internal static readonly StylusPointPropertyInfo PitchRotation =
new StylusPointPropertyInfo(StylusPointProperties.PitchRotation,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// RollRotation
internal static readonly StylusPointPropertyInfo RollRotation =
new StylusPointPropertyInfo(StylusPointProperties.RollRotation,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// YawRotation
internal static readonly StylusPointPropertyInfo YawRotation =
new StylusPointPropertyInfo(StylusPointProperties.YawRotation,
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// TipButton
internal static readonly StylusPointPropertyInfo TipButton =
new StylusPointPropertyInfo(StylusPointProperties.TipButton,
0,
1,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// BarrelButton
internal static readonly StylusPointPropertyInfo BarrelButton =
new StylusPointPropertyInfo(StylusPointProperties.BarrelButton,
0,
1,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// SecondaryTipButton
internal static readonly StylusPointPropertyInfo SecondaryTipButton =
new StylusPointPropertyInfo(StylusPointProperties.SecondaryTipButton,
0,
1,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// Default Value
/// </summary>
internal static readonly StylusPointPropertyInfo DefaultValue =
new StylusPointPropertyInfo(new StylusPointProperty(Guid.NewGuid(), false),
Int32.MinValue,
Int32.MaxValue,
StylusPointPropertyUnit.None,
1.0F);
/// <summary>
/// DefaultButton
internal static readonly StylusPointPropertyInfo DefaultButton =
new StylusPointPropertyInfo(new StylusPointProperty(Guid.NewGuid(), true),
0,
1,
StylusPointPropertyUnit.None,
1.0f);
/// <summary>
/// For a given StylusPointProperty, return the default property info
/// </summary>
/// <param name="stylusPointProperty">stylusPointProperty</param>
/// <returns></returns>
internal static StylusPointPropertyInfo GetStylusPointPropertyInfoDefault(StylusPointProperty stylusPointProperty)
{
if (stylusPointProperty.Id == StylusPointPropertyIds.X)
{
return StylusPointPropertyInfoDefaults.X;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.Y)
{
return StylusPointPropertyInfoDefaults.Y;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.Z)
{
return StylusPointPropertyInfoDefaults.Z;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.Width)
{
return StylusPointPropertyInfoDefaults.Width;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.Height)
{
return StylusPointPropertyInfoDefaults.Height;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.SystemTouch)
{
return StylusPointPropertyInfoDefaults.SystemTouch;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.PacketStatus)
{
return StylusPointPropertyInfoDefaults.PacketStatus;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.SerialNumber)
{
return StylusPointPropertyInfoDefaults.SerialNumber;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.NormalPressure)
{
return StylusPointPropertyInfoDefaults.NormalPressure;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.TangentPressure)
{
return StylusPointPropertyInfoDefaults.TangentPressure;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.ButtonPressure)
{
return StylusPointPropertyInfoDefaults.ButtonPressure;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.XTiltOrientation)
{
return StylusPointPropertyInfoDefaults.XTiltOrientation;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.YTiltOrientation)
{
return StylusPointPropertyInfoDefaults.YTiltOrientation;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.AzimuthOrientation)
{
return StylusPointPropertyInfoDefaults.AzimuthOrientation;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.AltitudeOrientation)
{
return StylusPointPropertyInfoDefaults.AltitudeOrientation;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.TwistOrientation)
{
return StylusPointPropertyInfoDefaults.TwistOrientation;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.PitchRotation)
{
return StylusPointPropertyInfoDefaults.PitchRotation;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.RollRotation)
{
return StylusPointPropertyInfoDefaults.RollRotation;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.YawRotation)
{
return StylusPointPropertyInfoDefaults.YawRotation;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.TipButton)
{
return StylusPointPropertyInfoDefaults.TipButton;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.BarrelButton)
{
return StylusPointPropertyInfoDefaults.BarrelButton;
}
if (stylusPointProperty.Id == StylusPointPropertyIds.SecondaryTipButton)
{
return StylusPointPropertyInfoDefaults.SecondaryTipButton;
}
//
// return a default
//
if (stylusPointProperty.IsButton)
{
return StylusPointPropertyInfoDefaults.DefaultButton;
}
return StylusPointPropertyInfoDefaults.DefaultValue;
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B09_CityColl (editable child list).<br/>
/// This is a generated base class of <see cref="B09_CityColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="B08_Region"/> editable child object.<br/>
/// The items of the collection are <see cref="B10_City"/> objects.
/// </remarks>
[Serializable]
public partial class B09_CityColl : BusinessListBase<B09_CityColl, B10_City>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="B10_City"/> item from the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to be removed.</param>
public void Remove(int city_ID)
{
foreach (var b10_City in this)
{
if (b10_City.City_ID == city_ID)
{
Remove(b10_City);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="B10_City"/> item is in the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the B10_City is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int city_ID)
{
foreach (var b10_City in this)
{
if (b10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="B10_City"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the B10_City is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int city_ID)
{
foreach (var b10_City in DeletedList)
{
if (b10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="B10_City"/> item of the <see cref="B09_CityColl"/> collection, based on item key properties.
/// </summary>
/// <param name="city_ID">The City_ID.</param>
/// <returns>A <see cref="B10_City"/> object.</returns>
public B10_City FindB10_CityByParentProperties(int city_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].City_ID.Equals(city_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B09_CityColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="B09_CityColl"/> collection.</returns>
internal static B09_CityColl NewB09_CityColl()
{
return DataPortal.CreateChild<B09_CityColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="B09_CityColl"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B09_CityColl"/> object.</returns>
internal static B09_CityColl GetB09_CityColl(SafeDataReader dr)
{
B09_CityColl obj = new B09_CityColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B09_CityColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B09_CityColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="B09_CityColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(dr);
OnFetchPre(args);
while (dr.Read())
{
Add(B10_City.GetB10_City(dr));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="B10_City"/> items on the B09_CityObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="B07_RegionColl"/> collection.</param>
internal void LoadItems(B07_RegionColl collection)
{
foreach (var item in this)
{
var obj = collection.FindB08_RegionByParentProperties(item.parent_Region_ID);
var rlce = obj.B09_CityObjects.RaiseListChangedEvents;
obj.B09_CityObjects.RaiseListChangedEvents = false;
obj.B09_CityObjects.Add(item);
obj.B09_CityObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright (c) 2017 Jan Pluskal, Miroslav Slivka, Viliam Letavay
//
//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.IO;
using System.Text;
using Castle.Windsor;
using Netfox.Core.Models.Exports;
using Netfox.Framework.Models;
using Netfox.Framework.Models.Interfaces;
using Netfox.Framework.Models.Snoopers;
namespace Netfox.Framework.ApplicationProtocolExport.Snoopers
{
public abstract class SnooperBase : ISnooper
{
/// <summary>
/// todo this should be DB collection
/// </summary>
private readonly List<SnooperExportBase> _snooperExportsList = new List<SnooperExportBase>();
protected Boolean ForceExportOnAllConversations;
protected SelectedConversations SelectedConversations;
protected IEnumerable<SnooperExportBase> SourceExports;
private DirectoryInfo _exportBaseDirectory;
/// <summary>
/// Parameterless constructor has to be always present in derived classes
/// </summary>
protected SnooperBase()
{
this.IsPrototype = true;
}
protected SnooperBase(
WindsorContainer investigationWindsorContainer,
SelectedConversations conversations,
DirectoryInfo exportDirectory,
Boolean ignoreApplicationTags)
{
this.InvestigationWindsorContainer = investigationWindsorContainer;
this.ExportBaseDirectory = new DirectoryInfo(Path.Combine(exportDirectory.FullName, this.Name));
//this.CreateExportDirectory();
this.SelectedConversations = conversations;
this.ForceExportOnAllConversations = ignoreApplicationTags;
}
protected SnooperBase(
WindsorContainer investigationWindsorContainer,
IEnumerable<SnooperExportBase> sourceExports,
DirectoryInfo exportDirectory)
{
this.InvestigationWindsorContainer = investigationWindsorContainer;
this.ExportBaseDirectory = new DirectoryInfo(Path.Combine(exportDirectory.FullName, this.Name));
//this.CreateExportDirectory();
this.SourceExports = sourceExports;
}
protected SnooperBase(WindsorContainer investigationWindsorContainer, IEnumerable<FileInfo> sourceFiles, DirectoryInfo exportDirectory)
{
this.InvestigationWindsorContainer = investigationWindsorContainer;
this.ExportBaseDirectory = new DirectoryInfo(Path.Combine(exportDirectory.FullName, this.Name));
//this.CreateExportDirectory();
this.SourceFiles = sourceFiles;
}
public WindsorContainer InvestigationWindsorContainer { get; }
public IEnumerable<FileInfo> SourceFiles { get; set; }
protected internal L7Conversation CurrentConversation { get; set; }
protected internal DirectoryInfo ExportBaseDirectory
{
get { return this._exportBaseDirectory; }
private set
{
this._exportBaseDirectory = value;
this.CreateExportDirectory();
}
}
protected SnooperExportBase SnooperExport { get; set; }
private Boolean IsPrototype { get; }
public abstract String Description { get; }
public abstract Int32[] KnownApplicationPorts { get; }
//private string _exportDirectory;
public abstract String Name { get; }
public abstract String[] ProtocolNBARName { get; }
public abstract SnooperExportBase PrototypExportObject { get; }
public void Run()
{
if(this.IsPrototype)
{
Console.WriteLine("Prototype of snooper cannot be used to export data!");
return;
}
// create export directory if it doesn't exist
if(!this.ExportBaseDirectory.Exists) { this.ExportBaseDirectory.Create(); }
try {
this.RunBody();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
this.SnooperExport.AddExportReport(ExportReport.ReportLevel.Error, this.Name, "unexpected exception caught",new []{this.CurrentConversation}, ex);
this.FinalizeExports();
}
this.SnooperExport?.CheckExportState();
}
public override String ToString()
{
var sb = new StringBuilder();
sb.AppendLine("Export:");
sb.AppendLine(this.SnooperExport.ToString());
return sb.ToString();
}
protected void CreateExportDirectory()
{
if(!this.ExportBaseDirectory.Exists)
{
Console.WriteLine("creating " + this.ExportBaseDirectory.FullName);
this.ExportBaseDirectory.Create();
return;
}
Console.WriteLine(this.ExportBaseDirectory.Name + "already exists");
}
protected abstract SnooperExportBase CreateSnooperExport();
protected void OnAfterDataExporting() => this.SnooperExport.OnAfterDataExporting();
protected void OnAfterProtocolParsing() => this.SnooperExport.OnAfterProtocolParsing();
protected void OnBeforeDataExporting() => this.SnooperExport.OnBeforeDataExporting();
protected void OnBeforeProtocolParsing() => this.SnooperExport.OnBeforeProtocolParsing();
protected void OnConversationProcessingBegin() => this.SnooperExport = this.CreateSnooperExport();
protected void OnConversationProcessingEnd() { this.FinalizeExports(); }
protected void ProcessAssignedConversations()
{
this.SelectedConversations.LockSelectedConversations();
long conversationIndex;
var sleuthType = this.GetType();
ILxConversation currentConversation;
//Main cycle on all conversations
while(this.SelectedConversations.TryGetNextConversations(this.GetType(), out currentConversation, out conversationIndex))
{
var selectedL7Conversations = new List<L7Conversation>();
if(currentConversation is L7Conversation) //todo refactor to SnooperBase.. or make more readable.. to method or somenting...
{
selectedL7Conversations.Add(currentConversation as L7Conversation);
}
else if(currentConversation is L4Conversation) {
selectedL7Conversations.AddRange((currentConversation as L4Conversation).L7Conversations);
}
else if(currentConversation is L3Conversation) { selectedL7Conversations.AddRange((currentConversation as L3Conversation).L7Conversations); }
foreach(var selectedL7Conversation in selectedL7Conversations)
{
this.CurrentConversation = selectedL7Conversation;
//eventExporter.ActualizeOpContext();
if(!this.ForceExportOnAllConversations && !this.CurrentConversation.IsXyProtocolConversation(this.ProtocolNBARName))
{
continue;
}
// RunBody(CurrentConversation, conversationIndex);
this.OnConversationProcessingBegin();
this.ProcessConversation();
this.OnConversationProcessingEnd();
}
}
}
protected abstract void ProcessConversation();
protected abstract void RunBody();
private void FinalizeExports()
{
this.SnooperExport.OnAfterDataExporting();
this._snooperExportsList.Add(this.SnooperExport);
this.OnSnooperExport(this.SnooperExport);
//Console.WriteLine(this);
}
private void OnSnooperExport(SnooperExportBase snooperExportBase)
{
//using (var dbx = this.InvestigationWindsorContainer.Resolve<NetfoxDbContext>())
//{
// dbx.SnooperExports.Add(snooperExportBase);
// dbx.SaveChanges();
//}
var exports = this.InvestigationWindsorContainer.Resolve<List<SnooperExportBase>>();
exports.Add(snooperExportBase);
}
}
}
| |
// 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,
// MERCHANTABLITY 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Microsoft.PythonTools.Django;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools.Project;
using Microsoft.Win32;
using TestUtilities;
using TestUtilities.Python;
namespace FastCgiTest {
[TestClass]
public class FastCgiTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
[TestInitialize]
public void CloseRunningIisExpress() {
PythonVersion.AssertInstalled();
IEnumerable<Process> running;
while ((running = Process.GetProcessesByName("iisexpress")).Any()) {
foreach (var p in running) {
try {
p.CloseMainWindow();
} catch (Exception ex) {
Console.WriteLine("Failed to CloseMainWindow on iisexpress: {0}", ex);
}
}
Thread.Sleep(1000);
foreach (var p in running) {
if (!p.HasExited) {
try {
p.Kill();
} catch (Exception ex) {
Console.WriteLine("Failed to Kill iisexpress: {0}", ex);
}
}
}
}
}
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void DjangoHelloWorld() {
using (var site = ConfigureIISForDjango(AppCmdPath, InterpreterPath, "DjangoTestApp.settings")) {
site.StartServer();
var response = site.Request("");
Console.WriteLine(response.ContentType);
var stream = response.GetResponseStream();
var content = new StreamReader(stream).ReadToEnd();
Console.WriteLine(content);
Assert.AreEqual(content, "<html><body>Hello World!</body></html>");
}
}
/*
* Currently disabled, we need to unify this w/ where web.config lives in Azure first
[TestMethod, Priority(1)]
public void ConfigVariables() {
using (var site = ConfigureIISForDjango(AppCmdPath, InterpreterPath, "DjangoTestApp.settings")) {
File.Copy("TestData\\DjangoTestApp\\web.config", Path.Combine(site.SiteDir, "web.config"));
site.StartServer();
CopyDir("TestData", site.SiteDir);
var response = site.Request("config");
Console.WriteLine(response.ContentType);
var stream = response.GetResponseStream();
var content = new StreamReader(stream).ReadToEnd();
Console.WriteLine(content);
Assert.AreEqual(content, "<html><body>Hello There!</body></html>");
}
}*/
[TestMethod, Priority(1)]
public void LargeResponse() {
using (var site = ConfigureIISForDjango(AppCmdPath, InterpreterPath, "DjangoTestApp.settings")) {
site.StartServer();
var response = site.Request("large_response");
Console.WriteLine(response.ContentType);
var stream = response.GetResponseStream();
var content = new StreamReader(stream).ReadToEnd();
string expected = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghjklmnopqrstuvwxyz0123456789";
Assert.AreEqual(expected.Length * 3000, content.Length, "Got: " + content);
for (int i = 0; i < content.Length / expected.Length; i++) {
for (int j = 0; j < expected.Length; j++) {
Assert.AreEqual(
expected[j],
content[i * expected.Length + j]
);
}
}
}
}
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void DjangoHelloWorldParallel() {
using (var site = ConfigureIISForDjango(AppCmdPath, InterpreterPath, "DjangoTestApp.settings")) {
site.StartServer();
const int threadCnt = 12;
const int requests = 1000;
var tasks = new Task[threadCnt];
int count = 0;
for (int i = 0; i < tasks.Length; i++) {
tasks[i] = Task.Run(() => {
for (int j = 0; j < requests; j++) {
var response = site.Request("");
var stream = response.GetResponseStream();
var content = new StreamReader(stream).ReadToEnd();
Assert.AreEqual(content, "<html><body>Hello World!</body></html>");
Interlocked.Increment(ref count);
}
});
}
for (int i = 0; i < tasks.Length; i++) {
tasks[i].Wait();
}
Assert.AreEqual(count, threadCnt * requests);
}
}
[TestMethod, Priority(1)]
public void CustomHandler() {
using (var site = ConfigureIISForCustomHandler(AppCmdPath, InterpreterPath, "custom_handler.handler")) {
site.StartServer();
var response = site.Request("");
var stream = response.GetResponseStream();
var content = new StreamReader(stream).ReadToEnd();
Assert.AreEqual("<html><body>hello world</body></html>", content);
Assert.AreEqual("42", response.Headers["Custom-Header"]);
}
}
[TestMethod, Priority(1)]
public void CustomCallableHandler() {
using (var site = ConfigureIISForCustomHandler(AppCmdPath, InterpreterPath, "custom_handler.callable_handler()")) {
site.StartServer();
var response = site.Request("");
var stream = response.GetResponseStream();
var content = new StreamReader(stream).ReadToEnd();
Assert.AreEqual("<html><body>hello world</body></html>", content);
}
}
[TestMethod, Priority(1)]
public void ErrorHandler() {
using (var site = ConfigureIISForCustomHandler(AppCmdPath, InterpreterPath, "custom_handler.error_handler")) {
site.StartServer();
try {
var response = site.Request("", printError: false);
} catch (WebException wex) {
var stream = wex.Response.GetResponseStream();
var content = new StreamReader(stream).ReadToEnd();
Assert.AreEqual(HttpStatusCode.NotFound, ((HttpWebResponse)wex.Response).StatusCode);
Assert.AreEqual("<html><body>Sorry folks, we're closed for two weeks to clean and repair America's favorite family fun park</body></html>", content);
Assert.AreEqual(WebExceptionStatus.ProtocolError, wex.Status);
}
}
}
private static string CreateSite() {
string dirName = TestData.GetTempPath(randomSubPath: true);
File.Copy("TestData\\applicationhostOriginal.config",
Path.Combine(dirName, "applicationHost.config"));
File.Copy(
WFastCgiPath,
Path.Combine(dirName, "wfastcgi.py")
);
Directory.CreateDirectory(Path.Combine(dirName, "WebSite"));
return dirName;
}
public static void ConfigureIIS(string appCmd, string appHostConfig, string python, string wfastcgi, Dictionary<string, string> envVars) {
using (var p = ProcessOutput.RunHiddenAndCapture(
appCmd, "set", "config", "/section:system.webServer/fastCGI",
string.Format("/+[fullPath='{0}', arguments='\"{1}\"']", python, wfastcgi),
"/AppHostConfig:" + appHostConfig
)) {
p.Wait();
DumpOutput(p);
Assert.AreEqual(0, p.ExitCode);
}
using (var p = ProcessOutput.RunHiddenAndCapture(
appCmd, "set", "config", "/section:system.webServer/handlers",
string.Format(
"/+[name='Python_via_FastCGI',path='*',verb='*',modules='FastCgiModule',scriptProcessor='{0}|\"{1}\"',resourceType='Unspecified']",
python, wfastcgi
),
"/AppHostConfig:" + appHostConfig
)) {
p.Wait();
DumpOutput(p);
Assert.AreEqual(0, p.ExitCode);
}
foreach (var keyValue in envVars) {
using (var p = ProcessOutput.RunHiddenAndCapture(
appCmd, "set", "config", "/section:system.webServer/fastCgi",
string.Format(
"/+[fullPath='{0}', arguments='\"{1}\"'].environmentVariables.[name='{2}',value='{3}']",
python, wfastcgi, keyValue.Key, keyValue.Value
),
"/commit:apphost",
"/AppHostConfig:" + appHostConfig
)) {
p.Wait();
DumpOutput(p);
Assert.AreEqual(0, p.ExitCode);
}
}
using(var p = ProcessOutput.RunHiddenAndCapture(
appCmd, "add", "site", "/name:TestSite",
"/bindings:http://localhost:8181",
"/physicalPath:" + Path.GetDirectoryName(appHostConfig),
"/AppHostConfig:" + appHostConfig
)) {
p.Wait();
DumpOutput(p);
Assert.AreEqual(0, p.ExitCode);
}
}
private static void DumpOutput(ProcessOutput process) {
Console.WriteLine(process.Arguments);
foreach (var line in process.StandardOutputLines) {
Console.WriteLine(line);
}
foreach (var line in process.StandardErrorLines) {
Console.Error.WriteLine(line);
}
}
private void EnsureDjango() {
EnsureDjango(InterpreterPath);
}
private static void EnsureDjango(string python) {
using (var proc = ProcessOutput.RunHiddenAndCapture(python, "-c", "import django")) {
proc.Wait();
if (proc.ExitCode != 0) {
DumpOutput(proc);
Assert.Inconclusive("Django must be installed into {0} for this test", python);
}
}
}
private static WebSite ConfigureIISForDjango(string appCmd, string python, string djangoSettings) {
EnsureDjango(python);
var site = CreateSite();
Console.WriteLine("Site: {0}", site);
ConfigureIIS(
appCmd,
Path.Combine(site, "applicationHost.config"),
python,
Path.Combine(site, "wfastcgi.py"),
new Dictionary<string, string>() {
{ "DJANGO_SETTINGS_MODULE", djangoSettings },
{ "PYTHONPATH", "" },
{ "WSGI_HANDLER", "django.core.handlers.wsgi.WSGIHandler()" }
}
);
var module = djangoSettings.Split(new[] { '.' }, 2)[0];
FileUtils.CopyDirectory(
TestData.GetPath(Path.Combine("TestData", "WFastCgi", module)),
Path.Combine(site, module)
);
Console.WriteLine("Site created at {0}", site);
return new WebSite(site);
}
private static WebSite ConfigureIISForCustomHandler(string appCmd, string python, string handler) {
var site = CreateSite();
Console.WriteLine("Site: {0}", site);
ConfigureIIS(
appCmd,
Path.Combine(site, "applicationHost.config"),
python,
Path.Combine(site, "wfastcgi.py"),
new Dictionary<string, string>() {
{ "WSGI_HANDLER", handler },
{ "WSGI_LOG", Path.Combine(site, "log.txt") }
}
);
var module = handler.Split(new[] { '.' }, 2)[0];
try {
File.Copy(
TestData.GetPath("TestData\\WFastCGI\\" + module + ".py"),
Path.Combine(site, module + ".py"),
true
);
} catch (IOException ex) {
Console.WriteLine("Failed to copy {0}.py: {1}", module, ex);
}
Console.WriteLine("Site created at {0}", site);
return new WebSite(site);
}
public virtual PythonVersion PythonVersion {
get {
return PythonPaths.Python27 ?? PythonPaths.Python27_x64;
}
}
public string InterpreterPath {
get {
return PythonVersion.InterpreterPath;
}
}
public virtual string AppCmdPath {
get {
return Path.Combine(
Path.GetDirectoryName(IisExpressPath),
"appcmd.exe"
);
}
}
class WebSite : IDisposable {
private readonly string _dir;
private ProcessOutput _process;
public WebSite(string dir) {
_dir = dir;
}
public string SiteDir {
get {
return _dir;
}
}
public void StartServer() {
_process = ProcessOutput.Run(
IisExpressPath,
new[] { "/config:" + Path.Combine(_dir, "applicationHost.config"), "/systray:false" },
null,
null,
false,
new OutputRedirector("IIS")
);
Console.WriteLine("Server started: {0}", _process.Arguments);
}
public WebResponse Request(string uri, bool printError = true) {
WebRequest req = WebRequest.Create(
"http://localhost:8181/" + uri
);
try {
return req.GetResponse();
} catch (WebException ex) {
if (printError) {
Console.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
throw;
}
}
public void StopServer() {
var p = Interlocked.Exchange(ref _process, null);
if (p != null) {
if (!p.Wait(TimeSpan.FromSeconds(5))) {
p.Kill();
}
p.Dispose();
}
}
#region IDisposable Members
public void Dispose() {
StopServer();
}
#endregion
}
#region Test Cases
[TestMethod, Priority(1)]
public void TestDjangoNewApp() {
EnsureDjango();
IisExpressTest(
"TestData\\WFastCgi\\DjangoApp",
new GetAndValidateUrl(GetLocalUrl(), ValidateWelcomeToDjango)
);
}
[TestMethod, Priority(1)]
public void TestDjangoNewAppUrlRewrite() {
EnsureDjango();
IisExpressTest(
"TestData\\WFastCgi\\DjangoAppUrlRewrite",
new GetAndValidateUrl(GetLocalUrl(), ValidateWelcomeToDjango)
);
}
[TestMethod, Priority(1)]
public void TestHelloWorld() {
IisExpressTest(
"TestData\\WFastCgi\\HelloWorld",
new GetAndValidateUrl(GetLocalUrl(), ValidateHelloWorld)
);
}
[TestMethod, Priority(1)]
public void TestHelloWorldCallable() {
IisExpressTest(
"TestData\\WFastCgi\\HelloWorldCallable",
new GetAndValidateUrl(GetLocalUrl(), ValidateHelloWorld)
);
}
/// <summary>
/// Handler doesn't exist in imported module
/// </summary>
[TestMethod, Priority(1)]
public void TestBadHandler() {
IisExpressTest(
"TestData\\WFastCgi\\BadHandler",
new GetAndValidateErrorUrl(GetLocalUrl(), ValidateString("'module' object has no attribute 'does_not_exist'"))
);
}
/// <summary>
/// WSGI_HANDLER module doesn't exist
/// </summary>
[TestMethod, Priority(1)]
public void TestBadHandler2() {
IisExpressTest(
"TestData\\WFastCgi\\BadHandler2",
new GetAndValidateErrorUrl(GetLocalUrl(), ValidateString("\"myapp_does_not_exist.does_not_exist\" could not be imported"))
);
}
/// <summary>
/// WSGI_HANDLER raises an exceptoin during import
/// </summary>
[TestMethod, Priority(1)]
public void TestBadHandler3() {
IisExpressTest(
"TestData\\WFastCgi\\BadHandler3",
new GetAndValidateErrorUrl(GetLocalUrl(), ValidateString("Exception: handler file is raising"))
);
}
/// <summary>
/// WSGI_HANDLER is just set to modulename
/// </summary>
[TestMethod, Priority(1)]
public void TestBadHandler4() {
IisExpressTest(
"TestData\\WFastCgi\\BadHandler4",
new GetAndValidateErrorUrl(GetLocalUrl(), ValidateString("\"myapp\" could not be imported"))
);
}
/// <summary>
/// WSGI_HANDLER env var isn't set at all
/// </summary>
[TestMethod, Priority(1)]
public void TestBadHandler5() {
IisExpressTest(
"TestData\\WFastCgi\\BadHandler5",
new GetAndValidateErrorUrl(GetLocalUrl(), ValidateString("WSGI_HANDLER env var must be set"))
);
}
/// <summary>
/// WSGI_HANDLER points to object of NoneType
/// </summary>
[TestMethod, Priority(1)]
public void TestBadHandler6() {
IisExpressTest(
"TestData\\WFastCgi\\BadHandler6",
new GetAndValidateErrorUrl(GetLocalUrl(), ValidateString("\"myapp.app\" could not be imported"))
);
}
/// <summary>
/// WSGI_HANDLER writes to std err and std out, and raises.
/// </summary>
[TestMethod, Priority(1)]
public void TestBadHandler7() {
IisExpressTest(
"TestData\\WFastCgi\\BadHandler7",
new GetAndValidateErrorUrl(GetLocalUrl(),
ValidateString("something to std err"),
ValidateString("something to std out")
)
);
}
/// <summary>
/// Validates environment dict passed to handler
/// </summary>
[TestMethod, Priority(1)]
public void TestEnvironment() {
IisExpressTest(
"TestData\\WFastCgi\\Environment",
new GetAndValidateUrl(
GetLocalUrl("/fob/oar/baz?quox=100"),
ValidateString("QUERY_STRING: quox=100\nPATH_INFO: /fob/oar/baz\nSCRIPT_NAME: \n")
)
);
}
/// <summary>
/// Validates wfastcgi exits when changes to .py or .config files are detected
/// </summary>
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void TestFileSystemChanges() {
var location = TestData.GetTempPath(randomSubPath: true);
FileUtils.CopyDirectory(TestData.GetPath(@"TestData\WFastCgi\FileSystemChanges"), location);
IisExpressTest(
location,
new GetAndValidateUrl(
GetLocalUrl(),
ValidateString("hello world!")
),
PatchFile(Path.Combine(location, "myapp.py"), @"def handler(environment, start_response):
start_response('200', '')
return [b'goodbye world!']"),
new GetAndValidateUrl(
GetLocalUrl(),
ValidateString("goodbye world!")
),
ReplaceInFile(Path.Combine(location, "web.config"), "myapp.handler", "myapp2.handler"),
new GetAndValidateUrl(
GetLocalUrl(),
ValidateString("myapp2 world!")
)
);
}
/// <summary>
/// Validates wfastcgi exits when changes to .py files in a subdirectory are detected
/// </summary>
[TestMethod, Priority(1)]
public void TestFileSystemChangesPackage() {
var location = TestData.GetTempPath(randomSubPath: true);
FileUtils.CopyDirectory(TestData.GetPath(@"TestData\WFastCgi\FileSystemChangesPackage"), location);
IisExpressTest(
location,
new GetAndValidateUrl(
GetLocalUrl(),
ValidateString("hello world!")
),
PatchFile(Path.Combine(location, "myapp", "__init__.py"), @"def handler(environment, start_response):
start_response('200', '')
return [b'goodbye world!']"),
new GetAndValidateUrl(
GetLocalUrl(),
ValidateString("goodbye world!")
)
);
}
/// <summary>
/// Validates wfastcgi exits when changes to a file pattern specified in web.config changes.
/// </summary>
[TestMethod, Priority(1)]
public void TestFileSystemChangesCustomRegex() {
var location = TestData.GetTempPath(randomSubPath: true);
FileUtils.CopyDirectory(TestData.GetPath(@"TestData\WFastCgi\FileSystemChangesCustomRegex"), location);
IisExpressTest(
location,
new GetAndValidateUrl(
GetLocalUrl(),
ValidateString("hello world!")
),
PatchFile(Path.Combine(location, "myapp.data"), "goodbye world!"),
new GetAndValidateUrl(
GetLocalUrl(),
ValidateString("goodbye world!")
)
);
}
/// <summary>
/// Validates wfastcgi doesn't exit when file system change checks are disabled.
/// </summary>
[TestMethod, Priority(1)]
public void TestFileSystemChangesDisabled() {
var location = TestData.GetTempPath(randomSubPath: true);
FileUtils.CopyDirectory(TestData.GetPath(@"TestData\WFastCgi\FileSystemChangesDisabled"), location);
IisExpressTest(
location,
new GetAndValidateUrl(
GetLocalUrl(),
ValidateString("hello world!")
),
PatchFile(Path.Combine(location, "myapp.py"), @"def handler(environment, start_response):
start_response('200', '')
return ['goodbye world!']"),
new GetAndValidateUrl(
GetLocalUrl(),
ValidateString("hello world!")
)
);
}
/// <summary>
/// Validates that we can setup IIS to serve static files properly
/// </summary>
[TestMethod, Priority(1)]
public void TestStaticFiles() {
EnsureDjango();
IisExpressTest(
CollectStaticFiles("TestData\\WFastCgi\\DjangoSimpleApp"),
"TestData\\WFastCgi\\DjangoSimpleApp",
null,
new GetAndValidateUrl(
GetLocalUrl("/static/fob/helloworld.txt"),
ValidateString("hello world from a static text file!")
)
);
}
/// <summary>
/// Validates that we can setup IIS to serve static files properly
/// </summary>
[TestMethod, Priority(1)]
public void TestStaticFilesUrlRewrite() {
EnsureDjango();
IisExpressTest(
CollectStaticFiles("TestData\\WFastCgi\\DjangoSimpleAppUrlRewrite"),
"TestData\\WFastCgi\\DjangoSimpleAppUrlRewrite",
null,
new GetAndValidateUrl(
GetLocalUrl("/static/fob/helloworld.txt"),
ValidateString("hello world from a static text file!")
)
);
}
/// <summary>
/// Validates environment dict passed to handler using URL rewriting
/// </summary>
[TestMethod, Priority(1)]
public void TestEnvironmentUrlRewrite() {
IisExpressTest(
"TestData\\WFastCgi\\EnvironmentUrlRewrite",
new GetAndValidateUrl(
GetLocalUrl("/fob/oar/baz?quox=100"),
ValidateString("QUERY_STRING: quox=100\nPATH_INFO: /fob/oar/baz\nSCRIPT_NAME: \n")
)
);
}
/// <summary>
/// Tests that we send portions of the response as they are given to us.
/// </summary>
[TestMethod, Priority(1)]
public void TestStreamingHandler() {
int partCount = 0;
IisExpressTest(
"TestData\\WFastCgi\\StreamingHandler",
new GetAndValidateUrlPieces(
GetLocalUrl(),
piece => {
if (partCount++ == 0) {
Assert.AreEqual("Hello world!", piece);
var req = WebRequest.Create(GetLocalUrl() + "/fob");
var response = req.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
} else {
Assert.AreEqual(partCount, 2);
Assert.AreEqual("goodbye world!", piece);
}
}
)
);
}
/// <summary>
/// Tests that we send portions of the response as they are given to us.
/// </summary>
[TestMethod, Priority(1)]
public void TestDjangoQueryString() {
EnsureDjango();
IisExpressTest(
"TestData\\WFastCgi\\DjangoSimpleApp",
new GetAndValidateUrl(
GetLocalUrl("?fob=42&oar=100"),
ValidateString("GET: fob=42&oar=100", "GET: oar=100&fob=42")
)
);
}
/// <summary>
/// Tests that we can post values to Django and it gets them
/// </summary>
[TestMethod, Priority(1)]
public void TestDjangoPost() {
EnsureDjango();
IisExpressTest(
"TestData\\WFastCgi\\DjangoSimpleApp",
new PostAndValidateUrl(
GetLocalUrl(),
ValidateString("POST: fob=42&oar=100", "POST: oar=100&fob=42"),
new KeyValuePair<string, string>("fob", "42"),
new KeyValuePair<string, string>("oar", "100")
)
);
}
/// <summary>
/// Tests that we send portions of the response as they are given to us.
/// </summary>
[TestMethod, Priority(1)]
public void TestDjangoPath() {
EnsureDjango();
IisExpressTest(
"TestData\\WFastCgi\\DjangoSimpleApp",
new GetAndValidateUrl(
GetLocalUrl("/fob/oar/baz"),
ValidateString("path: /fob/oar/baz\npath_info: /fob/oar/baz")
)
);
}
/// <summary>
/// Tests that we send portions of the response as they are given to us.
/// </summary>
[TestMethod, Priority(1)]
public void TestDjangoQueryStringUrlRewrite() {
EnsureDjango();
IisExpressTest(
"TestData\\WFastCgi\\DjangoSimpleAppUrlRewrite",
new GetAndValidateUrl(
GetLocalUrl("?fob=42&oar=100"),
ValidateString("GET: fob=42&oar=100", "GET: oar=100&fob=42")
)
);
}
/// <summary>
/// Tests that we can post values to Django and it gets them when using URL rewriting
/// </summary>
[TestMethod, Priority(1)]
public void TestDjangoPostUrlRewrite() {
EnsureDjango();
IisExpressTest(
"TestData\\WFastCgi\\DjangoSimpleAppUrlRewrite",
new PostAndValidateUrl(
GetLocalUrl(),
ValidateString("POST: fob=42&oar=100", "POST: oar=100&fob=42"),
new KeyValuePair<string, string>("fob", "42"),
new KeyValuePair<string, string>("oar", "100")
)
);
}
/// <summary>
/// Tests that we send portions of the response as they are given to us.
/// </summary>
[TestMethod, Priority(1)]
public void TestDjangoPathUrlRewrite() {
EnsureDjango();
IisExpressTest(
"TestData\\WFastCgi\\DjangoSimpleAppUrlRewrite",
new GetAndValidateUrl(
GetLocalUrl("/fob/oar/baz"),
ValidateString("path: /fob/oar/baz\npath_info: /fob/oar/baz")
)
);
}
/// <summary>
/// Tests expand path
/// </summary>
[TestMethod, Priority(1)]
public void TestExpandPathEnvironmentVariables() {
IisExpressTest(
null,
"TestData\\WFastCgi\\ExpandPathEnvironmentVariables",
new Dictionary<string, string> {
{ "SITELOCATION", TestData.GetPath("TestData\\WFastCgi\\ExpandPathEnvironmentVariables") },
{ "OTHERLOCATION", TestData.GetPath("TestData\\WFastCgi\\ExpandPathEnvironmentVariablesOtherDir") }
},
new GetAndValidateUrl(GetLocalUrl(), ValidateHelloWorld)
);
}
[TestMethod, Priority(1)]
public void TestBadHeaders1() {
IisExpressTest(
"TestData\\WFastCgi\\BadHeaders",
new GetAndValidateErrorUrl(
GetLocalUrl("/test_1"),
ValidateString("500 Error")
)
);
}
[TestMethod, Priority(1)]
public void TestBadHeaders2() {
IisExpressTest(
"TestData\\WFastCgi\\BadHeaders",
new GetAndValidateErrorUrl(
GetLocalUrl("/test_2"),
ValidateString("Exception")
)
);
}
[TestMethod, Priority(1)]
public void TestBadHeaders3() {
IisExpressTest(
"TestData\\WFastCgi\\BadHeaders",
new GetAndValidateErrorUrl(
GetLocalUrl("/test_3"),
ValidateString("start_response has already been called")
)
);
}
[TestMethod, Priority(1)]
public void TestBadHeaders4() {
IisExpressTest(
"TestData\\WFastCgi\\BadHeaders",
new GetAndValidateErrorUrl(
GetLocalUrl("/test_4"),
ValidateString("start_response has not yet been called")
)
);
}
#endregion
#region Test Case Validators/Actions
abstract class Validator {
public abstract void Validate();
public static implicit operator Action(Validator self) {
return self.Validate;
}
}
/// <summary>
/// Requests the specified URL, the web page request should succeed, and
/// then the contents of the web page are validated with the provided delegate.
/// </summary>
class GetAndValidateUrl : Validator {
private readonly string Url;
private readonly Action<string> Validation;
public GetAndValidateUrl(string url, Action<string> validation) {
Url = url;
Validation = validation;
}
public override void Validate() {
Console.WriteLine("Requesting Url: {0}", Url);
var req = WebRequest.Create(Url);
try {
var response = req.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
Console.WriteLine("Validating Url");
Validation(result);
} catch (WebException wex) {
var reader = new StreamReader(wex.Response.GetResponseStream());
Assert.Fail("Failed to get response: {0}", reader.ReadToEnd());
}
}
}
/// <summary>
/// Requests the specified URL, the web page request should succeed, and
/// then the contents of the web page are validated with the provided delegate.
/// </summary>
class PostAndValidateUrl : Validator {
private readonly string Url;
private readonly Action<string> Validation;
private readonly KeyValuePair<string, string>[] PostValues;
public PostAndValidateUrl(string url, Action<string> validation, params KeyValuePair<string, string>[] postValues) {
Url = url;
Validation = validation;
PostValues = postValues;
}
public override void Validate() {
Console.WriteLine("Requesting Url: {0}", Url);
var req = WebRequest.Create(Url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
StringBuilder data = new StringBuilder();
foreach (var keyValue in PostValues) {
if (data.Length > 0) {
data.Append('&');
}
data.Append(HttpUtility.UrlEncode(keyValue.Key));
data.Append("=");
data.Append(HttpUtility.UrlEncode(keyValue.Value));
}
var bytes = Encoding.UTF8.GetBytes(data.ToString());
req.ContentLength = bytes.Length;
var stream = req.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
try {
var response = req.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
Console.WriteLine("Validating Url");
Validation(result);
} catch (WebException wex) {
var reader = new StreamReader(wex.Response.GetResponseStream());
Assert.Fail("Failed to get response: {0}", reader.ReadToEnd());
}
}
}
/// <summary>
/// Requests the specified URL, the web page request should succeed, and
/// then the contents of the web page are validated with the provided delegate.
/// </summary>
class GetAndValidateUrlPieces : Validator {
private readonly string Url;
private readonly Action<string> Validation;
public GetAndValidateUrlPieces(string url, Action<string> validation) {
Url = url;
Validation = validation;
}
public override void Validate() {
Console.WriteLine("Requesting Url: {0}", Url);
var req = WebRequest.Create(Url);
var response = req.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
Console.WriteLine("Validating");
string line;
while ((line = reader.ReadLine()) != null) {
Console.WriteLine("Validating piece: {0}", line);
Validation(line);
}
}
}
/// <summary>
/// Requests the specified URL, the web page request should succeed, and
/// then the contents of the web page are validated with the provided delegate.
/// </summary>
class GetAndValidateErrorUrl : Validator {
private readonly string Url;
private readonly Action<string>[] Validators;
public GetAndValidateErrorUrl(string url, params Action<string>[] validatiors) {
Url = url;
Validators = validatiors;
}
public override void Validate() {
Console.WriteLine("Requesting URL: {0}", Url);
var req = WebRequest.Create(Url);
try {
var response = req.GetResponse();
Assert.Fail("Got successful response: " + new StreamReader(response.GetResponseStream()).ReadToEnd());
} catch (WebException we) {
var reader = new StreamReader(we.Response.GetResponseStream());
var result = reader.ReadToEnd();
Console.WriteLine("Received: {0}", result);
foreach (var validator in Validators) {
validator(result);
}
}
}
public static implicit operator Action(GetAndValidateErrorUrl self) {
return self.Validate;
}
}
private Action CollectStaticFiles(string location) {
location = TestData.GetPath(location);
return () => {
using (var p = ProcessOutput.Run(
InterpreterPath,
new[] { Path.Combine(location, "manage.py"), "collectstatic", "--noinput" },
location,
null,
false,
new OutputRedirector("manage.py")
)) {
p.Wait();
Assert.AreEqual(0, p.ExitCode);
}
};
}
private static Action ReplaceInFile(string filename, string oldText, string newText) {
return () => {
Console.WriteLine("Replacing text in {0}", filename);
File.WriteAllText(filename, File.ReadAllText(filename).Replace(oldText, newText));
System.Threading.Thread.Sleep(3000);
};
}
private static Action PatchFile(string filename, string newText) {
return () => {
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Patching file {0}", filename);
File.WriteAllText(filename, newText);
System.Threading.Thread.Sleep(4000);
};
}
private static string MakeAssertMessage(string[] expected, string actual) {
var combined = string.Join(
Environment.NewLine,
expected.Select(s => string.Format(" * \"{0}\"", s))
);
return string.Format(
"Expected any of:{0}{1}{0}Actual:{0}{2}",
Environment.NewLine,
combined,
actual
);
}
private static Action<string> ValidateString(params string[] text) {
return (received) => {
Assert.IsTrue(text.Any(t => received.Contains(t)), MakeAssertMessage(text, received));
};
}
private static void ValidateWelcomeToDjango(string text) {
Assert.IsTrue(text.IndexOf("Congratulations on your first Django-powered page.") != -1, "It worked page failed to be returned");
}
private static void ValidateHelloWorld(string text) {
Assert.IsTrue(text.IndexOf("hello world!") != -1, "hello world page not returned");
}
#endregion
#region Test Case Infrastructure
private void IisExpressTest(string location, params Action[] actions) {
IisExpressTest(null, location, null, actions);
}
private void IisExpressTest(
Action initialization,
string location,
Dictionary<string, string> environment,
params Action[] actions
) {
Console.WriteLine("Current Directory: {0}", Environment.CurrentDirectory);
Console.WriteLine("WFastCgiPath: {0}", WFastCgiPath);
if (!Path.IsPathRooted(location)) {
location = TestData.GetPath(location);
}
Console.WriteLine("Test location: {0}", location);
var appConfig = GenerateApplicationHostConfig(location);
var webConfigLocSource = Path.Combine(location, "web.config.source");
if (!File.Exists(webConfigLocSource)) {
webConfigLocSource = Path.Combine(location, "web.config");
}
var webConfigLoc = Path.Combine(location, "web.config");
var webConfigContents = File.ReadAllText(webConfigLocSource);
File.WriteAllText(
webConfigLoc,
webConfigContents.Replace("[PYTHONPATH]", InterpreterPath)
.Replace("[WFASTCGIPATH]", WFastCgiPath)
.Replace("[SITEPATH]", Path.GetFullPath(location))
);
var env = environment != null ? new Dictionary<string, string>(environment) : new Dictionary<string, string>();
env["WSGI_LOG"] = Path.Combine(location, "log.txt");
if (initialization != null) {
Console.WriteLine("Initializing");
initialization();
}
using (var p = ProcessOutput.Run(
IisExpressPath,
new[] { "/config:" + appConfig, "/site:WebSite1", "/systray:false", "/trace:info" },
null,
env,
false,
new OutputRedirector("IIS")
)) {
Console.WriteLine("Starting IIS Express: {0}", p.Arguments);
try {
foreach (var action in actions) {
action();
}
} finally {
p.Kill();
}
}
}
private class OutputRedirector : Redirector {
private readonly string _format;
public OutputRedirector(string category) {
if (string.IsNullOrEmpty(category)) {
_format = "{0}";
} else {
_format = category + ": {0}";
}
}
public override void WriteLine(string line) {
Console.WriteLine(_format, line ?? "(null)");
}
public override void WriteErrorLine(string line) {
Console.Error.WriteLine(_format, line ?? "(null)");
}
}
private static string IisExpressPath {
get {
var iisExpressPath = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\IISExpress\\10.0", "InstallPath", null) as string ??
Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\IISExpress\\8.0", "InstallPath", null) as string;
if (iisExpressPath == null) {
Assert.Inconclusive("Can't find IIS Express");
return null;
}
return Path.Combine(iisExpressPath, "iisexpress.exe");
}
}
private static string GetLocalUrl(string path = null) {
string res = "http://localhost:8080";
if (!String.IsNullOrWhiteSpace(path)) {
return res + path;
}
return res;
}
private string GenerateApplicationHostConfig(string siteLocation) {
var tempConfig = Path.Combine(TestData.GetTempPath(randomSubPath: true), "applicationHost.config");
StringBuilder baseConfig = new StringBuilder(File.ReadAllText("TestData\\WFastCgi\\applicationHost.config"));
baseConfig.Replace("[PYTHONPATH]", InterpreterPath)
.Replace("[WFASTCGIPATH]", WFastCgiPath)
.Replace("[SITE_LOCATION]", Path.GetFullPath(siteLocation));
File.WriteAllText(tempConfig, baseConfig.ToString());
return tempConfig;
}
private static string WFastCgiPath {
get {
var wfastcgiPath = TestData.GetPath("wfastcgi.py");
if (File.Exists(wfastcgiPath)) {
return wfastcgiPath;
}
//wfastcgiPath = Path.Combine(
// Environment.GetEnvironmentVariable("ProgramFiles"),
// "MSbuild",
// "Microsoft",
// "VisualStudio",
// "v" + AssemblyVersionInfo.VSVersion,
// "Python Tools",
// "wfastcgi.py"
//);
//if (File.Exists(wfastcgiPath)) {
// return wfastcgiPath;
//}
//wfastcgiPath = Path.Combine(
// Environment.GetEnvironmentVariable("ProgramFiles(x86)"),
// "MSbuild",
// "Microsoft",
// "VisualStudio",
// "v" + AssemblyVersionInfo.VSVersion,
// "Python Tools",
// "wfastcgi.py"
//);
//if (File.Exists(wfastcgiPath)) {
// return wfastcgiPath;
//}
throw new InvalidOperationException("Failed to find wfastcgi.py");
}
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/13/2009 4:47:12 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// Jiri Kadlec | 11/20/2010 | Updated the Esri string of Web Mercator Auxiliary sphere projection
// Matthew K | 01/10/2010 | Removed Parameters dictionary
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using DotSpatial.Projections.AuthorityCodes;
using DotSpatial.Projections.Transforms;
namespace DotSpatial.Projections
{
/// <summary>
/// Parameters based on http://trac.osgeo.org/proj/wiki/GenParms. Also, see http://home.comcast.net/~gevenden56/proj/manual.pdf
/// </summary>
public class ProjectionInfo : ProjDescriptor, IEsriString
{
#region Constants and Fields
private double? _longitudeOf1st;
private double? _longitudeOf2nd;
private double? _scaleFactor;
private string _longitudeOfCenterAlias;
// stores the value of the actual parameter name that was used in the original (when the string came from WKT/Esri)
private string _latitudeOfOriginAlias;
private string _falseEastingAlias;
private string _falseNorthingAlias;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref = "ProjectionInfo" /> class.
/// </summary>
public ProjectionInfo()
{
GeographicInfo = new GeographicInfo();
Unit = new LinearUnit();
_scaleFactor = 1; // if not specified, default to 1
AuxiliarySphereType = AuxiliarySphereType.NotSpecified;
NoDefs = true;
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the athority, for example EPSG
/// </summary>
public string Authority { get; set; }
/// <summary>
/// Gets or sets the athority code.
/// </summary>
public int AuthorityCode { get; set; }
/// <summary>
/// Gets or sets the auxiliary sphere type.
/// </summary>
public AuxiliarySphereType AuxiliarySphereType { get; set; }
/// <summary>
/// The horizontal 0 point in geographic terms
/// </summary>
public double? CentralMeridian { get; set; }
/// <summary>
/// The false easting for this coordinate system
/// </summary>
public double? FalseEasting { get; set; }
/// <summary>
/// The false northing for this coordinate system
/// </summary>
public double? FalseNorthing { get; set; }
/// <summary>
/// Gets or sets a boolean indicating a geocentric latitude parameter
/// </summary>
public bool Geoc { get; set; }
/// <summary>
/// The geographic information
/// </summary>
public GeographicInfo GeographicInfo { get; set; }
/// <summary>
/// Gets or sets a boolean that indicates whether or not this
/// projection is geocentric.
/// </summary>
public bool IsGeocentric { get; set; }
/// <summary>
/// True if this coordinate system is expressed only using geographic coordinates
/// </summary>
public bool IsLatLon { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether this projection applies to the
/// southern coordinate system or not.
/// </summary>
public bool IsSouth { get; set; }
/// <summary>
/// True if the transform is defined. That doesn't really mean it accurately represents the named
/// projection, but rather it won't throw a null exception during transformation for the lack of
/// a transform definition.
/// </summary>
public bool IsValid
{
get
{
return Transform != null;
}
}
/// <summary>
/// The zero point in geographic terms
/// </summary>
public double? LatitudeOfOrigin { get; set; }
/// <summary>
/// The longitude of center for this coordinate system
/// </summary>
public double? LongitudeOfCenter { get; set; }
/// <summary>
/// Gets or sets the M.
/// </summary>
/// <value>
/// The M.
/// </value>
public double? M { get; set; }
/// <summary>
/// Gets or sets the name of this projection information
/// </summary>
public string Name { get; set; }
/// <summary>
/// A boolean that indicates whether to use the /usr/share/proj/proj_def.dat defaults file (proj4 parameter "no_defs").
/// </summary>
public bool NoDefs { get; set; }
/// <summary>
/// Gets or sets a boolean for the over-ranging flag
/// </summary>
public bool Over { get; set; }
/// <summary>
/// The scale factor for this coordinate system
/// </summary>
public double ScaleFactor
{
get
{
return _scaleFactor ?? 1;
}
set
{
_scaleFactor = value;
}
}
/// <summary>
/// The line of latitude where the scale information is preserved.
/// </summary>
public double? StandardParallel1 { get; set; }
/// <summary>
/// The standard parallel 2.
/// </summary>
public double? StandardParallel2 { get; set; }
/// <summary>
/// Gets or sets the transform that converts between geodetic coordinates and projected coordinates.
/// </summary>
public ITransform Transform { get; set; }
/// <summary>
/// The unit being used for measurements.
/// </summary>
public LinearUnit Unit { get; set; }
/// <summary>
/// Gets or sets the w.
/// </summary>
/// <value>
/// The w.
/// </value>
public double? W { get; set; }
/// <summary>
/// Gets or sets the integer zone parameter if it is specified.
/// </summary>
public int? Zone { get; set; }
// ReSharper disable InconsistentNaming
/// <summary>
/// Gets or sets the alpha/ azimuth.
/// </summary>
/// <value>
/// ? Used with Oblique Mercator and possibly a few others. For our purposes this is exactly the same as azimuth
/// </value>
public double? alpha { get; set; }
/// <summary>
/// Gets or sets the BNS.
/// </summary>
/// <value>
/// The BNS.
/// </value>
public int? bns { get; set; }
/// <summary>
/// Gets or sets the czech.
/// </summary>
/// <value>
/// The czech.
/// </value>
public int? czech { get; set; }
/// <summary>
/// Gets or sets the guam.
/// </summary>
/// <value>
/// The guam.
/// </value>
public bool? guam { get; set; }
/// <summary>
/// Gets or sets the h.
/// </summary>
/// <value>
/// The h.
/// </value>
public double? h { get; set; }
/// <summary>
/// Gets or sets the lat_ts.
/// </summary>
/// <value>
/// Latitude of true scale.
/// </value>
public double? lat_ts { get; set; }
/// <summary>
/// Gets or sets the lon_1.
/// </summary>
/// <value>
/// The lon_1.
/// </value>
public double? lon_1 { get; set; }
/// <summary>
/// Gets or sets the lon_2.
/// </summary>
/// <value>
/// The lon_2.
/// </value>
public double? lon_2 { get; set; }
/// <summary>
/// Gets or sets the lonc.
/// </summary>
/// <value>
/// The lonc.
/// </value>
public double? lonc { get; set; }
/// <summary>
/// Gets or sets the m. Named mGeneral to prevent CLS conflicts.
/// </summary>
/// <value>
/// The m.
/// </value>
public double? mGeneral { get; set; }
/// <summary>
/// Gets or sets the n.
/// </summary>
/// <value>
/// The n.
/// </value>
public double? n { get; set; }
/// <summary>
/// Gets or sets the no_rot.
/// </summary>
/// <value>
/// The no_rot. Seems to be used as a boolean.
/// </value>
public int? no_rot { get; set; }
/// <summary>
/// Gets or sets the no_uoff.
/// </summary>
/// <value>
/// The no_uoff. Seems to be used as a boolean.
/// </value>
public int? no_uoff { get; set; }
/// <summary>
/// Gets or sets the rot_conv.
/// </summary>
/// <value>
/// The rot_conv. Seems to be used as a boolean.
/// </value>
public int? rot_conv { get; set; }
/// <summary>
/// Gets or sets the to_meter.
/// </summary>
/// <value>
/// Multiplier to convert map units to 1.0m
/// </value>
public double? to_meter { get; set; }
// ReSharper restore InconsistentNaming
#endregion
#region Public Methods
/// <summary>
/// Gets the lon_1 parameter in radians
/// </summary>
/// <returns>
/// The get lam 1.
/// </returns>
public double Lam1
{
get
{
if (StandardParallel1 != null)
{
return StandardParallel1.Value * GeographicInfo.Unit.Radians;
}
return 0;
}
}
/// <summary>
/// Gets the lon_2 parameter in radians
/// </summary>
/// <returns>
/// The get lam 2.
/// </returns>
public double Lam2
{
get
{
if (StandardParallel2 != null)
{
return StandardParallel2.Value * GeographicInfo.Unit.Radians;
}
return 0;
}
}
/// <summary>
/// Gets the lat_1 parameter multiplied by radians
/// </summary>
/// <returns>
/// The get phi 1.
/// </returns>
public double Phi1
{
get
{
if (StandardParallel1 != null)
{
return StandardParallel1.Value * GeographicInfo.Unit.Radians;
}
return 0;
}
}
/// <summary>
/// Gets the lat_2 parameter multiplied by radians
/// </summary>
/// <returns>
/// The get phi 2.
/// </returns>
public double Phi2
{
get
{
if (StandardParallel2 != null)
{
return StandardParallel2.Value * GeographicInfo.Unit.Radians;
}
return 0;
}
}
/// <summary>
/// Sets the lambda 0, or central meridian in radial coordinates
/// </summary>
/// <param name="value">
/// The value of Lambda 0 in radians
/// </param>
public double Lam0
{
get
{
if (CentralMeridian != null)
{
return CentralMeridian.Value * GeographicInfo.Unit.Radians;
}
return 0;
}
set
{
CentralMeridian = value / GeographicInfo.Unit.Radians;
}
}
/// <summary>
/// Sets the phi 0 or latitude of origin in radial coordinates
/// </summary>
/// <param name="value">
/// </param>
public double Phi0
{
get
{
if (LatitudeOfOrigin != null)
{
return LatitudeOfOrigin.Value * GeographicInfo.Unit.Radians;
}
return 0;
}
set
{
LatitudeOfOrigin = value / GeographicInfo.Unit.Radians;
}
}
/// <summary>
/// Expresses the entire projection as the Esri well known text format that can be found in .prj files
/// </summary>
/// <returns>
/// The generated string
/// </returns>
public string ToEsriString()
{
Spheroid tempSpheroid = new Spheroid(Proj4Ellipsoid.WGS_1984);
// changed by JK to fix the web mercator auxiliary sphere Esri string
if (Name == "WGS_1984_Web_Mercator_Auxiliary_Sphere")
{
tempSpheroid = GeographicInfo.Datum.Spheroid;
GeographicInfo.Datum.Spheroid = new Spheroid(Proj4Ellipsoid.WGS_1984);
}
// if (_auxiliarySphereType != AuxiliarySphereType.NotSpecified)
// {
// tempSpheroid = _geographicInfo.Datum.Spheroid;
// _geographicInfo.Datum.Spheroid = new Spheroid(Proj4Ellipsoid.WGS_1984);
// }
string result = string.Empty;
if (!IsLatLon)
{
result += String.Format(@"PROJCS[""{0}"",", Name);
}
result += GeographicInfo.ToEsriString();
if (IsLatLon)
{
return result;
}
result += ", ";
if (Transform != null)
{
// Since we can have semi-colon delimited names for aliases, we have to output just one in the WKT. Issue #297
var name = Transform.Name.Contains(";")
? Transform.Name.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)[0]
: Transform.Name;
result += String.Format(@"PROJECTION[""{0}""],", name);
}
if (FalseEasting != null)
{
string alias = _falseEastingAlias ?? "False_Easting";
result += @"PARAMETER[""" + alias + @"""," + Convert.ToString(FalseEasting / Unit.Meters, CultureInfo.InvariantCulture) + "],";
}
if (FalseNorthing != null)
{
string alias = _falseNorthingAlias ?? "False_Northing";
result += @"PARAMETER[""" + alias + @"""," + Convert.ToString(FalseNorthing / Unit.Meters, CultureInfo.InvariantCulture) + "],";
}
if (CentralMeridian != null && CentralMeridianValid())
{
result += @"PARAMETER[""Central_Meridian""," + Convert.ToString(CentralMeridian, CultureInfo.InvariantCulture) + "],";
}
if (StandardParallel1 != null)
{
result += @"PARAMETER[""Standard_Parallel_1""," + Convert.ToString(StandardParallel1, CultureInfo.InvariantCulture) + "],";
}
if (StandardParallel2 != null)
{
result += @"PARAMETER[""Standard_Parallel_2""," + Convert.ToString(StandardParallel2, CultureInfo.InvariantCulture) + "],";
}
if (_scaleFactor != null)
{
result += @"PARAMETER[""Scale_Factor""," + Convert.ToString(_scaleFactor, CultureInfo.InvariantCulture) + "],";
}
if (alpha != null)
{
result += @"PARAMETER[""Azimuth""," + Convert.ToString(alpha, CultureInfo.InvariantCulture) + "],";
}
if (LongitudeOfCenter != null)
{
string alias = _longitudeOfCenterAlias ?? "Longitude_Of_Center";
result += @"PARAMETER[""" + alias + @"""," + Convert.ToString(LongitudeOfCenter, CultureInfo.InvariantCulture) + "],";
}
if (_longitudeOf1st != null)
{
result += @"PARAMETER[""Longitude_Of_1st""," + Convert.ToString(_longitudeOf1st, CultureInfo.InvariantCulture) + "],";
}
if (_longitudeOf2nd != null)
{
result += @"PARAMETER[""Longitude_Of_2nd""," + Convert.ToString(_longitudeOf2nd, CultureInfo.InvariantCulture) + "],";
}
if (LatitudeOfOrigin != null)
{
string alias = _latitudeOfOriginAlias ?? "Latitude_Of_Origin";
result += @"PARAMETER[""" + alias + @"""," + Convert.ToString(LatitudeOfOrigin, CultureInfo.InvariantCulture) + "],";
}
// changed by JK to fix the web mercator auxiliary sphere Esri string
if (Name == "WGS_1984_Web_Mercator_Auxiliary_Sphere")
{
result += @"PARAMETER[""Auxiliary_Sphere_Type""," + ((int)AuxiliarySphereType) + ".0],";
}
result += Unit.ToEsriString() + "]";
// changed by JK to fix the web mercator auxiliary sphere Esri string
if (Name == "WGS_1984_Web_Mercator_Auxiliary_Sphere")
{
GeographicInfo.Datum.Spheroid = new Spheroid(Proj4Ellipsoid.WGS_1984);
GeographicInfo.Datum.Spheroid = tempSpheroid;
}
return result;
}
/// <summary>
/// Using the specified code, this will attempt to look up the related reference information
/// from the appropriate pcs code.
/// </summary>
/// <param name="epsgCode">
/// The epsg Code.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">Throws when there is no projection for given epsg code</exception>
public static ProjectionInfo FromEpsgCode(int epsgCode)
{
return FromAuthorityCode("EPSG", epsgCode);
}
/// <summary>
/// Using the specified code, this will attempt to look up the related reference information from the appropriate authority code.
/// </summary>
/// <param name="authority"> The authority. </param>
/// <param name="code"> The code. </param>
/// <returns>ProjectionInfo</returns>
/// <exception cref="ArgumentOutOfRangeException">Throws when there is no projection for given authority and code</exception>
public static ProjectionInfo FromAuthorityCode(string authority, int code)
{
var pi = AuthorityCodeHandler.Instance[string.Format("{0}:{1}", authority, code)];
if (pi != null)
{
// we need to copy the projection information because the Authority Codes implementation returns its one and only
// in memory copy of the ProjectionInfo. Passing it to the caller might introduce unintended results.
var info = FromProj4String(pi.ToProj4String());
info.Name = pi.Name;
info.NoDefs = true;
info.Authority = authority;
info.AuthorityCode = code;
return info;
}
throw new ArgumentOutOfRangeException("authority", ProjectionMessages.AuthorityCodeNotFound);
}
/// <summary>
/// Parses the entire projection from an Esri string. In some cases, this will have
/// default projection information since only geographic information is obtained.
/// </summary>
/// <param name="esriString">
/// The Esri string to parse
/// </param>
public static ProjectionInfo FromEsriString(string esriString)
{
if (String.IsNullOrWhiteSpace(esriString))
{
// Return a default 'empty' projection
return new ProjectionInfo();
}
//special case for Krovak Projection
//todo use a lookup table instead of hard coding the projection here
if (esriString.Contains("Krovak"))
return KnownCoordinateSystems.Projected.NationalGrids.SJTSKKrovakEastNorth;
var info = new ProjectionInfo();
info.NoDefs = true;
if (!info.TryParseEsriString(esriString))
{
throw new InvalidEsriFormatException(esriString);
}
return info;
}
/// <summary>
/// Creates a new projection and automatically reads in the proj4 string
/// </summary>
/// <param name="proj4String">
/// The proj4String to read in while defining the projection
/// </param>
public static ProjectionInfo FromProj4String(string proj4String)
{
var info = new ProjectionInfo();
info.ParseProj4String(proj4String);
return info;
}
/// <summary>
/// Open a given prj fileName
/// </summary>
/// <param name="prjFilename">
/// </param>
public static ProjectionInfo Open(string prjFilename)
{
string prj = File.ReadAllText(prjFilename);
return FromEsriString(prj);
}
/// <summary>
/// Gets a boolean that is true if the Esri WKT string created by the projections matches.
/// There are multiple ways to write the same projection, but the output Esri WKT string
/// should be a good indicator of whether or not they are the same.
/// </summary>
/// <param name="other">
/// The other projection to compare with.
/// </param>
/// <returns>
/// Boolean, true if the projections are the same.
/// </returns>
public bool Equals(ProjectionInfo other)
{
if (other == null)
{
return false;
}
return ToEsriString().Equals(other.ToEsriString()) || ToProj4String().Equals(other.ToProj4String());
}
/// <summary>
/// If this is a geographic coordinate system, this will show decimal degrees. Otherwise,
/// this will show the linear unit units.
/// </summary>
/// <param name="quantity">
/// The quantity.
/// </param>
/// <returns>
/// The get unit text.
/// </returns>
public string GetUnitText(double quantity)
{
if (Geoc || IsLatLon)
{
if (Math.Abs(quantity) < 1)
{
return "of a decimal degree";
}
return quantity == 1 ? "decimal degree" : "decimal degrees";
}
if (Math.Abs(quantity) < 1)
{
return "of a " + Unit.Name;
}
if (Math.Abs(quantity) == 1)
{
return Unit.Name;
}
if (Math.Abs(quantity) > 1)
{
// The following are frequently followed by specifications, so adding s doesn't work
if (Unit.Name.Contains("Foot") || Unit.Name.Contains("foot"))
{
return Unit.Name
.Replace("Foot", "Feet")
.Replace("foot", "Feet");
}
if (Unit.Name.Contains("Yard") || Unit.Name.Contains("yard"))
{
return Unit.Name
.Replace("Yard", "Yards")
.Replace("yard", "Yards");
}
if (Unit.Name.Contains("Chain") || Unit.Name.Contains("chain"))
{
return Unit.Name
.Replace("Chain", "Chains")
.Replace("chain", "Chains");
}
if (Unit.Name.Contains("Link") || Unit.Name.Contains("link"))
{
return Unit.Name
.Replace("Link", "Links")
.Replace("link", "Links");
}
return Unit.Name + "s";
}
return Unit.Name;
}
/// <summary>
/// Exports this projection info by saving it to a *.prj file.
/// </summary>
/// <param name="prjFilename">
/// The prj file to save to
/// </param>
public void SaveAs(string prjFilename)
{
if (File.Exists(prjFilename))
{
File.Delete(prjFilename);
}
using (StreamWriter sw = File.CreateText(prjFilename))
{
sw.WriteLine(ToEsriString());
}
}
/// <summary>
/// Returns a representaion of this object as a Proj4 string.
/// </summary>
/// <returns>
/// The to proj 4 string.
/// </returns>
public string ToProj4String()
{
//enforce invariant culture
CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var result = new StringBuilder();
Append(result, "x_0", FalseEasting);
Append(result, "y_0", FalseNorthing);
if (_scaleFactor != 1)
{
Append(result, "k_0", _scaleFactor);
}
Append(result, "lat_0", LatitudeOfOrigin);
Append(result, "lon_0", CentralMeridian);
Append(result, "lat_1", StandardParallel1);
Append(result, "lat_2", StandardParallel2);
if (Over)
{
result.Append(" +over");
}
if (Geoc)
{
result.Append(" +geoc");
}
Append(result, "alpha", alpha);
Append(result, "lonc", LongitudeOfCenter);
Append(result, "zone", Zone);
if (IsLatLon)
{
Append(result, "proj", "longlat");
}
else
{
if (Transform != null)
{
Append(result, "proj", Transform.Proj4Name);
}
// skips over to_meter if this is geographic or defaults to 1
if (Unit.Meters != 1)
{
// we don't create +units=m or +units=f instead we use.
Append(result, "to_meter", Unit.Meters);
}
}
result.Append(GeographicInfo.ToProj4String());
if (IsSouth)
{
result.Append(" +south");
}
if (NoDefs)
{
result.Append(" +no_defs");
}
//reset the culture info
Thread.CurrentThread.CurrentCulture = originalCulture;
return result.ToString();
}
/// <summary>
/// This overrides ToString to get the Esri name of the projection.
/// </summary>
/// <returns>
/// The to string.
/// </returns>
public override string ToString()
{
if (!string.IsNullOrEmpty(Name))
{
return Name;
}
if (Transform != null && !string.IsNullOrEmpty(Transform.Name))
{
return Transform.Name;
}
if (IsLatLon)
{
if (GeographicInfo == null || string.IsNullOrEmpty(GeographicInfo.Name))
{
return "LatLon";
}
return GeographicInfo.Name;
}
return ToProj4String();
}
#endregion
#region Methods
private bool CentralMeridianValid()
{
// CentralMeridian (lam0) is calculated for these coordinate system, but IS NOT part of their Esri WKTs
return Transform.Name.ToLower() != "hotine_oblique_mercator_azimuth_natural_origin" &&
Transform.Name.ToLower() != "hotine_oblique_mercator_azimuth_center";
}
private static void Append(StringBuilder result, string name, object value)
{
if (value == null) return;
// The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value.
// This format is supported only for the Single, Double, and BigInteger types.
if (value is double)
{
value = ((double)value).ToString("R", CultureInfo.InvariantCulture);
}
else if (value is float)
{
value = ((float)value).ToString("R", CultureInfo.InvariantCulture);
}
result.AppendFormat(CultureInfo.InvariantCulture, " +{0}={1}", name, value);
}
private static double? GetParameter(string name, string esriString)
{
if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(esriString))
return null;
double? result = null;
int iStart = esriString.IndexOf(@"PARAMETER[""" + name + "\"", StringComparison.InvariantCultureIgnoreCase);
if (iStart >= 0)
{
iStart += 13 + name.Length;
int iEnd = esriString.IndexOf(']', iStart);
string tst = esriString.Substring(iStart, iEnd - iStart);
result = double.Parse(tst, CultureInfo.InvariantCulture);
}
return result;
}
private static double? GetParameter(IEnumerable<string> parameterNames, ref string alias, string esriString)
{
if (parameterNames == null || String.IsNullOrEmpty(esriString))
return null;
// Return the first result that returns a value
foreach (string parameterName in parameterNames)
{
var result = GetParameter(parameterName, esriString);
if (result != null)
{
alias = parameterName;
return result;
}
}
return null;
}
/// <summary>
/// Attempts to parse known parameters from the set of proj4 parameters
/// </summary>
private void ParseProj4String(string proj4String)
{
if (string.IsNullOrEmpty(proj4String))
{
return;
}
// If it has a zone, and the projection is tmerc, it actually needs the utm initialization
var tmercIsUtm = proj4String.Contains("zone=");
if (tmercIsUtm)
{
ScaleFactor = 0.9996; // Default scale factor for utm
// This also needed to write correct Esri String from given projection
}
string[] sections = proj4String.Split('+');
foreach (string str in sections)
{
string s = str.Trim();
if (string.IsNullOrEmpty(s))
{
continue;
}
// single token commands
if (s == "no_defs")
{
NoDefs = true;
continue;
}
if (s == "over")
{
Over = true;
continue;
}
if (s == "geoc")
{
Geoc = GeographicInfo.Datum.Spheroid.EccentricitySquared() != 0;
continue;
}
if (s == "south")
{
IsSouth = true;
continue;
}
if (s == "R_A")
{
//+R_A tells PROJ.4 to use a spherical radius that
//gives a sphere with the same surface area as the original ellipsoid. I
//imagine I added this while trying to get the results to match PCI's GCTP
//based implementation though the history isn't clear on the details.
//the R_A parameter indicates that an authalic auxiliary sphere should be used.
//from http://pdl.perl.org/?docs=Transform/Proj4&title=PDL::Transform::Proj4#r_a
AuxiliarySphereType = AuxiliarySphereType.Authalic;
continue;
}
if (s == "to")
{
// some "+to" parameters exist... e.g., DutchRD. but I'm not sure what to do with them.
// they seem to specify a second projection
Trace.WriteLine(
String.Format("ProjectionInfo.ParseProj4String: command 'to' not supported and the portion of the string after 'to' will not be processed in '{0}'", proj4String));
break;
}
// parameters
string[] set = s.Split('=');
if (set.Length != 2)
{
Trace.WriteLine(
String.Format("ProjectionInfo.ParseProj4String: command '{0}' not understood in '{1}'", s, proj4String));
continue;
}
string name = set[0].Trim();
string value = set[1].Trim();
switch (name)
{
case "lonc":
LongitudeOfCenter = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "alpha":
alpha = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "x_0":
FalseEasting = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "y_0":
FalseNorthing = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "k":
case "k_0":
_scaleFactor = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "lat_0":
LatitudeOfOrigin = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "lat_1":
StandardParallel1 = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "lat_2":
StandardParallel2 = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "lon_0":
CentralMeridian = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "lat_ts":
StandardParallel1 = double.Parse(value, CultureInfo.InvariantCulture);
break;
case "zone":
Zone = int.Parse(value, CultureInfo.InvariantCulture);
break;
case "proj":
if (value == "longlat")
{
IsLatLon = true;
}
Transform = tmercIsUtm
? new UniversalTransverseMercator()
: TransformManager.DefaultTransformManager.GetProj4(value);
break;
case "to_meter":
Unit.Meters = double.Parse(value, CultureInfo.InvariantCulture);
if (Unit.Meters == .3048)
{
Unit.Name = "Foot"; // International Foot
}
else if (Unit.Meters > .3048 && Unit.Meters < .305)
{
Unit.Name = "Foot_US";
}
break;
case "units":
if (value == "m")
{
// do nothing, since the default is meter anyway.
}
else if (value == "ft" || value == "f")
{
Unit.Name = "Foot";
Unit.Meters = .3048;
}
else if (value == "us-ft")
{
Unit.Name = "Foot_US";
Unit.Meters = .304800609601219;
}
break;
case "pm":
GeographicInfo.Meridian.pm = value;
//// added by Jiri Kadlec - pm should also specify the CentralMeridian
//if (value != null)
//{
// CentralMeridian = GeographicInfo.Meridian.Longitude;
//}
break;
case "datum":
// Even though th ellipsoid is set by its known definition, we permit overriding it with a specifically defined ellps parameter
GeographicInfo.Datum = new Datum(value);
break;
case "nadgrids":
GeographicInfo.Datum.NadGrids = value.Split(',');
if (value != "@null")
{
GeographicInfo.Datum.DatumType = DatumType.GridShift;
}
break;
case "towgs84":
GeographicInfo.Datum.InitializeToWgs84(value.Split(','));
break;
case "ellps":
// Even though th ellipsoid is set by its known definition, we permit overriding it with a specifically defined ellps parameter
// generally ellps will not be used in the same string as a,b,rf,R.
GeographicInfo.Datum.Spheroid = new Spheroid(value);
break;
case "a":
case "R":
GeographicInfo.Datum.Spheroid.EquatorialRadius = double.Parse(value, CultureInfo.InvariantCulture);
GeographicInfo.Datum.Spheroid.KnownEllipsoid = Proj4Ellipsoid.Custom; // This will provide same spheroid on export to Proj4 string
break;
case "b":
GeographicInfo.Datum.Spheroid.PolarRadius = double.Parse(value, CultureInfo.InvariantCulture);
GeographicInfo.Datum.Spheroid.KnownEllipsoid = Proj4Ellipsoid.Custom; // This will provide same spheroid on export to Proj4 string
break;
case "rf":
Debug.Assert(GeographicInfo.Datum.Spheroid.EquatorialRadius > 0, "a must appear before rf");
GeographicInfo.Datum.Spheroid.InverseFlattening = double.Parse(
value, CultureInfo.InvariantCulture);
break;
default:
Trace.WriteLine(string.Format("Unrecognized parameter skipped {0}.", name));
break;
}
}
if (Transform != null)
{
Transform.Init(this);
}
}
/// <summary>
/// This will try to read the string, but if the validation fails, then it will return false,
/// rather than throwing an exception.
/// </summary>
/// <param name="esriString">
/// The string to test and define this projection if possible.
/// </param>
/// <returns>
/// Boolean, true if at least the GEOGCS tag was found.
/// </returns>
public bool TryParseEsriString(string esriString)
{
if (esriString == null)
{
return false;
}
if (!esriString.Contains("GEOGCS"))
{
return false;
}
if (esriString.Contains("PROJCS") == false)
{
GeographicInfo.ParseEsriString(esriString);
IsLatLon = true;
Transform = new LongLat();
Transform.Init(this);
return true;
}
int iStart = esriString.IndexOf(@""",", StringComparison.Ordinal);
Name = esriString.Substring(8, iStart - 8);
int iEnd = esriString.IndexOf("PARAMETER", StringComparison.Ordinal);
string gcs;
if (iEnd != -1)
{
gcs = esriString.Substring(iStart + 1, iEnd - (iStart + 2));
}
else
{
// an odd Esri projection string that doesn't have PARAMETER
gcs = esriString.Substring(iStart + 1);
}
GeographicInfo.ParseEsriString(gcs);
FalseEasting = GetParameter(new string[] { "False_Easting", "Easting_At_False_Origin" }, ref _falseEastingAlias, esriString);
FalseNorthing = GetParameter(new string[] { "False_Northing", "Northing_At_False_Origin" }, ref _falseNorthingAlias, esriString);
CentralMeridian = GetParameter("Central_Meridian", esriString);
// Esri seems to indicate that these should be treated the same, but they aren't here... http://support.esri.com/en/knowledgebase/techarticles/detail/39992
// CentralMeridian = GetParameter(new string[] { "Longitude_Of_Center", "Central_Meridian", "Longitude_Of_Origin" }, ref LongitudeOfCenterAlias, esriString);
LongitudeOfCenter = GetParameter("Longitude_Of_Center", esriString);
StandardParallel1 = GetParameter("Standard_Parallel_1", esriString);
StandardParallel2 = GetParameter("Standard_Parallel_2", esriString);
_scaleFactor = GetParameter("Scale_Factor", esriString);
alpha = GetParameter("Azimuth", esriString);
_longitudeOf1st = GetParameter("Longitude_Of_1st", esriString);
_longitudeOf2nd = GetParameter("Longitude_Of_2nd", esriString);
LatitudeOfOrigin = GetParameter(new[] { "Latitude_Of_Origin", "Latitude_Of_Center", "Central_Parallel" }, ref _latitudeOfOriginAlias, esriString);
iStart = esriString.LastIndexOf("UNIT", StringComparison.Ordinal);
string unit = esriString.Substring(iStart, esriString.Length - iStart);
Unit.ParseEsriString(unit);
if (esriString.Contains("PROJECTION"))
{
iStart = esriString.IndexOf("PROJECTION", StringComparison.Ordinal) + 12;
iEnd = esriString.IndexOf("]", iStart, StringComparison.Ordinal) - 1;
string projection = esriString.Substring(iStart, iEnd - iStart);
Transform = TransformManager.DefaultTransformManager.GetProjection(projection);
Transform.Init(this);
}
double? auxType = GetParameter("Auxiliary_Sphere_Type", esriString);
if (auxType != null)
{
// While the Esri implementation sort of tip-toes around the datum transform,
// we simply ensure that the spheroid becomes properly spherical based on the
// parameters we have here. (The sphereoid will be read as WGS84).
AuxiliarySphereType = (AuxiliarySphereType)auxType;
if (AuxiliarySphereType == AuxiliarySphereType.SemimajorAxis)
{
// added by Jiri to properly re-initialize the 'web mercator auxiliary sphere' transform
Transform = KnownCoordinateSystems.Projected.World.WebMercator.Transform;
}
else if (AuxiliarySphereType == AuxiliarySphereType.SemiminorAxis)
{
double r = GeographicInfo.Datum.Spheroid.PolarRadius;
GeographicInfo.Datum.Spheroid = new Spheroid(r);
}
else if (AuxiliarySphereType == AuxiliarySphereType.Authalic
|| AuxiliarySphereType == AuxiliarySphereType.AuthalicWithConvertedLatitudes)
{
double a = GeographicInfo.Datum.Spheroid.EquatorialRadius;
double b = GeographicInfo.Datum.Spheroid.PolarRadius;
double r =
Math.Sqrt(
(a * a
+
a * b * b
/ (Math.Sqrt(a * a - b * b) * Math.Log((a + Math.Sqrt(a * a - b * b)) / b, Math.E)))
/ 2);
GeographicInfo.Datum.Spheroid = new Spheroid(r);
}
}
if (FalseEasting != null)
{
FalseEasting = FalseEasting * Unit.Meters;
}
if (FalseNorthing != null)
{
FalseNorthing = FalseNorthing * Unit.Meters;
}
return true;
}
#endregion
#region IEsriString Members
/// <summary>
/// Re-sets the parameters of this projection info by parsing the esri projection string
/// </summary>
/// <param name="esriString">The projection information string in Esri WKT format</param>
public void ParseEsriString(string esriString)
{
TryParseEsriString(esriString);
}
#endregion
}
}
| |
#if !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
#define UNITY_4_3_AND_LATER
#endif
#if (UNITY_2_6 || UNITY_2_6_1 || UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4)
#define ONLY_SINGLE_SELECTION_SUPPORTED_IN_INSPECTOR
#endif
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
//-------------------------------------------------------------------------
/// <summary>
/// Editor class for the AlphaMeshCollider component.
/// </summary>
[CustomEditor(typeof(AlphaMeshCollider))]
[CanEditMultipleObjects]
public class EditorScriptAlphaMeshCollider : Editor {
protected float mOldAlphaThreshold = 0;
protected int mOldTargetColliderTypeEnumIndex = 0;
protected bool mOldFlipNormals = false;
protected bool mFlipHorizontalChanged = false;
protected bool mFlipVerticalChanged = false;
protected bool mOldConvex = false;
protected int mOldPointCount = 0;
protected float mOldThickness = 0;
protected float mOldDistanceTolerance = 0;
protected float mOldCustomRotation = 0.0f;
protected Vector2 mOldCustomScale = Vector2.one;
protected Vector3 mOldCustomOffset = Vector3.zero;
protected bool mOldIsCustomAtlasRegionUsed = false;
public float mOldCustomAtlasFrameRotation = 0.0f;
protected bool mLiveUpdate = true;
protected bool mShowAdvanced = false;
protected bool mShowTextureRegionSection = false;
protected bool mShowHolesAndIslandsSection = false;
protected Texture2D mOldCustomTex = null;
protected int mPointCountSliderMax = 100;
SerializedProperty targetLiveUpdate;
SerializedProperty targetAlphaOpaqueThreshold;
SerializedProperty targetFlipNormals;
SerializedProperty targetConvex;
//SerializedProperty targetMaxPointCount;
SerializedProperty targetVertexReductionDistanceTolerance;
SerializedProperty targetThickness;
SerializedProperty targetHasOTSpriteComponent;
SerializedProperty targetHasOTTilesSpriteComponent;
SerializedProperty targetTargetColliderType;
SerializedProperty targetCopyOTSpriteFlipping;
SerializedProperty targetCustomRotation;
SerializedProperty targetCustomScale;
SerializedProperty targetCustomOffset;
SerializedProperty targetIsCustomAtlasRegionUsed;
SerializedProperty targetCustomAtlasFrameRotation;
//-------------------------------------------------------------------------
enum OTTilesSpriteSelectionStatus {
NONE = 0,
MIXED,
ALL
}
//-------------------------------------------------------------------------
class DuplicatePermittingIntComparer : IComparer<int> {
public int Compare(int x, int y) {
if (x > y)
return -1;
else
return 1;
}
}
//-------------------------------------------------------------------------
[MenuItem ("2D ColliderGen/Add AlphaMeshCollider", false, 10)]
static void ColliderGenAddAlphaMeshCollider() {
foreach (GameObject gameObj in Selection.gameObjects) {
AlphaMeshCollider alphaCollider = gameObj.GetComponent<AlphaMeshCollider>();
if (alphaCollider == null) {
alphaCollider = gameObj.AddComponent<AlphaMeshCollider>();
}
}
}
//-------------------------------------------------------------------------
// Validation function for the function above.
[MenuItem ("2D ColliderGen/Add AlphaMeshCollider", true)]
static bool ValidateColliderGenAddAlphaMeshCollider() {
if (Selection.gameObjects.Length == 0) {
return false;
}
else {
foreach (GameObject gameObj in Selection.gameObjects) {
Component tk2dSprite = gameObj.GetComponent("tk2dBaseSprite");
if (tk2dSprite != null) {
return false;
}
}
return true; // no tk2dSprite selected
}
}
//-------------------------------------------------------------------------
[MenuItem ("2D ColliderGen/Select AlphaMeshCollider Children", false, 11)]
static void ColliderGenSelectChildAlphaMeshColliders() {
SelectChildAlphaMeshColliders(Selection.gameObjects);
}
//-------------------------------------------------------------------------
// Validation function for the function above.
[MenuItem ("2D ColliderGen/Remove AlphaMeshCollider Components", true)]
static bool ValidateColliderGenRemoveColliderAndGenerator() {
return (Selection.gameObjects.Length > 0);
}
//-------------------------------------------------------------------------
[MenuItem ("2D ColliderGen/Remove AlphaMeshCollider Components", false, 11)]
static void ColliderGenRemoveColliderAndGenerator() {
RemoveColliderAndGenerator(Selection.gameObjects);
}
//-------------------------------------------------------------------------
// Validation function for the function above.
[MenuItem ("2D ColliderGen/Select AlphaMeshCollider Children", true)]
static bool ValidateColliderGenSelectChildAlphaMeshColliders() {
return (Selection.gameObjects.Length > 0);
}
//-------------------------------------------------------------------------
void OnEnable() {
// Setup the SerializedProperties
targetLiveUpdate = serializedObject.FindProperty("mRegionIndependentParameters.mLiveUpdate");
targetAlphaOpaqueThreshold = serializedObject.FindProperty("mRegionIndependentParameters.mAlphaOpaqueThreshold");
targetFlipNormals = serializedObject.FindProperty("mRegionIndependentParameters.mFlipInsideOutside");
targetConvex = serializedObject.FindProperty("mRegionIndependentParameters.mConvex");
//targetMaxPointCount = serializedObject.FindProperty("mMaxPointCount");
targetVertexReductionDistanceTolerance = serializedObject.FindProperty("mRegionIndependentParameters.mVertexReductionDistanceTolerance");
targetThickness = serializedObject.FindProperty("mRegionIndependentParameters.mThickness");
#if UNITY_4_3_AND_LATER
targetTargetColliderType = serializedObject.FindProperty("mRegionIndependentParameters.mTargetColliderType");
#endif
targetHasOTSpriteComponent = serializedObject.FindProperty("mHasOTSpriteComponent");
targetHasOTTilesSpriteComponent = serializedObject.FindProperty("mHasOTTilesSpriteComponent");
targetCopyOTSpriteFlipping = serializedObject.FindProperty("mRegionIndependentParameters.mCopyOTSpriteFlipping");
targetCustomRotation = serializedObject.FindProperty("mRegionIndependentParameters.mCustomRotation");
targetCustomScale = serializedObject.FindProperty("mRegionIndependentParameters.mCustomScale");
targetCustomOffset = serializedObject.FindProperty("mRegionIndependentParameters.mCustomOffset");
targetIsCustomAtlasRegionUsed = serializedObject.FindProperty("mRegionIndependentParameters.mIsCustomAtlasRegionUsed");
targetCustomAtlasFrameRotation = serializedObject.FindProperty("mRegionIndependentParameters.mCustomAtlasFrameRotation");
mPointCountSliderMax = AlphaMeshColliderPreferences.Instance.ColliderPointCountSliderMaxValue;
}
//-------------------------------------------------------------------------
// Newer multi-selection version.
public override void OnInspectorGUI() {
//EditorGUIUtility.LookLikeInspector();
// Update the serializedProperty - needed in the beginning of OnInspectorGUI.
serializedObject.Update();
mOldAlphaThreshold = targetAlphaOpaqueThreshold.floatValue;
#if UNITY_4_3_AND_LATER
mOldTargetColliderTypeEnumIndex = targetTargetColliderType.enumValueIndex;
#endif
mOldFlipNormals = targetFlipNormals.boolValue;
mOldConvex = targetConvex.boolValue;
mOldThickness = targetThickness.floatValue;
mOldDistanceTolerance = targetVertexReductionDistanceTolerance.floatValue;
mOldCustomRotation = targetCustomRotation.floatValue;
mOldCustomScale = targetCustomScale.vector2Value;
mOldCustomOffset = targetCustomOffset.vector3Value;
mOldIsCustomAtlasRegionUsed = targetIsCustomAtlasRegionUsed.boolValue;
mOldCustomAtlasFrameRotation = targetCustomAtlasFrameRotation.floatValue;
Texture2D usedTexture = null;
bool usedTextureIsCustomTex = false;
bool areUsedTexturesDifferent = false;
bool areOutputDirectoriesDifferent = false;
bool areOutputFilenamesDifferent = false;
bool areGroupSuffixesDifferent = false;
float imageMinExtent = 128;
string commonOutputDirectoryPath = null;
string commonOutputFilename = null;
string commonGroupSuffix = null;
Texture2D commonCustomTexture = null;
bool areCustomTexturesDifferent = false;
Vector2 commonCustomAtlasFramePositionInPixels = Vector2.zero;
Vector2 commonCustomAtlasFrameSizeInPixels = Vector2.zero;
bool isCommonCustomAtlasFramePositionInPixelsDifferent = false;
bool isCommonCustomAtlasFrameSizeInPixelsDifferent = false;
bool hasCommonCustomAtlasFramePositionInPixelsChanged = false;
bool hasCommonCustomAtlasFrameSizeInPixelsChanged = false;
int numObjectsWithSmoothMovesBoneAnimationParent = 0;
bool allHaveSmoothMovesBoneAnimationParent = false;
bool commonApplySmoothMovesScaleAnim = false;
bool isApplySmoothMovesScaleAnimDifferent = false;
bool hasCommonApplySmoothMovesScaleAnimChanged = false;
bool haveColliderRegionEnabledChanged = false;
bool haveColliderRegionMaxPointCountChanged = false;
bool haveColliderRegionConvexChanged = false;
int commonFirstEnabledMaxPointCount = 0;
bool isFirstEnabledMaxPointCountDifferent = false;
bool hasFirstEnabledMaxPointCountChanged = false;
bool isAtlas = false;
bool canReloadAnyCollider = false;
bool canRecalculateAnyCollider = false;
bool anyColliderWithoutActiveIslandsOrHoles = false; // if we have no active islands/holes currently in any of the selected objects OR have no island ticked in the inspector menu.
OTTilesSpriteSelectionStatus otTilesSpriteSelectionStatus = OTTilesSpriteSelectionStatus.NONE;
Object[] targetObjects = serializedObject.targetObjects;
SortedDictionary<int, AlphaMeshCollider> sortedTargets = SortAlphaMeshColliders(targetObjects);
areUsedTexturesDifferent = AreUsedTexturesDifferent(sortedTargets);
AlphaMeshCollider targetObject;
for (int targetIndex = 0; targetIndex != targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
Texture2D currentTexture = targetObject.UsedTexture;
usedTextureIsCustomTex = (targetObject.CustomTex != null);
isAtlas = targetObject.mIsAtlasUsed;
int textureWidth = targetObject.UsedTexture != null ? targetObject.UsedTexture.width : 0;
int textureHeight = targetObject.UsedTexture != null ? targetObject.UsedTexture.height : 0;
imageMinExtent = Mathf.Min(imageMinExtent, Mathf.Min(textureWidth, textureHeight));
if (targetObject.CanReloadCollider)
canReloadAnyCollider = true;
if (targetObject.CanRecalculateCollider)
canRecalculateAnyCollider = true;
// set commonOutputDirectoryPath and areOutputDirectoriesDifferent
if (commonOutputDirectoryPath != null && !commonOutputDirectoryPath.Equals(targetObject.ColliderMeshDirectory)) {
areOutputDirectoriesDifferent = true;
}
else {
commonOutputDirectoryPath = targetObject.ColliderMeshDirectory;
}
// set commonGroupSuffix and areGroupSuffixesDifferent
if (commonGroupSuffix != null && !commonGroupSuffix.Equals(targetObject.GroupSuffix)) {
areGroupSuffixesDifferent = true;
}
else {
commonGroupSuffix = targetObject.GroupSuffix;
}
// set commonOutputFilename and areOutputFilenamesDifferent
if (commonOutputFilename != null && !commonOutputFilename.Equals(targetObject.mColliderMeshFilename)) {
areOutputFilenamesDifferent = true;
}
else {
commonOutputFilename = targetObject.mColliderMeshFilename;
}
// set commonCustomTexture and areCustomTexturesDifferent
if (commonCustomTexture != null && commonCustomTexture != targetObject.CustomTex) {
areCustomTexturesDifferent = true;
}
else {
commonCustomTexture = targetObject.CustomTex;
}
if (!usedTexture) {
usedTexture = currentTexture;
}
// set commonCustomAtlasFramePositionInPixels
if (targetIndex != 0 && commonCustomAtlasFramePositionInPixels != targetObject.CustomAtlasFramePositionInPixels) {
isCommonCustomAtlasFramePositionInPixelsDifferent = true;
}
else {
commonCustomAtlasFramePositionInPixels = targetObject.CustomAtlasFramePositionInPixels;
}
// set commonCustomAtlasFrameSizeInPixels
if (targetIndex != 0 && commonCustomAtlasFrameSizeInPixels != targetObject.CustomAtlasFrameSizeInPixels) {
isCommonCustomAtlasFrameSizeInPixelsDifferent = true;
}
else {
commonCustomAtlasFrameSizeInPixels = targetObject.CustomAtlasFrameSizeInPixels;
}
// set numObjectsWithSmoothMovesBoneAnimationParent
if (targetObject.HasSmoothMovesBoneAnimationParent) {
++numObjectsWithSmoothMovesBoneAnimationParent;
}
// set commonApplySmoothMovesScaleAnim
if (targetIndex != 0 && commonApplySmoothMovesScaleAnim != targetObject.ApplySmoothMovesScaleAnim) {
isApplySmoothMovesScaleAnimDifferent = true;
}
else {
commonApplySmoothMovesScaleAnim = targetObject.ApplySmoothMovesScaleAnim;
}
if (targetIndex != 0 && commonFirstEnabledMaxPointCount != targetObject.MaxPointCountOfFirstEnabledRegion) {
isFirstEnabledMaxPointCountDifferent = true;
}
else {
commonFirstEnabledMaxPointCount = targetObject.MaxPointCountOfFirstEnabledRegion;
}
}
// set otTilesSpriteSelectionStatus
if (targetHasOTTilesSpriteComponent.hasMultipleDifferentValues) {
otTilesSpriteSelectionStatus = OTTilesSpriteSelectionStatus.MIXED;
}
else if (targetHasOTTilesSpriteComponent.boolValue == true) {
otTilesSpriteSelectionStatus = OTTilesSpriteSelectionStatus.ALL;
}
else {
otTilesSpriteSelectionStatus = OTTilesSpriteSelectionStatus.NONE;
}
// set allHaveSmoothMovesBoneAnimationParent
if (numObjectsWithSmoothMovesBoneAnimationParent == targetObjects.Length) {
allHaveSmoothMovesBoneAnimationParent = true;
}
else {
allHaveSmoothMovesBoneAnimationParent = false;
}
PrepareColliderRegionsIfOldVersion(sortedTargets);
if (!areUsedTexturesDifferent) {
if (usedTexture == null) {
EditorGUILayout.LabelField("No Texture Image", "Set Advanced/Custom Image");
}
else {
Rect textureImageRect = GUILayoutUtility.GetRect(50, 50);
if (usedTextureIsCustomTex) {
EditorGUI.LabelField(textureImageRect, new GUIContent("Custom Image"), new GUIContent(usedTexture));
}
else {
if (otTilesSpriteSelectionStatus == OTTilesSpriteSelectionStatus.ALL) {
EditorGUI.LabelField(textureImageRect, new GUIContent("OTTilesSprite"), new GUIContent(usedTexture));
}
else if (isAtlas) {
EditorGUI.LabelField(textureImageRect, new GUIContent("Atlas / SpriteSheet"), new GUIContent(usedTexture));
}
else {
EditorGUI.LabelField(textureImageRect, new GUIContent("Texture Image"), new GUIContent(usedTexture));
}
}
EditorGUILayout.LabelField("Texture Width x Height: ", usedTexture.width.ToString() + " x " + usedTexture.height.ToString());
}
}
else {
EditorGUILayout.LabelField("Texture Image", "<different textures selected>");
}
if (canRecalculateAnyCollider) {
if (otTilesSpriteSelectionStatus == OTTilesSpriteSelectionStatus.NONE) {
EditorGUILayout.PropertyField(targetLiveUpdate, new GUIContent("Editor Live Update"));
}
// float [0..1] Alpha Opaque Threshold
EditorGUILayout.Slider(targetAlphaOpaqueThreshold, 0.0f, 1.0f, "Alpha Opaque Threshold");
// int [3..100] max point count
//EditorGUILayout.IntSlider(targetMaxPointCount, 3, mPointCountSliderMax, "Outline Vertex Count");
if (!isFirstEnabledMaxPointCountDifferent) {
bool noIslandOrHoleActive = (commonFirstEnabledMaxPointCount == 0);
string outlineVertexCountLabelString = noIslandOrHoleActive ? "No Holes or Islands Active" : "Outline Vertex Count";
int newFirstEnabledMaxPointCount = EditorGUILayout.IntSlider(outlineVertexCountLabelString, commonFirstEnabledMaxPointCount, 3, mPointCountSliderMax);
hasFirstEnabledMaxPointCountChanged = newFirstEnabledMaxPointCount != commonFirstEnabledMaxPointCount;
if (hasFirstEnabledMaxPointCountChanged) {
for (int targetIndex = 0; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
targetObject.MaxPointCountOfFirstEnabledRegion = newFirstEnabledMaxPointCount;
}
}
}
else {
EditorGUILayout.LabelField("Outline Vertex Count", "<different values>");
}
// removed, since it was not too intuitive to use.
// float [0..0.3] Accepted Distance
//EditorGUILayout.Slider(targetVertexReductionDistanceTolerance, 0.0f, 0.3f, "Accepted Distance");
// float thickness
EditorGUILayout.PropertyField(targetThickness, new GUIContent("Z-Thickness"));
}
if (canReloadAnyCollider || canRecalculateAnyCollider) {
#if UNITY_4_3_AND_LATER
// collider type enum
EditorGUILayout.PropertyField(targetTargetColliderType, new GUIContent("Collider Type"));
#endif
// copy OT sprite flipping
bool showFlipProperties = true;
if (!targetHasOTSpriteComponent.hasMultipleDifferentValues &&
targetHasOTSpriteComponent.boolValue == true) {
//targetObject.mCopyOTSpriteFlipping = EditorGUILayout.Toggle("Copy OTSprite Flipping", targetObject.mCopyOTSpriteFlipping);
EditorGUILayout.PropertyField(targetCopyOTSpriteFlipping, new GUIContent("Copy OTSprite Flipping"));
if (targetCopyOTSpriteFlipping.boolValue == true) {
showFlipProperties = false;
}
}
if (showFlipProperties) {
bool areFlipHorizontalDifferent = false;
bool areFlipVerticalDifferent = false;
mFlipHorizontalChanged = false;
mFlipVerticalChanged = false;
targetObject = (AlphaMeshCollider) targetObjects[0];
bool flipHorizontal = targetObject.FlipHorizontal;
bool flipVertical = targetObject.FlipVertical;
for (int targetIndex = 1; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
bool currentFlipHorizontal = targetObject.FlipHorizontal;
bool currentFlipVertical = targetObject.FlipVertical;
if (currentFlipHorizontal != flipHorizontal)
areFlipHorizontalDifferent = true;
if (currentFlipVertical != flipVertical)
areFlipVerticalDifferent = true;
}
// flip horizontal
bool newFlipHorizontal = false;
if (!areFlipHorizontalDifferent) {
newFlipHorizontal = EditorGUILayout.Toggle("Flip Horizontal", flipHorizontal);
if (newFlipHorizontal != flipHorizontal) {
mFlipHorizontalChanged = true;
for (int targetIndex = 0; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
targetObject.FlipHorizontal = newFlipHorizontal;
}
}
}
else {
EditorGUILayout.LabelField("Flip Horizontal", "<different values>");
}
// flip vertical
bool newFlipVertical = false;
if (!areFlipVerticalDifferent) {
newFlipVertical = EditorGUILayout.Toggle("Flip Vertical", flipVertical);
if (newFlipVertical != flipVertical) {
mFlipVerticalChanged = true;
for (int targetIndex = 0; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
targetObject.FlipVertical = newFlipVertical;
}
}
}
else {
EditorGUILayout.LabelField("Flip Vertical", "<different values>");
}
}
EditorGUILayout.PropertyField(targetConvex, new GUIContent("Force Convex"));
EditorGUILayout.PropertyField(targetFlipNormals, new GUIContent("Flip Normals"));
if (allHaveSmoothMovesBoneAnimationParent) {
if (!isApplySmoothMovesScaleAnimDifferent) {
bool newApplySmoothMovesScaleAnim = EditorGUILayout.Toggle("SmoothMoves Scale Anim", commonApplySmoothMovesScaleAnim);
hasCommonApplySmoothMovesScaleAnimChanged = newApplySmoothMovesScaleAnim != commonApplySmoothMovesScaleAnim;
if (hasCommonApplySmoothMovesScaleAnimChanged) {
for (int targetIndex = 0; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
targetObject.ApplySmoothMovesScaleAnim = newApplySmoothMovesScaleAnim;
}
}
}
else {
EditorGUILayout.LabelField("SmoothMoves Scale Anim", "<different values>");
}
}
}
// output directory
string newOutputDirectoryPath = null;
if (!areOutputDirectoriesDifferent) {
newOutputDirectoryPath = EditorGUILayout.TextField("Output Directory", commonOutputDirectoryPath);
}
else {
newOutputDirectoryPath = EditorGUILayout.TextField("Output Directory", "<different values>");
}
if (!newOutputDirectoryPath.Equals(commonOutputDirectoryPath) && !newOutputDirectoryPath.Equals("<different values>")) {
for (int targetIndex = 0; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
targetObject.ColliderMeshDirectory = newOutputDirectoryPath;
}
}
// group suffix
string newGroupSuffix = null;
if (!areGroupSuffixesDifferent) {
newGroupSuffix = EditorGUILayout.TextField("Group Suffix", commonGroupSuffix);
}
else {
newGroupSuffix = EditorGUILayout.TextField("Group Suffix", "<different values>");
}
if (!newGroupSuffix.Equals(commonGroupSuffix) && !newGroupSuffix.Equals("<different values>")) {
for (int targetIndex = 0; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
targetObject.GroupSuffix = newGroupSuffix;
}
}
if (otTilesSpriteSelectionStatus == OTTilesSpriteSelectionStatus.NONE) {
// output filename (read-only)
if (!areOutputFilenamesDifferent) {
EditorGUILayout.TextField("Output Filename", commonOutputFilename);
}
else {
EditorGUILayout.TextField("Output Filename", "<different values>");
}
}
// Advanced settings
mShowAdvanced = EditorGUILayout.Foldout(mShowAdvanced, "Advanced Settings");
if(mShowAdvanced) {
EditorGUI.indentLevel++;
Texture2D newCustomTexture = null;
if (!areCustomTexturesDifferent) {
newCustomTexture = (Texture2D) EditorGUILayout.ObjectField("Custom Image", commonCustomTexture, typeof(Texture2D), false);
if (newCustomTexture != commonCustomTexture) {
for (int targetIndex = 0; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
targetObject.CustomTex = newCustomTexture;
}
sortedTargets = SortAlphaMeshColliders(targetObjects); // path hash values are outdated - recalculate them!
areUsedTexturesDifferent = AreUsedTexturesDifferent(sortedTargets);
ReloadOrRecalculateSelectedColliders(sortedTargets);
}
}
else {
EditorGUILayout.LabelField("Custom Image", "<different images selected>");
}
EditorGUILayout.Slider(targetCustomRotation, 0.0f, 360.0f, new GUIContent("Custom Rotation"));
EditorGUI.indentLevel++; // provide some space for the vector foldout triangles
EditorGUILayout.PropertyField(targetCustomScale, new GUIContent("Custom Scale"), true);
EditorGUILayout.PropertyField(targetCustomOffset, new GUIContent("Custom Offset"), true);
EditorGUI.indentLevel--;
EditorGUI.indentLevel--;
}
// custom texture region part
if (otTilesSpriteSelectionStatus == OTTilesSpriteSelectionStatus.NONE) {
mShowTextureRegionSection = EditorGUILayout.Foldout(mShowTextureRegionSection, "Custom Texture Region");
if(mShowTextureRegionSection) {
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(targetIsCustomAtlasRegionUsed, new GUIContent("Use Custom Region"));
bool showCustomAtlasRegionParams = false;
if (targetIsCustomAtlasRegionUsed.boolValue == true) {
showCustomAtlasRegionParams = true;
}
if (showCustomAtlasRegionParams) {
if (!isCommonCustomAtlasFramePositionInPixelsDifferent) {
Vector2 newCommonCustomAtlasFramePositionInPixels = EditorGUILayout.Vector2Field("Position", commonCustomAtlasFramePositionInPixels);
hasCommonCustomAtlasFramePositionInPixelsChanged = newCommonCustomAtlasFramePositionInPixels != commonCustomAtlasFramePositionInPixels;
if (hasCommonCustomAtlasFramePositionInPixelsChanged) {
for (int targetIndex = 0; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
targetObject.CustomAtlasFramePositionInPixels = newCommonCustomAtlasFramePositionInPixels;
}
}
}
else {
EditorGUILayout.LabelField("Position", "<different values>");
}
if (!isCommonCustomAtlasFrameSizeInPixelsDifferent) {
Vector2 newCommonCustomAtlasFrameSizeInPixels = EditorGUILayout.Vector2Field("Size", commonCustomAtlasFrameSizeInPixels);
hasCommonCustomAtlasFrameSizeInPixelsChanged = newCommonCustomAtlasFrameSizeInPixels != commonCustomAtlasFrameSizeInPixels;
if (hasCommonCustomAtlasFrameSizeInPixelsChanged) {
for (int targetIndex = 0; targetIndex < targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
targetObject.CustomAtlasFrameSizeInPixels = newCommonCustomAtlasFrameSizeInPixels;
}
}
}
else {
EditorGUILayout.LabelField("Size", "<different values>");
}
}
EditorGUI.indentLevel--;
}
}
// holes and islands part
if (!areUsedTexturesDifferent && otTilesSpriteSelectionStatus == OTTilesSpriteSelectionStatus.NONE) {
OnInspectorGuiHolesAndIslandsSection(out haveColliderRegionEnabledChanged, out haveColliderRegionMaxPointCountChanged, out haveColliderRegionConvexChanged, targetObjects);
}
// check if we now have no islands/holes selected
for (int targetIndex = 0; targetIndex != targetObjects.Length; ++targetIndex) {
targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
if (targetObject.NumEnabledColliderRegions == 0) {
anyColliderWithoutActiveIslandsOrHoles = true;
}
}
// Apply changes to the serializedProperty.
serializedObject.ApplyModifiedProperties();
//mLiveUpdate = sortedTargets.Values[0].RegionIndependentParams.LiveUpdate;
SortedDictionary<int, AlphaMeshCollider>.Enumerator firstTargetEnumerator = sortedTargets.GetEnumerator();
firstTargetEnumerator.MoveNext();
AlphaMeshCollider firstTarget = firstTargetEnumerator.Current.Value;
mLiveUpdate = firstTarget.RegionIndependentParams.LiveUpdate;
if (otTilesSpriteSelectionStatus != OTTilesSpriteSelectionStatus.NONE) {
mLiveUpdate = false;
}
EditorGUILayout.BeginHorizontal();
if (otTilesSpriteSelectionStatus == OTTilesSpriteSelectionStatus.ALL) {
if (GUILayout.Button("Recalculate Tile Colliders")) {
RecalculateOTTilesSpriteColliders(sortedTargets);
}
}
else {
if (canReloadAnyCollider)
{
if (GUILayout.Button("Reload Collider")) {
ReloadSelectedColliders(sortedTargets);
}
}
if (canRecalculateAnyCollider) {
if (GUILayout.Button("Recalculate Collider")) {
RecalculateSelectedColliders(sortedTargets);
}
}
}
EditorGUILayout.EndHorizontal();
if (mLiveUpdate) {
bool isCompleteRecalculationRequired = false;
bool isRecalculationFromPreviousResultRequired = false;
bool isRewriteRequired = false;
//bool pointCountNeedsUpdate = ((mOldPointCount != targetMaxPointCount.intValue) && (targetMaxPointCount.intValue > 2)); // when typing 28, it would otherwise update at the first digit '2'.
bool pointCountNeedsUpdate = hasFirstEnabledMaxPointCountChanged || haveColliderRegionMaxPointCountChanged;
if (pointCountNeedsUpdate ||
haveColliderRegionConvexChanged ||
mOldConvex != targetConvex.boolValue ||
mOldThickness != targetThickness.floatValue ||
mOldDistanceTolerance != targetVertexReductionDistanceTolerance.floatValue) {
isRecalculationFromPreviousResultRequired = true;
}
if (mOldConvex != targetConvex.boolValue) {
isCompleteRecalculationRequired = true; // TODO: this part is not efficient, we should set the property instead of the value directly and then act based on it.
}
if (mOldAlphaThreshold != targetAlphaOpaqueThreshold.floatValue ||
mOldFlipNormals != targetFlipNormals.boolValue ||
hasCommonApplySmoothMovesScaleAnimChanged) {
isCompleteRecalculationRequired = true;
}
if (mOldIsCustomAtlasRegionUsed != targetIsCustomAtlasRegionUsed.boolValue ||
hasCommonCustomAtlasFramePositionInPixelsChanged ||
hasCommonCustomAtlasFrameSizeInPixelsChanged ||
mOldCustomAtlasFrameRotation != targetCustomAtlasFrameRotation.floatValue) {
isCompleteRecalculationRequired = true;
}
if (haveColliderRegionEnabledChanged) {
isCompleteRecalculationRequired = true;
}
if (mOldCustomRotation != targetCustomRotation.floatValue ||
mOldCustomScale != targetCustomScale.vector2Value ||
mOldCustomOffset != targetCustomOffset.vector3Value
#if UNITY_4_3_AND_LATER
|| mOldTargetColliderTypeEnumIndex != targetTargetColliderType.enumValueIndex
#endif
) {
isRewriteRequired = true;
}
if (!anyColliderWithoutActiveIslandsOrHoles) {
if (isCompleteRecalculationRequired) {
RecalculateSelectedColliders(sortedTargets);
}
else if (isRecalculationFromPreviousResultRequired) {
RecalculateSelectedCollidersFromPreviousResult(sortedTargets);
}
else if (isRewriteRequired) {
RewriteSelectedColliders(sortedTargets);
}
}
}
if (GUI.changed) {
foreach (Object target in targetObjects) {
EditorUtility.SetDirty(target);
}
}
//EditorGUIUtility.LookLikeControls();
}
//-------------------------------------------------------------------------
void OnInspectorGuiHolesAndIslandsSection(out bool haveColliderRegionEnabledChanged,
out bool haveColliderRegionMaxPointCountChanged,
out bool haveColliderRegionConvexChanged,
Object[] targetObjects) {
// TODO NEXT: ensure that the case that no island is enabled does not happen or not cause problems.
haveColliderRegionEnabledChanged = false;
haveColliderRegionMaxPointCountChanged = false;
haveColliderRegionConvexChanged = false;
AlphaMeshCollider firstObject = (AlphaMeshCollider) targetObjects[0];
int numColliderRegions = 0;
if (firstObject.ColliderRegions != null) {
numColliderRegions = firstObject.ColliderRegions.Length;
}
bool[] newIsRegionEnabled = new bool [numColliderRegions];
int[] newRegionPointCount = new int [numColliderRegions];
bool[] newForceRegionConvex = new bool [numColliderRegions];
string foldoutString = "Holes and Islands [" + firstObject.NumEnabledColliderRegions + "][" + firstObject.ActualPointCountOfAllRegions + " vertices]";
mShowHolesAndIslandsSection = EditorGUILayout.Foldout(mShowHolesAndIslandsSection, foldoutString);
if(mShowHolesAndIslandsSection) {
EditorGUI.indentLevel++;
for (int regionIndex = 0; regionIndex < numColliderRegions; ++regionIndex) {
ColliderRegionData colliderRegion = firstObject.ColliderRegions[regionIndex];
AlphaMeshCollider.ColliderRegionParameters parameters = firstObject.ColliderRegionParams[regionIndex];
bool isEnabled = parameters.EnableRegion;
int maxPointCount = parameters.MaxPointCount;
bool convex = parameters.Convex;
if (regionIndex != 0) {
EditorGUILayout.Space();
}
string regionOrIslandString = colliderRegion.mRegionIsIsland ? "Island " : "Hole ";
regionOrIslandString += regionIndex + " [" + colliderRegion.mDetectedRegion.mPointCount + " px]";
//bool newIsEnabled = EditorGUILayout.BeginToggleGroup(regionOrIslandString, isEnabled);
bool newIsEnabled = EditorGUILayout.Toggle(regionOrIslandString, isEnabled);
EditorGUI.indentLevel++;
// int [3..100] max point count
int newPointCount = EditorGUILayout.IntSlider("Outline Vertex Count", maxPointCount, 3, mPointCountSliderMax);
bool newConvex = EditorGUILayout.Toggle("Force Convex", convex);
EditorGUI.indentLevel--;
//EditorGUILayout.EndToggleGroup();
bool hasEnabledChanged = newIsEnabled != isEnabled;
bool hasPountCountChanged = newPointCount != maxPointCount;
bool hasConvexChanged = newConvex != convex;
if (hasEnabledChanged) {
haveColliderRegionEnabledChanged = true;
}
if (hasPountCountChanged) {
haveColliderRegionMaxPointCountChanged = true;
}
if (hasConvexChanged) {
haveColliderRegionConvexChanged = true;
}
newIsRegionEnabled[regionIndex] = newIsEnabled;
newRegionPointCount[regionIndex] = newPointCount;
newForceRegionConvex[regionIndex] = newConvex;
}
for (int targetIndex = 0; targetIndex != targetObjects.Length; ++targetIndex) {
AlphaMeshCollider targetObject = (AlphaMeshCollider) targetObjects[targetIndex];
for (int regionIndex = 0; regionIndex < numColliderRegions; ++regionIndex) {
AlphaMeshCollider.ColliderRegionParameters colliderRegionParams = targetObject.ColliderRegionParams[regionIndex];
colliderRegionParams.EnableRegion = newIsRegionEnabled[regionIndex];
colliderRegionParams.MaxPointCount = newRegionPointCount[regionIndex];
colliderRegionParams.Convex = newForceRegionConvex[regionIndex];
}
}
EditorGUI.indentLevel--;
}
}
//-------------------------------------------------------------------------
static void SelectChildAlphaMeshColliders(GameObject[] gameObjects) {
List<GameObject> newSelectionList = new List<GameObject>();
foreach (GameObject gameObj in gameObjects) {
AddAlphaMeshCollidersOfTreeToList(gameObj.transform, ref newSelectionList);
}
GameObject[] newSelection = newSelectionList.ToArray();
Selection.objects = newSelection;
}
//-------------------------------------------------------------------------
static void RemoveColliderAndGenerator(GameObject[] gameObjects) {
foreach (GameObject gameObj in gameObjects) {
// AlphaMeshCollider component
AlphaMeshCollider alphaMeshColliderComponent = gameObj.GetComponent<AlphaMeshCollider>();
Transform colliderNode = null;
if (alphaMeshColliderComponent) {
colliderNode = alphaMeshColliderComponent.TargetNodeToAttachMeshCollider;
DestroyImmediate(alphaMeshColliderComponent);
}
// MeshCollider component
MeshCollider meshColliderComponent = gameObj.GetComponent<MeshCollider>();
if (meshColliderComponent) {
DestroyImmediate(meshColliderComponent);
}
// Potentially a MeshCollider at a child node (used for SmoothMoves scale animation)
if (colliderNode != null) {
meshColliderComponent = colliderNode.GetComponent<MeshCollider>();
if (meshColliderComponent) {
DestroyImmediate(meshColliderComponent);
}
}
#if UNITY_4_3_AND_LATER
// PolygonCollider2D component
PolygonCollider2D polygonColliderComponent = gameObj.GetComponent<PolygonCollider2D>();
if (polygonColliderComponent) {
DestroyImmediate(polygonColliderComponent);
}
// Potentially a PolygonCollider2D at a child node (used for SmoothMoves scale animation)
if (colliderNode != null) {
polygonColliderComponent = colliderNode.GetComponent<PolygonCollider2D>();
if (polygonColliderComponent) {
DestroyImmediate(polygonColliderComponent);
}
}
#endif
// AlphaMeshColliders child gameobject node
foreach (Transform child in gameObj.transform) {
if (child.name.Equals("AlphaMeshColliders")) {
GameObject.DestroyImmediate(child.gameObject);
}
}
}
}
//-------------------------------------------------------------------------
static void AddAlphaMeshCollidersOfTreeToList(Transform node, ref List<GameObject> resultList) {
AlphaMeshCollider alphaCollider = node.GetComponent<AlphaMeshCollider>();
if (alphaCollider != null) {
resultList.Add(node.gameObject);
}
foreach (Transform child in node) {
AddAlphaMeshCollidersOfTreeToList(child, ref resultList);
}
}
//-------------------------------------------------------------------------
static void AddCollidersToBoneAnimationTree(Transform node) {
foreach (Transform child in node) {
if (!child.name.EndsWith("_Sprite")) {
AlphaMeshCollider collider = child.GetComponent<AlphaMeshCollider>();
if (collider == null) {
collider = child.gameObject.AddComponent<AlphaMeshCollider>();
}
}
AddCollidersToBoneAnimationTree(child);
}
}
//-------------------------------------------------------------------------
static void AddCollidersToOTTileMap(Transform tileMapNode, Component otTileMap) {
// OTTileMapLayer[] otTileMap.layers
System.Type otTileMapType = otTileMap.GetType();
FieldInfo fieldLayers = otTileMapType.GetField("layers");
if (fieldLayers == null) {
Debug.LogError("Detected a missing 'layers' member variable at OTTileMap component - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
return;
}
// add a GameObject node named "AlphaMeshColliders"
GameObject collidersNode = new GameObject("AlphaMeshColliders");
collidersNode.transform.parent = tileMapNode;
collidersNode.transform.localPosition = Vector3.zero;
collidersNode.transform.localScale = Vector3.one;
IEnumerable layersArray = (IEnumerable) fieldLayers.GetValue(otTileMap);
int layerIndex = 0;
foreach (object otTileMapLayer in layersArray) {
System.Type otTileMapLayerType = otTileMapLayer.GetType();
FieldInfo fieldName = otTileMapLayerType.GetField("name");
if (fieldName == null) {
Debug.LogError("Detected a missing 'name' member variable at OTTileMapLayer component - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
return;
}
string layerName = (string) fieldName.GetValue(otTileMapLayer);
// add a GameObject node for each tilemap layer.
GameObject layerNode = new GameObject(layerName);
layerNode.transform.parent = collidersNode.transform;
layerNode.transform.localPosition = Vector3.zero;
layerNode.transform.localScale = Vector3.one;
addColliderGameObjectsForOTTileMapLayer(layerNode.transform, otTileMap, otTileMapLayer, layerIndex);
++layerIndex;
}
}
//-------------------------------------------------------------------------
static void addColliderGameObjectsForOTTileMapLayer(Transform layerNode, Component otTileMap, object otTileMapLayer, int layerIndex) {
// read tileMapSize = OTTileMap.mapSize (UnityEngine.Vector2)
System.Type otTileMapType = otTileMap.GetType();
FieldInfo fieldMapSize = otTileMapType.GetField("mapSize");
if (fieldMapSize == null) {
Debug.LogError("Detected a missing 'mapSize' member variable at OTTileMap component - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
return;
}
Vector2 tileMapSize = (UnityEngine.Vector2) fieldMapSize.GetValue(otTileMap);
int tileMapWidth = (int) tileMapSize.x;
int tileMapHeight = (int) tileMapSize.y;
// read mapTileSize = OTTileMap.mapTileSize (UnityEngine.Vector2)
FieldInfo fieldMapTileSize = otTileMapType.GetField("mapTileSize");
if (fieldMapTileSize == null) {
Debug.LogError("Detected a missing 'mapTileSize' member variable at OTTileMap component - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
return;
}
Vector2 mapTileSize = (UnityEngine.Vector2) fieldMapTileSize.GetValue(otTileMap);
Vector3 mapTileScale = new Vector3(1.0f / tileMapSize.x, 1.0f / tileMapSize.y, 1.0f / tileMapSize.x);
System.Collections.Generic.Dictionary<int, object> tileSetAtTileIndex = new System.Collections.Generic.Dictionary<int, object>();
Vector2 bottomLeftTileOffset = new Vector2(-0.5f, -0.5f);
// read tileIndices = otTileMapLayer.tiles (int[])
System.Type otTileMapLayerType = otTileMapLayer.GetType();
FieldInfo fieldTiles = otTileMapLayerType.GetField("tiles");
if (fieldTiles == null) {
Debug.LogError("Detected a missing 'tiles' member variable at OTTileMapLayer component - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
return;
}
int[] tileIndices = (int[]) fieldTiles.GetValue(otTileMapLayer);
System.Collections.Generic.Dictionary<int, Transform> groupNodeForTileIndex = new System.Collections.Generic.Dictionary<int, Transform>();
Transform tileGroupNode = null;
object tileSet = null;
for (int y = 0; y < tileMapHeight; ++y) {
for (int x = 0; x < tileMapWidth; ++x) {
int tileIndex = tileIndices[y * tileMapWidth + x];
if (tileIndex != 0) {
if (groupNodeForTileIndex.ContainsKey(tileIndex)) {
tileGroupNode = groupNodeForTileIndex[tileIndex];
tileSet = tileSetAtTileIndex[tileIndex];
}
else {
// create a group node
GameObject newTileGroup = new GameObject("Tile Type " + tileIndex);
newTileGroup.transform.parent = layerNode;
newTileGroup.transform.localPosition = Vector3.zero;
newTileGroup.transform.localScale = Vector3.one;
tileGroupNode = newTileGroup.transform;
groupNodeForTileIndex[tileIndex] = tileGroupNode;
// get tileset for tile index
tileSet = AlphaMeshCollider.GetOTTileSetForTileIndex(otTileMap, tileIndex);
tileSetAtTileIndex[tileIndex] = tileSet;
}
// read tileSet.tileSize (Vector2)
System.Type otTileSetType = tileSet.GetType();
FieldInfo fieldTileSize = otTileSetType.GetField("tileSize");
if (fieldTileSize == null) {
Debug.LogError("Detected a missing 'tileSize' member variable at OTTileSet class - Is your Orthello package up to date? 2D ColliderGen might probably not work correctly with this version.");
return;
}
Vector2 tileSize = (UnityEngine.Vector2) fieldTileSize.GetValue(tileSet);
Vector3 tileScale = new Vector3(mapTileScale.x / mapTileSize.x * tileSize.x, mapTileScale.y / mapTileSize.y * tileSize.y, mapTileScale.z);
Vector2 tileCenterOffset = new Vector3(tileScale.x * 0.5f, tileScale.x * 0.5f);
// add a GameObject for each enabled tile with name "tile y x"
GameObject alphaMeshColliderNode = new GameObject("tile " + y + " " + x);
alphaMeshColliderNode.transform.parent = tileGroupNode;
AlphaMeshCollider alphaMeshColliderComponent = alphaMeshColliderNode.AddComponent<AlphaMeshCollider>();
alphaMeshColliderComponent.SetOTTileMap(otTileMap, layerIndex, x, y, tileMapWidth);
// set the position of the tile collider according to its (x,y) pos in the map.
alphaMeshColliderNode.transform.localPosition = new Vector3(x * mapTileScale.x + bottomLeftTileOffset.x + tileCenterOffset.x, (tileMapSize.y - 1 - y) * mapTileScale.y + bottomLeftTileOffset.y + tileCenterOffset.y, 0.0f);
alphaMeshColliderNode.transform.localScale = tileScale;
}
}
}
}
//-------------------------------------------------------------------------
static void AddAlphaMeshColliderToOTTilesSprite(Transform tilesSpriteNode, Component otTilesSprite) {
AlphaMeshCollider alphaMeshColliderComponent = tilesSpriteNode.GetComponent<AlphaMeshCollider>();
if (alphaMeshColliderComponent == null) {
alphaMeshColliderComponent = tilesSpriteNode.gameObject.AddComponent<AlphaMeshCollider>();
alphaMeshColliderComponent.SetOTTilesSprite(otTilesSprite);
}
}
//-------------------------------------------------------------------------
void ReloadSelectedColliders(SortedDictionary<int, AlphaMeshCollider> sortedTargets) {
foreach (KeyValuePair<int, AlphaMeshCollider> pair in sortedTargets) {
AlphaMeshCollider target = pair.Value;
if (target.CanReloadCollider) {
target.ReloadCollider();
}
}
}
//-------------------------------------------------------------------------
void ReloadOrRecalculateSelectedColliders(SortedDictionary<int, AlphaMeshCollider> sortedTargets) {
int lastHash = int.MinValue;
foreach (KeyValuePair<int, AlphaMeshCollider> pair in sortedTargets) {
int hash = pair.Key;
AlphaMeshCollider target = pair.Value;
if (hash != lastHash) {
AlphaMeshColliderRegistry.Instance.ReloadOrRecalculateColliderAndUpdateSimilar(target); // if found, just load it, if not, recalculate and update all others.
}
lastHash = hash;
}
}
//-------------------------------------------------------------------------
void PrepareColliderIslandsAtSelectedColliders(SortedDictionary<int, AlphaMeshCollider> sortedTargets) {
int lastHash = int.MinValue;
foreach (KeyValuePair<int, AlphaMeshCollider> pair in sortedTargets) {
int hash = pair.Key;
AlphaMeshCollider target = pair.Value;
if (hash != lastHash) {
target.PrepareColliderIslandsForGui();
}
lastHash = hash;
}
}
//-------------------------------------------------------------------------
void PrepareColliderRegionsIfOldVersion(SortedDictionary<int, AlphaMeshCollider> sortedTargets) {
int lastHash = int.MinValue;
foreach (KeyValuePair<int, AlphaMeshCollider> pair in sortedTargets) {
int hash = pair.Key;
AlphaMeshCollider target = pair.Value;
if (hash != lastHash) {
if (target.ColliderRegionParams == null || target.ColliderRegionParams.Length == 0) {
target.PrepareColliderIslandsForGui();
}
}
lastHash = hash;
}
}
//-------------------------------------------------------------------------
void RecalculateSelectedColliders(SortedDictionary<int, AlphaMeshCollider> sortedTargets) {
int lastHash = int.MinValue;
foreach (KeyValuePair<int, AlphaMeshCollider> pair in sortedTargets) {
int hash = pair.Key;
AlphaMeshCollider target = pair.Value;
if (hash != lastHash) {
AlphaMeshColliderRegistry.Instance.RecalculateColliderAndUpdateSimilar(target);
}
lastHash = hash;
}
}
//-------------------------------------------------------------------------
void RecalculateSelectedCollidersFromPreviousResult(SortedDictionary<int, AlphaMeshCollider> sortedTargets) {
int lastHash = int.MinValue;
foreach (KeyValuePair<int, AlphaMeshCollider> pair in sortedTargets) {
int hash = pair.Key;
AlphaMeshCollider target = pair.Value;
if (hash != lastHash) {
AlphaMeshColliderRegistry.Instance.RecalculateColliderFromPreviousResultAndUpdateSimilar(target);
}
lastHash = hash;
}
}
//-------------------------------------------------------------------------
void RewriteSelectedColliders(SortedDictionary<int, AlphaMeshCollider> sortedTargets) {
int lastHash = int.MinValue;
foreach (KeyValuePair<int, AlphaMeshCollider> pair in sortedTargets) {
int hash = pair.Key;
AlphaMeshCollider target = pair.Value;
if (hash != lastHash) {
AlphaMeshColliderRegistry.Instance.RewriteColliderToFileAndUpdateSimilar(target);
}
lastHash = hash;
}
}
//-------------------------------------------------------------------------
void RecalculateOTTilesSpriteColliders(SortedDictionary<int, AlphaMeshCollider> sortedTargets) {
foreach (KeyValuePair<int, AlphaMeshCollider> pair in sortedTargets) {
AlphaMeshCollider target = pair.Value;
target.RecalculateCollidersForOTTilesSprite();
}
}
//-------------------------------------------------------------------------
SortedDictionary<int, AlphaMeshCollider> SortAlphaMeshColliders(Object[] unsortedAlphaMeshColliders) {
SortedDictionary<int, AlphaMeshCollider> resultList = new SortedDictionary<int, AlphaMeshCollider>(new DuplicatePermittingIntComparer());
foreach (AlphaMeshCollider alphaMeshCollider in unsortedAlphaMeshColliders) {
int textureHash = alphaMeshCollider.FullColliderMeshPath().GetHashCode();
resultList.Add(textureHash, alphaMeshCollider);
}
return resultList;
}
//-------------------------------------------------------------------------
bool AreUsedTexturesDifferent(SortedDictionary<int, AlphaMeshCollider> sortedTargets) {
Texture firstTexture = null;
foreach (KeyValuePair<int, AlphaMeshCollider> pair in sortedTargets) {
AlphaMeshCollider target = pair.Value;
Texture texture = target.UsedTexture;
if (firstTexture == null) {
firstTexture = texture;
}
if (texture != firstTexture) {
return true;
}
}
return false;
}
}
| |
// 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.
/*============================================================
**
**
**
** Purpose: A representation of a 32 bit 2's complement
** integer.
**
**
===========================================================*/
using System;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Int32 : IComparable, IFormattable, IConvertible
, IComparable<Int32>, IEquatable<Int32>
{
internal int m_value;
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int32, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Int32)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
int i = (int)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt32"));
}
public int CompareTo(int value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is Int32))
{
return false;
}
return m_value == ((Int32)obj).m_value;
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(Int32 obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return m_value;
}
[Pure]
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public static int Parse(String s)
{
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static int Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo);
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[Pure]
public static int Parse(String s, IFormatProvider provider)
{
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[Pure]
public static int Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String. Returns false rather
// than throwing exceptin if input is invalid
//
[Pure]
public static bool TryParse(String s, out Int32 result)
{
return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
// Parses an integer from a String in the given style. Returns false rather
// than throwing exceptin if input is invalid
//
[Pure]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
[Pure]
public TypeCode GetTypeCode()
{
return TypeCode.Int32;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider)
{
return m_value;
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int32", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using Lucene.Net.Util;
using NUnit.Framework;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
/*
/// 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
using TermQuery = Lucene.Net.Search.TermQuery;
using TextField = TextField;
[TestFixture]
public class TestStressIndexing2 : LuceneTestCase
{
internal static int MaxFields = 4;
internal static int BigFieldSize = 10;
internal static bool SameFieldOrder = false;
internal static int MergeFactor = 3;
internal static int MaxBufferedDocs = 3;
internal static int Seed = 0;
public sealed class YieldTestPoint : RandomIndexWriter.TestPoint
{
private readonly TestStressIndexing2 OuterInstance;
public YieldTestPoint(TestStressIndexing2 outerInstance)
{
this.OuterInstance = outerInstance;
}
public void Apply(string name)
{
// if (name.equals("startCommit")) {
if (Random().Next(4) == 2)
{
Thread.@Yield();
}
}
}
//
[Test]
public virtual void TestRandomIWReader()
{
Directory dir = NewDirectory();
// TODO: verify equals using IW.getReader
DocsAndWriter dw = IndexRandomIWReader(5, 3, 100, dir);
DirectoryReader reader = dw.Writer.Reader;
dw.Writer.Commit();
VerifyEquals(Random(), reader, dir, "id");
reader.Dispose();
dw.Writer.Dispose();
dir.Dispose();
}
[Ignore]
[Test]
public virtual void TestRandom()
{
Directory dir1 = NewDirectory();
Directory dir2 = NewDirectory();
// mergeFactor=2; maxBufferedDocs=2; Map docs = indexRandom(1, 3, 2, dir1);
int maxThreadStates = 1 + Random().Next(10);
bool doReaderPooling = Random().NextBoolean();
IDictionary<string, Document> docs = IndexRandom(5, 3, 100, dir1, maxThreadStates, doReaderPooling);
IndexSerial(Random(), docs, dir2);
// verifying verify
// verifyEquals(dir1, dir1, "id");
// verifyEquals(dir2, dir2, "id");
VerifyEquals(dir1, dir2, "id");
dir1.Dispose();
dir2.Dispose();
}
[Test]
public virtual void TestMultiConfig()
{
// test lots of smaller different params together
int num = AtLeast(3);
for (int i = 0; i < num; i++) // increase iterations for better testing
{
if (VERBOSE)
{
Console.WriteLine("\n\nTEST: top iter=" + i);
}
SameFieldOrder = Random().NextBoolean();
MergeFactor = Random().Next(3) + 2;
MaxBufferedDocs = Random().Next(3) + 2;
int maxThreadStates = 1 + Random().Next(10);
bool doReaderPooling = Random().NextBoolean();
Seed++;
int nThreads = Random().Next(5) + 1;
int iter = Random().Next(5) + 1;
int range = Random().Next(20) + 1;
Directory dir1 = NewDirectory();
Directory dir2 = NewDirectory();
if (VERBOSE)
{
Console.WriteLine(" nThreads=" + nThreads + " iter=" + iter + " range=" + range + " doPooling=" + doReaderPooling + " maxThreadStates=" + maxThreadStates + " sameFieldOrder=" + SameFieldOrder + " mergeFactor=" + MergeFactor + " maxBufferedDocs=" + MaxBufferedDocs);
}
IDictionary<string, Document> docs = IndexRandom(nThreads, iter, range, dir1, maxThreadStates, doReaderPooling);
if (VERBOSE)
{
Console.WriteLine("TEST: index serial");
}
IndexSerial(Random(), docs, dir2);
if (VERBOSE)
{
Console.WriteLine("TEST: verify");
}
VerifyEquals(dir1, dir2, "id");
dir1.Dispose();
dir2.Dispose();
}
}
internal static Term IdTerm = new Term("id", "");
internal IndexingThread[] Threads;
internal static IComparer<IndexableField> fieldNameComparator = new ComparatorAnonymousInnerClassHelper();
private class ComparatorAnonymousInnerClassHelper : IComparer<IndexableField>
{
public ComparatorAnonymousInnerClassHelper()
{
}
public virtual int Compare(IndexableField o1, IndexableField o2)
{
return o1.Name().CompareTo(o2.Name());
}
}
// this test avoids using any extra synchronization in the multiple
// indexing threads to test that IndexWriter does correctly synchronize
// everything.
public class DocsAndWriter
{
internal IDictionary<string, Document> Docs;
internal IndexWriter Writer;
}
public virtual DocsAndWriter IndexRandomIWReader(int nThreads, int iterations, int range, Directory dir)
{
IDictionary<string, Document> docs = new Dictionary<string, Document>();
IndexWriter w = RandomIndexWriter.MockIndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.CREATE).SetRAMBufferSizeMB(0.1).SetMaxBufferedDocs(MaxBufferedDocs).SetMergePolicy(NewLogMergePolicy()), new YieldTestPoint(this));
w.Commit();
LogMergePolicy lmp = (LogMergePolicy)w.Config.MergePolicy;
lmp.NoCFSRatio = 0.0;
lmp.MergeFactor = MergeFactor;
/*
/// w.setMaxMergeDocs(Integer.MAX_VALUE);
/// w.setMaxFieldLength(10000);
/// w.SetRAMBufferSizeMB(1);
/// w.setMergeFactor(10);
*/
Threads = new IndexingThread[nThreads];
for (int i = 0; i < Threads.Length; i++)
{
IndexingThread th = new IndexingThread(this);
th.w = w;
th.@base = 1000000 * i;
th.Range = range;
th.Iterations = iterations;
Threads[i] = th;
}
for (int i = 0; i < Threads.Length; i++)
{
Threads[i].Start();
}
for (int i = 0; i < Threads.Length; i++)
{
Threads[i].Join();
}
// w.ForceMerge(1);
//w.Dispose();
for (int i = 0; i < Threads.Length; i++)
{
IndexingThread th = Threads[i];
lock (th)
{
docs.PutAll(th.Docs);
}
}
TestUtil.CheckIndex(dir);
DocsAndWriter dw = new DocsAndWriter();
dw.Docs = docs;
dw.Writer = w;
return dw;
}
public virtual IDictionary<string, Document> IndexRandom(int nThreads, int iterations, int range, Directory dir, int maxThreadStates, bool doReaderPooling)
{
IDictionary<string, Document> docs = new Dictionary<string, Document>();
IndexWriter w = RandomIndexWriter.MockIndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.CREATE).SetRAMBufferSizeMB(0.1).SetMaxBufferedDocs(MaxBufferedDocs).SetIndexerThreadPool(new ThreadAffinityDocumentsWriterThreadPool(maxThreadStates)).SetReaderPooling(doReaderPooling).SetMergePolicy(NewLogMergePolicy()), new YieldTestPoint(this));
LogMergePolicy lmp = (LogMergePolicy)w.Config.MergePolicy;
lmp.NoCFSRatio = 0.0;
lmp.MergeFactor = MergeFactor;
Threads = new IndexingThread[nThreads];
for (int i = 0; i < Threads.Length; i++)
{
IndexingThread th = new IndexingThread(this);
th.w = w;
th.@base = 1000000 * i;
th.Range = range;
th.Iterations = iterations;
Threads[i] = th;
}
for (int i = 0; i < Threads.Length; i++)
{
Threads[i].Start();
}
for (int i = 0; i < Threads.Length; i++)
{
Threads[i].Join();
}
//w.ForceMerge(1);
w.Dispose();
for (int i = 0; i < Threads.Length; i++)
{
IndexingThread th = Threads[i];
lock (th)
{
docs.PutAll(th.Docs);
}
}
//System.out.println("TEST: checkindex");
TestUtil.CheckIndex(dir);
return docs;
}
public static void IndexSerial(Random random, IDictionary<string, Document> docs, Directory dir)
{
IndexWriter w = new IndexWriter(dir, LuceneTestCase.NewIndexWriterConfig(random, TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(NewLogMergePolicy()));
// index all docs in a single thread
IEnumerator<Document> iter = docs.Values.GetEnumerator();
while (iter.MoveNext())
{
Document d = iter.Current;
List<IndexableField> fields = new List<IndexableField>();
fields.AddRange(d.Fields);
// put fields in same order each time
fields.Sort(fieldNameComparator);
Document d1 = new Document();
for (int i = 0; i < fields.Count; i++)
{
d1.Add(fields[i]);
}
w.AddDocument(d1);
// System.out.println("indexing "+d1);
}
w.Dispose();
}
public virtual void VerifyEquals(Random r, DirectoryReader r1, Directory dir2, string idField)
{
DirectoryReader r2 = DirectoryReader.Open(dir2);
VerifyEquals(r1, r2, idField);
r2.Dispose();
}
public virtual void VerifyEquals(Directory dir1, Directory dir2, string idField)
{
DirectoryReader r1 = DirectoryReader.Open(dir1);
DirectoryReader r2 = DirectoryReader.Open(dir2);
VerifyEquals(r1, r2, idField);
r1.Dispose();
r2.Dispose();
}
private static void PrintDocs(DirectoryReader r)
{
foreach (AtomicReaderContext ctx in r.Leaves)
{
// TODO: improve this
AtomicReader sub = (AtomicReader)ctx.Reader;
Bits liveDocs = sub.LiveDocs;
Console.WriteLine(" " + ((SegmentReader)sub).SegmentInfo);
for (int docID = 0; docID < sub.MaxDoc; docID++)
{
Document doc = sub.Document(docID);
if (liveDocs == null || liveDocs.Get(docID))
{
Console.WriteLine(" docID=" + docID + " id:" + doc.Get("id"));
}
else
{
Console.WriteLine(" DEL docID=" + docID + " id:" + doc.Get("id"));
}
}
}
}
public virtual void VerifyEquals(DirectoryReader r1, DirectoryReader r2, string idField)
{
if (VERBOSE)
{
Console.WriteLine("\nr1 docs:");
PrintDocs(r1);
Console.WriteLine("\nr2 docs:");
PrintDocs(r2);
}
if (r1.NumDocs != r2.NumDocs)
{
Debug.Assert(false, "r1.NumDocs=" + r1.NumDocs + " vs r2.NumDocs=" + r2.NumDocs);
}
bool hasDeletes = !(r1.MaxDoc == r2.MaxDoc && r1.NumDocs == r1.MaxDoc);
int[] r2r1 = new int[r2.MaxDoc]; // r2 id to r1 id mapping
// create mapping from id2 space to id2 based on idField
Fields f1 = MultiFields.GetFields(r1);
if (f1 == null)
{
// make sure r2 is empty
Assert.IsNull(MultiFields.GetFields(r2));
return;
}
Terms terms1 = f1.Terms(idField);
if (terms1 == null)
{
Assert.IsTrue(MultiFields.GetFields(r2) == null || MultiFields.GetFields(r2).Terms(idField) == null);
return;
}
TermsEnum termsEnum = terms1.Iterator(null);
Bits liveDocs1 = MultiFields.GetLiveDocs(r1);
Bits liveDocs2 = MultiFields.GetLiveDocs(r2);
Fields fields = MultiFields.GetFields(r2);
if (fields == null)
{
// make sure r1 is in fact empty (eg has only all
// deleted docs):
Bits liveDocs = MultiFields.GetLiveDocs(r1);
DocsEnum docs = null;
while (termsEnum.Next() != null)
{
docs = TestUtil.Docs(Random(), termsEnum, liveDocs, docs, DocsEnum.FLAG_NONE);
while (docs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
Assert.Fail("r1 is not empty but r2 is");
}
}
return;
}
Terms terms2 = fields.Terms(idField);
TermsEnum termsEnum2 = terms2.Iterator(null);
DocsEnum termDocs1 = null;
DocsEnum termDocs2 = null;
while (true)
{
BytesRef term = termsEnum.Next();
//System.out.println("TEST: match id term=" + term);
if (term == null)
{
break;
}
termDocs1 = TestUtil.Docs(Random(), termsEnum, liveDocs1, termDocs1, DocsEnum.FLAG_NONE);
if (termsEnum2.SeekExact(term))
{
termDocs2 = TestUtil.Docs(Random(), termsEnum2, liveDocs2, termDocs2, DocsEnum.FLAG_NONE);
}
else
{
termDocs2 = null;
}
if (termDocs1.NextDoc() == DocIdSetIterator.NO_MORE_DOCS)
{
// this doc is deleted and wasn't replaced
Assert.IsTrue(termDocs2 == null || termDocs2.NextDoc() == DocIdSetIterator.NO_MORE_DOCS);
continue;
}
int id1 = termDocs1.DocID();
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, termDocs1.NextDoc());
Assert.IsTrue(termDocs2.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
int id2 = termDocs2.DocID();
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, termDocs2.NextDoc());
r2r1[id2] = id1;
// verify stored fields are equivalent
try
{
VerifyEquals(r1.Document(id1), r2.Document(id2));
}
catch (Exception t)
{
Console.WriteLine("FAILED id=" + term + " id1=" + id1 + " id2=" + id2 + " term=" + term);
Console.WriteLine(" d1=" + r1.Document(id1));
Console.WriteLine(" d2=" + r2.Document(id2));
throw t;
}
try
{
// verify term vectors are equivalent
VerifyEquals(r1.GetTermVectors(id1), r2.GetTermVectors(id2));
}
catch (Exception e)
{
Console.WriteLine("FAILED id=" + term + " id1=" + id1 + " id2=" + id2);
Fields tv1 = r1.GetTermVectors(id1);
Console.WriteLine(" d1=" + tv1);
if (tv1 != null)
{
DocsAndPositionsEnum dpEnum = null;
DocsEnum dEnum = null;
foreach (string field in tv1)
{
Console.WriteLine(" " + field + ":");
Terms terms3 = tv1.Terms(field);
Assert.IsNotNull(terms3);
TermsEnum termsEnum3 = terms3.Iterator(null);
BytesRef term2;
while ((term2 = termsEnum3.Next()) != null)
{
Console.WriteLine(" " + term2.Utf8ToString() + ": freq=" + termsEnum3.TotalTermFreq());
dpEnum = termsEnum3.DocsAndPositions(null, dpEnum);
if (dpEnum != null)
{
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
int freq = dpEnum.Freq();
Console.WriteLine(" doc=" + dpEnum.DocID() + " freq=" + freq);
for (int posUpto = 0; posUpto < freq; posUpto++)
{
Console.WriteLine(" pos=" + dpEnum.NextPosition());
}
}
else
{
dEnum = TestUtil.Docs(Random(), termsEnum3, null, dEnum, DocsEnum.FLAG_FREQS);
Assert.IsNotNull(dEnum);
Assert.IsTrue(dEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
int freq = dEnum.Freq();
Console.WriteLine(" doc=" + dEnum.DocID() + " freq=" + freq);
}
}
}
}
Fields tv2 = r2.GetTermVectors(id2);
Console.WriteLine(" d2=" + tv2);
if (tv2 != null)
{
DocsAndPositionsEnum dpEnum = null;
DocsEnum dEnum = null;
foreach (string field in tv2)
{
Console.WriteLine(" " + field + ":");
Terms terms3 = tv2.Terms(field);
Assert.IsNotNull(terms3);
TermsEnum termsEnum3 = terms3.Iterator(null);
BytesRef term2;
while ((term2 = termsEnum3.Next()) != null)
{
Console.WriteLine(" " + term2.Utf8ToString() + ": freq=" + termsEnum3.TotalTermFreq());
dpEnum = termsEnum3.DocsAndPositions(null, dpEnum);
if (dpEnum != null)
{
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
int freq = dpEnum.Freq();
Console.WriteLine(" doc=" + dpEnum.DocID() + " freq=" + freq);
for (int posUpto = 0; posUpto < freq; posUpto++)
{
Console.WriteLine(" pos=" + dpEnum.NextPosition());
}
}
else
{
dEnum = TestUtil.Docs(Random(), termsEnum3, null, dEnum, DocsEnum.FLAG_FREQS);
Assert.IsNotNull(dEnum);
Assert.IsTrue(dEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
int freq = dEnum.Freq();
Console.WriteLine(" doc=" + dEnum.DocID() + " freq=" + freq);
}
}
}
}
throw e;
}
}
//System.out.println("TEST: done match id");
// Verify postings
//System.out.println("TEST: create te1");
Fields fields1 = MultiFields.GetFields(r1);
IEnumerator<string> fields1Enum = fields1.GetEnumerator();
Fields fields2 = MultiFields.GetFields(r2);
IEnumerator<string> fields2Enum = fields2.GetEnumerator();
string field1 = null, field2 = null;
TermsEnum termsEnum1 = null;
termsEnum2 = null;
DocsEnum docs1 = null, docs2 = null;
// pack both doc and freq into single element for easy sorting
long[] info1 = new long[r1.NumDocs];
long[] info2 = new long[r2.NumDocs];
for (; ; )
{
BytesRef term1 = null, term2 = null;
// iterate until we get some docs
int len1;
for (; ; )
{
len1 = 0;
if (termsEnum1 == null)
{
if (!fields1Enum.MoveNext())
{
break;
}
field1 = fields1Enum.Current;
Terms terms = fields1.Terms(field1);
if (terms == null)
{
continue;
}
termsEnum1 = terms.Iterator(null);
}
term1 = termsEnum1.Next();
if (term1 == null)
{
// no more terms in this field
termsEnum1 = null;
continue;
}
//System.out.println("TEST: term1=" + term1);
docs1 = TestUtil.Docs(Random(), termsEnum1, liveDocs1, docs1, DocsEnum.FLAG_FREQS);
while (docs1.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
int d = docs1.DocID();
int f = docs1.Freq();
info1[len1] = (((long)d) << 32) | f;
len1++;
}
if (len1 > 0)
{
break;
}
}
// iterate until we get some docs
int len2;
for (; ; )
{
len2 = 0;
if (termsEnum2 == null)
{
if (!fields2Enum.MoveNext())
{
break;
}
field2 = fields2Enum.Current;
Terms terms = fields2.Terms(field2);
if (terms == null)
{
continue;
}
termsEnum2 = terms.Iterator(null);
}
term2 = termsEnum2.Next();
if (term2 == null)
{
// no more terms in this field
termsEnum2 = null;
continue;
}
//System.out.println("TEST: term1=" + term1);
docs2 = TestUtil.Docs(Random(), termsEnum2, liveDocs2, docs2, DocsEnum.FLAG_FREQS);
while (docs2.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
int d = r2r1[docs2.DocID()];
int f = docs2.Freq();
info2[len2] = (((long)d) << 32) | f;
len2++;
}
if (len2 > 0)
{
break;
}
}
Assert.AreEqual(len1, len2);
if (len1 == 0) // no more terms
{
break;
}
Assert.AreEqual(field1, field2);
Assert.IsTrue(term1.BytesEquals(term2));
if (!hasDeletes)
{
Assert.AreEqual(termsEnum1.DocFreq(), termsEnum2.DocFreq());
}
Assert.AreEqual(term1, term2, "len1=" + len1 + " len2=" + len2 + " deletes?=" + hasDeletes);
// sort info2 to get it into ascending docid
Array.Sort(info2, 0, len2);
// now compare
for (int i = 0; i < len1; i++)
{
Assert.AreEqual(info1[i], info2[i], "i=" + i + " len=" + len1 + " d1=" + ((long)((ulong)info1[i] >> 32)) + " f1=" + (info1[i] & int.MaxValue) + " d2=" + ((long)((ulong)info2[i] >> 32)) + " f2=" + (info2[i] & int.MaxValue) + " field=" + field1 + " term=" + term1.Utf8ToString());
}
}
}
public static void VerifyEquals(Document d1, Document d2)
{
List<IndexableField> ff1 = d1.Fields;
List<IndexableField> ff2 = d2.Fields;
ff1.Sort(fieldNameComparator);
ff2.Sort(fieldNameComparator);
Assert.AreEqual(ff1.Count, ff2.Count, ff1 + " : " + ff2);
for (int i = 0; i < ff1.Count; i++)
{
IndexableField f1 = ff1[i];
IndexableField f2 = ff2[i];
if (f1.BinaryValue() != null)
{
Debug.Assert(f2.BinaryValue() != null);
}
else
{
string s1 = f1.StringValue;
string s2 = f2.StringValue;
Assert.AreEqual(s1, s2, ff1 + " : " + ff2);
}
}
}
public static void VerifyEquals(Fields d1, Fields d2)
{
if (d1 == null)
{
Assert.IsTrue(d2 == null || d2.Size == 0);
return;
}
Assert.IsTrue(d2 != null);
IEnumerator<string> fieldsEnum2 = d2.GetEnumerator();
foreach (string field1 in d1)
{
fieldsEnum2.MoveNext();
string field2 = fieldsEnum2.Current;
Assert.AreEqual(field1, field2);
Terms terms1 = d1.Terms(field1);
Assert.IsNotNull(terms1);
TermsEnum termsEnum1 = terms1.Iterator(null);
Terms terms2 = d2.Terms(field2);
Assert.IsNotNull(terms2);
TermsEnum termsEnum2 = terms2.Iterator(null);
DocsAndPositionsEnum dpEnum1 = null;
DocsAndPositionsEnum dpEnum2 = null;
DocsEnum dEnum1 = null;
DocsEnum dEnum2 = null;
BytesRef term1;
while ((term1 = termsEnum1.Next()) != null)
{
BytesRef term2 = termsEnum2.Next();
Assert.AreEqual(term1, term2);
Assert.AreEqual(termsEnum1.TotalTermFreq(), termsEnum2.TotalTermFreq());
dpEnum1 = termsEnum1.DocsAndPositions(null, dpEnum1);
dpEnum2 = termsEnum2.DocsAndPositions(null, dpEnum2);
if (dpEnum1 != null)
{
Assert.IsNotNull(dpEnum2);
int docID1 = dpEnum1.NextDoc();
dpEnum2.NextDoc();
// docIDs are not supposed to be equal
//int docID2 = dpEnum2.NextDoc();
//Assert.AreEqual(docID1, docID2);
Assert.IsTrue(docID1 != DocIdSetIterator.NO_MORE_DOCS);
int freq1 = dpEnum1.Freq();
int freq2 = dpEnum2.Freq();
Assert.AreEqual(freq1, freq2);
IOffsetAttribute offsetAtt1 = dpEnum1.Attributes().HasAttribute<IOffsetAttribute>() ? dpEnum1.Attributes().GetAttribute<IOffsetAttribute>() : null;
IOffsetAttribute offsetAtt2 = dpEnum2.Attributes().HasAttribute<IOffsetAttribute>() ? dpEnum2.Attributes().GetAttribute<IOffsetAttribute>() : null;
if (offsetAtt1 != null)
{
Assert.IsNotNull(offsetAtt2);
}
else
{
Assert.IsNull(offsetAtt2);
}
for (int posUpto = 0; posUpto < freq1; posUpto++)
{
int pos1 = dpEnum1.NextPosition();
int pos2 = dpEnum2.NextPosition();
Assert.AreEqual(pos1, pos2);
if (offsetAtt1 != null)
{
Assert.AreEqual(offsetAtt1.StartOffset(), offsetAtt2.StartOffset());
Assert.AreEqual(offsetAtt1.EndOffset(), offsetAtt2.EndOffset());
}
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum1.NextDoc());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum2.NextDoc());
}
else
{
dEnum1 = TestUtil.Docs(Random(), termsEnum1, null, dEnum1, DocsEnum.FLAG_FREQS);
dEnum2 = TestUtil.Docs(Random(), termsEnum2, null, dEnum2, DocsEnum.FLAG_FREQS);
Assert.IsNotNull(dEnum1);
Assert.IsNotNull(dEnum2);
int docID1 = dEnum1.NextDoc();
dEnum2.NextDoc();
// docIDs are not supposed to be equal
//int docID2 = dEnum2.NextDoc();
//Assert.AreEqual(docID1, docID2);
Assert.IsTrue(docID1 != DocIdSetIterator.NO_MORE_DOCS);
int freq1 = dEnum1.Freq();
int freq2 = dEnum2.Freq();
Assert.AreEqual(freq1, freq2);
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dEnum1.NextDoc());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dEnum2.NextDoc());
}
}
Assert.IsNull(termsEnum2.Next());
}
Assert.IsFalse(fieldsEnum2.MoveNext());
}
internal class IndexingThread : ThreadClass
{
private readonly TestStressIndexing2 OuterInstance;
public IndexingThread(TestStressIndexing2 outerInstance)
{
this.OuterInstance = outerInstance;
}
internal IndexWriter w;
internal int @base;
internal int Range;
internal int Iterations;
internal IDictionary<string, Document> Docs = new Dictionary<string, Document>();
internal Random r;
public virtual int NextInt(int lim)
{
return r.Next(lim);
}
// start is inclusive and end is exclusive
public virtual int NextInt(int start, int end)
{
return start + r.Next(end - start);
}
internal char[] Buffer = new char[100];
internal virtual int AddUTF8Token(int start)
{
int end = start + NextInt(20);
if (Buffer.Length < 1 + end)
{
char[] newBuffer = new char[(int)((1 + end) * 1.25)];
Array.Copy(Buffer, 0, newBuffer, 0, Buffer.Length);
Buffer = newBuffer;
}
for (int i = start; i < end; i++)
{
int t = NextInt(5);
if (0 == t && i < end - 1)
{
// Make a surrogate pair
// High surrogate
Buffer[i++] = (char)NextInt(0xd800, 0xdc00);
// Low surrogate
Buffer[i] = (char)NextInt(0xdc00, 0xe000);
}
else if (t <= 1)
{
Buffer[i] = (char)NextInt(0x80);
}
else if (2 == t)
{
Buffer[i] = (char)NextInt(0x80, 0x800);
}
else if (3 == t)
{
Buffer[i] = (char)NextInt(0x800, 0xd800);
}
else if (4 == t)
{
Buffer[i] = (char)NextInt(0xe000, 0xffff);
}
}
Buffer[end] = ' ';
return 1 + end;
}
public virtual string GetString(int nTokens)
{
nTokens = nTokens != 0 ? nTokens : r.Next(4) + 1;
// Half the time make a random UTF8 string
if (r.NextBoolean())
{
return GetUTF8String(nTokens);
}
// avoid StringBuffer because it adds extra synchronization.
char[] arr = new char[nTokens * 2];
for (int i = 0; i < nTokens; i++)
{
arr[i * 2] = (char)('A' + r.Next(10));
arr[i * 2 + 1] = ' ';
}
return new string(arr);
}
public virtual string GetUTF8String(int nTokens)
{
int upto = 0;
Arrays.Fill(Buffer, (char)0);
for (int i = 0; i < nTokens; i++)
{
upto = AddUTF8Token(upto);
}
return new string(Buffer, 0, upto);
}
public virtual string IdString
{
get
{
return Convert.ToString(@base + NextInt(Range));
}
}
public virtual void IndexDoc()
{
Document d = new Document();
FieldType customType1 = new FieldType(TextField.TYPE_STORED);
customType1.Tokenized = false;
customType1.OmitNorms = true;
List<Field> fields = new List<Field>();
string idString = IdString;
Field idField = NewField("id", idString, customType1);
fields.Add(idField);
int nFields = NextInt(MaxFields);
for (int i = 0; i < nFields; i++)
{
FieldType customType = new FieldType();
switch (NextInt(4))
{
case 0:
break;
case 1:
customType.StoreTermVectors = true;
break;
case 2:
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
break;
case 3:
customType.StoreTermVectors = true;
customType.StoreTermVectorOffsets = true;
break;
}
switch (NextInt(4))
{
case 0:
customType.Stored = true;
customType.OmitNorms = true;
customType.Indexed = true;
fields.Add(NewField("f" + NextInt(100), GetString(1), customType));
break;
case 1:
customType.Indexed = true;
customType.Tokenized = true;
fields.Add(NewField("f" + NextInt(100), GetString(0), customType));
break;
case 2:
customType.Stored = true;
customType.StoreTermVectors = false;
customType.StoreTermVectorOffsets = false;
customType.StoreTermVectorPositions = false;
fields.Add(NewField("f" + NextInt(100), GetString(0), customType));
break;
case 3:
customType.Stored = true;
customType.Indexed = true;
customType.Tokenized = true;
fields.Add(NewField("f" + NextInt(100), GetString(BigFieldSize), customType));
break;
}
}
if (SameFieldOrder)
{
fields.Sort(fieldNameComparator);
}
else
{
// random placement of id field also
CollectionsHelper.Swap(fields, NextInt(fields.Count), 0);
}
for (int i = 0; i < fields.Count; i++)
{
d.Add(fields[i]);
}
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": indexing id:" + idString);
}
w.UpdateDocument(new Term("id", idString), d);
//System.out.println(Thread.currentThread().getName() + ": indexing "+d);
Docs[idString] = d;
}
public virtual void DeleteDoc()
{
string idString = IdString;
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": del id:" + idString);
}
w.DeleteDocuments(new Term("id", idString));
Docs.Remove(idString);
}
public virtual void DeleteByQuery()
{
string idString = IdString;
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": del query id:" + idString);
}
w.DeleteDocuments(new TermQuery(new Term("id", idString)));
Docs.Remove(idString);
}
public override void Run()
{
try
{
r = new Random(@base + Range + Seed);
for (int i = 0; i < Iterations; i++)
{
int what = NextInt(100);
if (what < 5)
{
DeleteDoc();
}
else if (what < 10)
{
DeleteByQuery();
}
else
{
IndexDoc();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.Write(e.StackTrace);
Assert.Fail(e.ToString());
}
lock (this)
{
int dummy = Docs.Count;
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SWP.Backend.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);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Testing;
using Microsoft.Net.Http.Headers;
using Moq;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests
{
public class Http2TimeoutTests : Http2TestBase
{
[Fact]
public async Task Preamble_NotReceivedInitially_WithinKeepAliveTimeout_ClosesConnection()
{
var limits = _serviceContext.ServerOptions.Limits;
CreateConnection();
_connectionTask = _connection.ProcessRequestsAsync(new DummyApplication(_noopApplication));
AdvanceClock(limits.KeepAliveTimeout + Heartbeat.Interval);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromTicks(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.KeepAlive), Times.Once);
await WaitForConnectionStopAsync(expectedLastStreamId: 0, ignoreNonGoAwayFrames: false);
_mockTimeoutHandler.VerifyNoOtherCalls();
}
[Fact]
public async Task HEADERS_NotReceivedInitially_WithinKeepAliveTimeout_ClosesConnection()
{
var limits = _serviceContext.ServerOptions.Limits;
await InitializeConnectionAsync(_noopApplication);
AdvanceClock(limits.KeepAliveTimeout + Heartbeat.Interval);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromTicks(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.KeepAlive), Times.Once);
await WaitForConnectionStopAsync(expectedLastStreamId: 0, ignoreNonGoAwayFrames: false);
_mockTimeoutHandler.VerifyNoOtherCalls();
}
[Fact]
public async Task HEADERS_NotReceivedAfterFirstRequest_WithinKeepAliveTimeout_ClosesConnection()
{
var limits = _serviceContext.ServerOptions.Limits;
await InitializeConnectionAsync(_noopApplication);
AdvanceClock(limits.KeepAliveTimeout + Heartbeat.Interval);
// keep-alive timeout set but not fired.
_mockTimeoutControl.Verify(c => c.SetTimeout(It.IsAny<long>(), TimeoutReason.KeepAlive), Times.Once);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
// The KeepAlive timeout is set when the stream completes processing on a background thread, so we need to hook the
// keep-alive set afterwards to make a reliable test.
var setTimeoutTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_mockTimeoutControl.Setup(c => c.SetTimeout(It.IsAny<long>(), TimeoutReason.KeepAlive)).Callback<long, TimeoutReason>((t, r) =>
{
_timeoutControl.SetTimeout(t, r);
setTimeoutTcs.SetResult();
});
// Send continuation frame to verify intermediate request header timeout doesn't interfere with keep-alive timeout.
await SendHeadersAsync(1, Http2HeadersFrameFlags.END_STREAM, _browserRequestHeaders);
await SendEmptyContinuationFrameAsync(1, Http2ContinuationFrameFlags.END_HEADERS);
_mockTimeoutControl.Verify(c => c.SetTimeout(It.IsAny<long>(), TimeoutReason.RequestHeaders), Times.Once);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 36,
withFlags: (byte)(Http2HeadersFrameFlags.END_HEADERS | Http2HeadersFrameFlags.END_STREAM),
withStreamId: 1);
await setTimeoutTcs.Task.DefaultTimeout();
AdvanceClock(limits.KeepAliveTimeout + Heartbeat.Interval);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromTicks(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.KeepAlive), Times.Once);
await WaitForConnectionStopAsync(expectedLastStreamId: 1, ignoreNonGoAwayFrames: false);
_mockTimeoutHandler.VerifyNoOtherCalls();
}
[Fact]
public async Task PING_WithinKeepAliveTimeout_ResetKeepAliveTimeout()
{
var limits = _serviceContext.ServerOptions.Limits;
CreateConnection();
await InitializeConnectionAsync(_noopApplication);
// Connection starts and sets keep alive timeout
_mockTimeoutControl.Verify(c => c.SetTimeout(It.IsAny<long>(), TimeoutReason.KeepAlive), Times.Once);
_mockTimeoutControl.Verify(c => c.ResetTimeout(It.IsAny<long>(), TimeoutReason.KeepAlive), Times.Never);
await SendPingAsync(Http2PingFrameFlags.NONE);
await ExpectAsync(Http2FrameType.PING,
withLength: 8,
withFlags: (byte)Http2PingFrameFlags.ACK,
withStreamId: 0);
// Server resets keep alive timeout
_mockTimeoutControl.Verify(c => c.ResetTimeout(It.IsAny<long>(), TimeoutReason.KeepAlive), Times.Once);
}
[Fact]
public async Task PING_NoKeepAliveTimeout_DoesNotResetKeepAliveTimeout()
{
var limits = _serviceContext.ServerOptions.Limits;
CreateConnection();
await InitializeConnectionAsync(_echoApplication);
// Connection starts and sets keep alive timeout
_mockTimeoutControl.Verify(c => c.SetTimeout(It.IsAny<long>(), TimeoutReason.KeepAlive), Times.Once);
_mockTimeoutControl.Verify(c => c.ResetTimeout(It.IsAny<long>(), TimeoutReason.KeepAlive), Times.Never);
_mockTimeoutControl.Verify(c => c.CancelTimeout(), Times.Never);
// Stream will stay open because it is waiting for request body to end
await StartStreamAsync(1, _browserRequestHeaders, endStream: false);
// Starting a stream cancels the keep alive timeout
_mockTimeoutControl.Verify(c => c.CancelTimeout(), Times.Once);
await SendPingAsync(Http2PingFrameFlags.NONE);
await ExpectAsync(Http2FrameType.PING,
withLength: 8,
withFlags: (byte)Http2PingFrameFlags.ACK,
withStreamId: 0);
// Server doesn't reset keep alive timeout because it isn't running
_mockTimeoutControl.Verify(c => c.ResetTimeout(It.IsAny<long>(), TimeoutReason.KeepAlive), Times.Never);
// End stream
await SendDataAsync(1, _helloWorldBytes, endStream: true);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: _helloWorldBytes.Length,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
}
[Fact]
public async Task HEADERS_ReceivedWithoutAllCONTINUATIONs_WithinRequestHeadersTimeout_AbortsConnection()
{
var limits = _serviceContext.ServerOptions.Limits;
await InitializeConnectionAsync(_noopApplication);
await SendHeadersAsync(1, Http2HeadersFrameFlags.END_STREAM, _browserRequestHeaders);
await SendEmptyContinuationFrameAsync(1, Http2ContinuationFrameFlags.NONE);
AdvanceClock(limits.RequestHeadersTimeout + Heartbeat.Interval);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
await SendEmptyContinuationFrameAsync(1, Http2ContinuationFrameFlags.NONE);
AdvanceClock(TimeSpan.FromTicks(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.RequestHeaders), Times.Once);
await WaitForConnectionErrorAsync<Microsoft.AspNetCore.Http.BadHttpRequestException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: int.MaxValue,
Http2ErrorCode.INTERNAL_ERROR,
CoreStrings.BadRequest_RequestHeadersTimeout);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.BadRequest_RequestHeadersTimeout)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task ResponseDrain_SlowerThanMinimumDataRate_AbortsConnection()
{
var limits = _serviceContext.ServerOptions.Limits;
await InitializeConnectionAsync(_noopApplication);
await SendGoAwayAsync();
await WaitForConnectionStopAsync(expectedLastStreamId: 0, ignoreNonGoAwayFrames: false);
AdvanceClock(TimeSpan.FromSeconds(_bytesReceived / limits.MinResponseDataRate.BytesPerSecond) +
limits.MinResponseDataRate.GracePeriod + Heartbeat.Interval - TimeSpan.FromSeconds(.5));
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
_mockConnectionContext.Verify(c => c.Abort(It.IsAny<ConnectionAbortedException>()), Times.Never);
AdvanceClock(TimeSpan.FromSeconds(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.WriteDataRate), Times.Once);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.ConnectionTimedBecauseResponseMininumDataRateNotSatisfied)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
Assert.Contains(TestSink.Writes, w => w.EventId.Name == "ResponseMinimumDataRateNotSatisfied");
}
[Theory]
[InlineData((int)Http2FrameType.DATA)]
[InlineData((int)Http2FrameType.CONTINUATION)]
public async Task AbortedStream_ResetsAndDrainsRequest_RefusesFramesAfterCooldownExpires(int intFinalFrameType)
{
var closeLock = new object();
var closed = false;
var finalFrameType = (Http2FrameType)intFinalFrameType;
// Remove callback that completes _pair.Application.Output on abort.
_mockConnectionContext.Reset();
var mockSystemClock = _serviceContext.MockSystemClock;
var headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, "POST"),
new KeyValuePair<string, string>(HeaderNames.Path, "/"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "http"),
};
await InitializeConnectionAsync(_appAbort);
await StartStreamAsync(1, headers, endStream: false);
await WaitForStreamErrorAsync(1, Http2ErrorCode.INTERNAL_ERROR, "The connection was aborted by the application.");
async Task AdvanceClockAndSendFrames()
{
if (finalFrameType == Http2FrameType.CONTINUATION)
{
await SendHeadersAsync(1, Http2HeadersFrameFlags.END_STREAM, new byte[0]);
await SendContinuationAsync(1, Http2ContinuationFrameFlags.NONE, new byte[0]);
}
// There's a race when the appfunc is exiting about how soon it unregisters the stream, so retry until success.
while (!closed)
{
// Just past the timeout
mockSystemClock.UtcNow += Constants.RequestBodyDrainTimeout + TimeSpan.FromTicks(1);
// Send an extra frame to make it fail
switch (finalFrameType)
{
case Http2FrameType.DATA:
await SendDataAsync(1, new byte[100], endStream: false);
break;
case Http2FrameType.CONTINUATION:
await SendContinuationAsync(1, Http2ContinuationFrameFlags.NONE, new byte[0]);
break;
default:
throw new NotImplementedException(finalFrameType.ToString());
}
// TODO how do I force a function to go async?
await Task.Delay(1);
}
}
var sendTask = AdvanceClockAndSendFrames();
await WaitForConnectionErrorAsyncDoNotCloseTransport<Http2ConnectionErrorException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: 1,
Http2ErrorCode.STREAM_CLOSED,
CoreStrings.FormatHttp2ErrorStreamClosed(finalFrameType, 1));
closed = true;
await sendTask.DefaultTimeout();
_pair.Application.Output.Complete();
}
private class EchoAppWithNotification
{
private readonly TaskCompletionSource _writeStartedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
public Task WriteStartedTask => _writeStartedTcs.Task;
public async Task RunApp(HttpContext context)
{
await context.Response.Body.FlushAsync();
var buffer = new byte[Http2PeerSettings.MinAllowedMaxFrameSize];
int received;
while ((received = await context.Request.Body.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
var writeTask = context.Response.Body.WriteAsync(buffer, 0, received);
_writeStartedTcs.TrySetResult();
await writeTask;
}
}
}
[Fact]
public async Task DATA_Sent_TooSlowlyDueToSocketBackPressureOnSmallWrite_AbortsConnectionAfterGracePeriod()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinResponseDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
// Disable response buffering so "socket" backpressure is observed immediately.
limits.MaxResponseBufferSize = 0;
var app = new EchoAppWithNotification();
await InitializeConnectionAsync(app.RunApp);
await StartStreamAsync(1, _browserRequestHeaders, endStream: false);
await SendDataAsync(1, _helloWorldBytes, endStream: true);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await app.WriteStartedTask.DefaultTimeout();
// Complete timing of the request body so we don't induce any unexpected request body rate timeouts.
TriggerTick();
// Don't read data frame to induce "socket" backpressure.
AdvanceClock(TimeSpan.FromSeconds((_bytesReceived + _helloWorldBytes.Length) / limits.MinResponseDataRate.BytesPerSecond) +
limits.MinResponseDataRate.GracePeriod + Heartbeat.Interval - TimeSpan.FromSeconds(.5));
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromSeconds(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.WriteDataRate), Times.Once);
// The "hello, world" bytes are buffered from before the timeout, but not an END_STREAM data frame.
await ExpectAsync(Http2FrameType.DATA,
withLength: _helloWorldBytes.Length,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
Assert.True((await _pair.Application.Input.ReadAsync().AsTask().DefaultTimeout()).IsCompleted);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.ConnectionTimedBecauseResponseMininumDataRateNotSatisfied)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Sent_TooSlowlyDueToSocketBackPressureOnLargeWrite_AbortsConnectionAfterRateTimeout()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinResponseDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
// Disable response buffering so "socket" backpressure is observed immediately.
limits.MaxResponseBufferSize = 0;
var app = new EchoAppWithNotification();
await InitializeConnectionAsync(app.RunApp);
await StartStreamAsync(1, _browserRequestHeaders, endStream: false);
await SendDataAsync(1, _maxData, endStream: true);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await app.WriteStartedTask.DefaultTimeout();
// Complete timing of the request body so we don't induce any unexpected request body rate timeouts.
TriggerTick();
var timeToWriteMaxData = TimeSpan.FromSeconds((_bytesReceived + _maxData.Length) / limits.MinResponseDataRate.BytesPerSecond) +
limits.MinResponseDataRate.GracePeriod + Heartbeat.Interval - TimeSpan.FromSeconds(.5);
// Don't read data frame to induce "socket" backpressure.
AdvanceClock(timeToWriteMaxData);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromSeconds(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.WriteDataRate), Times.Once);
// The _maxData bytes are buffered from before the timeout, but not an END_STREAM data frame.
await ExpectAsync(Http2FrameType.DATA,
withLength: _maxData.Length,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
Assert.True((await _pair.Application.Input.ReadAsync().AsTask().DefaultTimeout()).IsCompleted);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.ConnectionTimedBecauseResponseMininumDataRateNotSatisfied)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Sent_TooSlowlyDueToFlowControlOnSmallWrite_AbortsConnectionAfterGracePeriod()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinResponseDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
// This only affects the stream windows. The connection-level window is always initialized at 64KiB.
_clientSettings.InitialWindowSize = 6;
await InitializeConnectionAsync(_echoApplication);
await StartStreamAsync(1, _browserRequestHeaders, endStream: false);
await SendDataAsync(1, _helloWorldBytes, endStream: true);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: (int)_clientSettings.InitialWindowSize,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
// Complete timing of the request body so we don't induce any unexpected request body rate timeouts.
TriggerTick();
// Don't send WINDOW_UPDATE to induce flow-control backpressure
AdvanceClock(TimeSpan.FromSeconds(_bytesReceived / limits.MinResponseDataRate.BytesPerSecond) +
limits.MinResponseDataRate.GracePeriod + Heartbeat.Interval - TimeSpan.FromSeconds(.5));
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromSeconds(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.WriteDataRate), Times.Once);
await WaitForConnectionErrorAsync<ConnectionAbortedException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: int.MaxValue,
Http2ErrorCode.INTERNAL_ERROR,
null);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.ConnectionTimedBecauseResponseMininumDataRateNotSatisfied)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Sent_TooSlowlyDueToOutputFlowControlOnLargeWrite_AbortsConnectionAfterRateTimeout()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinResponseDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
// This only affects the stream windows. The connection-level window is always initialized at 64KiB.
_clientSettings.InitialWindowSize = (uint)_maxData.Length - 1;
await InitializeConnectionAsync(_echoApplication);
await StartStreamAsync(1, _browserRequestHeaders, endStream: false);
await SendDataAsync(1, _maxData, endStream: true);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: (int)_clientSettings.InitialWindowSize,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
// Complete timing of the request body so we don't induce any unexpected request body rate timeouts.
TriggerTick();
var timeToWriteMaxData = TimeSpan.FromSeconds(_bytesReceived / limits.MinResponseDataRate.BytesPerSecond) +
limits.MinResponseDataRate.GracePeriod + Heartbeat.Interval - TimeSpan.FromSeconds(.5);
// Don't send WINDOW_UPDATE to induce flow-control backpressure
AdvanceClock(timeToWriteMaxData);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromSeconds(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.WriteDataRate), Times.Once);
await WaitForConnectionErrorAsync<ConnectionAbortedException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: int.MaxValue,
Http2ErrorCode.INTERNAL_ERROR,
null);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.ConnectionTimedBecauseResponseMininumDataRateNotSatisfied)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Sent_TooSlowlyDueToOutputFlowControlOnMultipleStreams_AbortsConnectionAfterAdditiveRateTimeout()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinResponseDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
// This only affects the stream windows. The connection-level window is always initialized at 64KiB.
_clientSettings.InitialWindowSize = (uint)_maxData.Length - 1;
await InitializeConnectionAsync(_echoApplication);
await StartStreamAsync(1, _browserRequestHeaders, endStream: false);
await SendDataAsync(1, _maxData, endStream: true);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: (int)_clientSettings.InitialWindowSize,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
await StartStreamAsync(3, _browserRequestHeaders, endStream: false);
await SendDataAsync(3, _maxData, endStream: true);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 2,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 3);
await ExpectAsync(Http2FrameType.DATA,
withLength: (int)_clientSettings.InitialWindowSize,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 3);
// Complete timing of the request bodies so we don't induce any unexpected request body rate timeouts.
TriggerTick();
var timeToWriteMaxData = TimeSpan.FromSeconds(_bytesReceived / limits.MinResponseDataRate.BytesPerSecond) +
limits.MinResponseDataRate.GracePeriod + Heartbeat.Interval - TimeSpan.FromSeconds(.5);
// Don't send WINDOW_UPDATE to induce flow-control backpressure
AdvanceClock(timeToWriteMaxData);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromSeconds(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.WriteDataRate), Times.Once);
await WaitForConnectionErrorAsync<ConnectionAbortedException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: int.MaxValue,
Http2ErrorCode.INTERNAL_ERROR,
null);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.ConnectionTimedBecauseResponseMininumDataRateNotSatisfied)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Received_TooSlowlyOnSmallRead_AbortsConnectionAfterGracePeriod()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
await InitializeConnectionAsync(_readRateApplication);
// _helloWorldBytes is 12 bytes, and 12 bytes / 240 bytes/sec = .05 secs which is far below the grace period.
await StartStreamAsync(1, ReadRateRequestHeaders(_helloWorldBytes.Length), endStream: false);
await SendDataAsync(1, _helloWorldBytes, endStream: false);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: 1,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
// Don't send any more data and advance just to and then past the grace period.
AdvanceClock(limits.MinRequestBodyDataRate.GracePeriod);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromTicks(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.ReadDataRate), Times.Once);
await WaitForConnectionErrorAsync<ConnectionAbortedException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: int.MaxValue,
Http2ErrorCode.INTERNAL_ERROR,
null);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.BadRequest_RequestBodyTimeout)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Received_TooSlowlyOnLargeRead_AbortsConnectionAfterRateTimeout()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
await InitializeConnectionAsync(_readRateApplication);
// _maxData is 16 KiB, and 16 KiB / 240 bytes/sec ~= 68 secs which is far above the grace period.
await StartStreamAsync(1, ReadRateRequestHeaders(_maxData.Length), endStream: false);
await SendDataAsync(1, _maxData, endStream: false);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: 1,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
// Due to the imprecision of floating point math and the fact that TimeoutControl derives rate from elapsed
// time for reads instead of vice versa like for writes, use a half-second instead of single-tick cushion.
var timeToReadMaxData = TimeSpan.FromSeconds(_maxData.Length / limits.MinRequestBodyDataRate.BytesPerSecond) - TimeSpan.FromSeconds(.5);
// Don't send any more data and advance just to and then past the rate timeout.
AdvanceClock(timeToReadMaxData);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromSeconds(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.ReadDataRate), Times.Once);
await WaitForConnectionErrorAsync<ConnectionAbortedException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: int.MaxValue,
Http2ErrorCode.INTERNAL_ERROR,
null);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.BadRequest_RequestBodyTimeout)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Received_TooSlowlyOnMultipleStreams_AbortsConnectionAfterAdditiveRateTimeout()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
await InitializeConnectionAsync(_readRateApplication);
// _maxData is 16 KiB, and 16 KiB / 240 bytes/sec ~= 68 secs which is far above the grace period.
await StartStreamAsync(1, ReadRateRequestHeaders(_maxData.Length), endStream: false);
await SendDataAsync(1, _maxData, endStream: false);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: 1,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
await StartStreamAsync(3, ReadRateRequestHeaders(_maxData.Length), endStream: false);
await SendDataAsync(3, _maxData, endStream: false);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 2,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 3);
await ExpectAsync(Http2FrameType.DATA,
withLength: 1,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 3);
var timeToReadMaxData = TimeSpan.FromSeconds(_maxData.Length / limits.MinRequestBodyDataRate.BytesPerSecond);
// Double the timeout for the second stream.
timeToReadMaxData += timeToReadMaxData;
// Due to the imprecision of floating point math and the fact that TimeoutControl derives rate from elapsed
// time for reads instead of vice versa like for writes, use a half-second instead of single-tick cushion.
timeToReadMaxData -= TimeSpan.FromSeconds(.5);
// Don't send any more data and advance just to and then past the rate timeout.
AdvanceClock(timeToReadMaxData);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromSeconds(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.ReadDataRate), Times.Once);
await WaitForConnectionErrorAsync<ConnectionAbortedException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: int.MaxValue,
Http2ErrorCode.INTERNAL_ERROR,
null);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.BadRequest_RequestBodyTimeout)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Received_TooSlowlyOnSecondStream_AbortsConnectionAfterNonAdditiveRateTimeout()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
await InitializeConnectionAsync(_readRateApplication);
// _maxData is 16 KiB, and 16 KiB / 240 bytes/sec ~= 68 secs which is far above the grace period.
await StartStreamAsync(1, ReadRateRequestHeaders(_maxData.Length), endStream: false);
await SendDataAsync(1, _maxData, endStream: true);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: 1,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: 0,
withFlags: (byte)Http2DataFrameFlags.END_STREAM,
withStreamId: 1);
await StartStreamAsync(3, ReadRateRequestHeaders(_maxData.Length), endStream: false);
await SendDataAsync(3, _maxData, endStream: false);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 2,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 3);
await ExpectAsync(Http2FrameType.DATA,
withLength: 1,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 3);
// Due to the imprecision of floating point math and the fact that TimeoutControl derives rate from elapsed
// time for reads instead of vice versa like for writes, use a half-second instead of single-tick cushion.
var timeToReadMaxData = TimeSpan.FromSeconds(_maxData.Length / limits.MinRequestBodyDataRate.BytesPerSecond) - TimeSpan.FromSeconds(.5);
// Don't send any more data and advance just to and then past the rate timeout.
AdvanceClock(timeToReadMaxData);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromSeconds(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.ReadDataRate), Times.Once);
await WaitForConnectionErrorAsync<ConnectionAbortedException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: int.MaxValue,
Http2ErrorCode.INTERNAL_ERROR,
null);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.BadRequest_RequestBodyTimeout)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Received_SlowlyWhenRateLimitDisabledPerRequest_DoesNotAbortConnection()
{
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
await InitializeConnectionAsync(context =>
{
// Completely disable rate limiting for this stream.
context.Features.Get<IHttpMinRequestBodyDataRateFeature>().MinDataRate = null;
return _readRateApplication(context);
});
// _helloWorldBytes is 12 bytes, and 12 bytes / 240 bytes/sec = .05 secs which is far below the grace period.
await StartStreamAsync(1, ReadRateRequestHeaders(_helloWorldBytes.Length), endStream: false);
await SendDataAsync(1, _helloWorldBytes, endStream: false);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 1);
await ExpectAsync(Http2FrameType.DATA,
withLength: 1,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 1);
// Don't send any more data and advance just to and then past the grace period.
AdvanceClock(limits.MinRequestBodyDataRate.GracePeriod);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromTicks(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
await SendDataAsync(1, _helloWorldBytes, endStream: true);
await ExpectAsync(Http2FrameType.DATA,
withLength: 0,
withFlags: (byte)Http2DataFrameFlags.END_STREAM,
withStreamId: 1);
await StopConnectionAsync(expectedLastStreamId: 1, ignoreNonGoAwayFrames: false);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
[Fact]
public async Task DATA_Received_SlowlyDueToConnectionFlowControl_DoesNotAbortConnection()
{
var initialConnectionWindowSize = _serviceContext.ServerOptions.Limits.Http2.InitialConnectionWindowSize;
var framesConnectionInWindow = initialConnectionWindowSize / Http2PeerSettings.DefaultMaxFrameSize;
var backpressureTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var limits = _serviceContext.ServerOptions.Limits;
// Use non-default value to ensure the min request and response rates aren't mixed up.
limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5));
await InitializeConnectionAsync(async context =>
{
var streamId = context.Features.Get<IHttp2StreamIdFeature>().StreamId;
if (streamId == 1)
{
await backpressureTcs.Task;
}
else
{
await _readRateApplication(context);
}
});
await StartStreamAsync(1, _browserRequestHeaders, endStream: false);
for (var i = 0; i < framesConnectionInWindow / 2; i++)
{
await SendDataAsync(1, _maxData, endStream: false);
}
await SendDataAsync(1, _maxData, endStream: true);
await StartStreamAsync(3, ReadRateRequestHeaders(_helloWorldBytes.Length), endStream: false);
await SendDataAsync(3, _helloWorldBytes, endStream: false);
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 32,
withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS,
withStreamId: 3);
await ExpectAsync(Http2FrameType.DATA,
withLength: 1,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 3);
// No matter how much time elapses there is no read timeout because the connection window is too small.
AdvanceClock(TimeSpan.FromDays(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
// Opening the connection window starts the read rate timeout enforcement after that point.
backpressureTcs.SetResult();
await ExpectAsync(Http2FrameType.HEADERS,
withLength: 6,
withFlags: (byte)(Http2HeadersFrameFlags.END_HEADERS | Http2HeadersFrameFlags.END_STREAM),
withStreamId: 1);
var updateFrame = await ExpectAsync(Http2FrameType.WINDOW_UPDATE,
withLength: 4,
withFlags: (byte)Http2DataFrameFlags.NONE,
withStreamId: 0);
var expectedUpdateSize = ((framesConnectionInWindow / 2) + 1) * _maxData.Length + _helloWorldBytes.Length;
Assert.Equal(expectedUpdateSize, updateFrame.WindowUpdateSizeIncrement);
AdvanceClock(limits.MinRequestBodyDataRate.GracePeriod);
_mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never);
AdvanceClock(TimeSpan.FromTicks(1));
_mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.ReadDataRate), Times.Once);
await WaitForConnectionErrorAsync<ConnectionAbortedException>(
ignoreNonGoAwayFrames: false,
expectedLastStreamId: int.MaxValue,
Http2ErrorCode.INTERNAL_ERROR,
null);
_mockConnectionContext.Verify(c => c.Abort(It.Is<ConnectionAbortedException>(e =>
e.Message == CoreStrings.BadRequest_RequestBodyTimeout)), Times.Once);
_mockTimeoutHandler.VerifyNoOtherCalls();
_mockConnectionContext.VerifyNoOtherCalls();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lucene.Net.Search.Spans
{
using Lucene.Net.Support;
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using Bits = Lucene.Net.Util.Bits;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using TermContext = Lucene.Net.Index.TermContext;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// Matches the union of its clauses. </summary>
public class SpanOrQuery : SpanQuery, ICloneable
{
private readonly IList<SpanQuery> clauses;
private string field;
/// <summary>
/// Construct a SpanOrQuery merging the provided clauses. </summary>
public SpanOrQuery(params SpanQuery[] clauses)
{
// copy clauses array into an ArrayList
this.clauses = new List<SpanQuery>(clauses.Length);
for (int i = 0; i < clauses.Length; i++)
{
AddClause(clauses[i]);
}
}
/// <summary>
/// Adds a clause to this query </summary>
public void AddClause(SpanQuery clause)
{
if (field == null)
{
field = clause.Field;
}
else if (clause.Field != null && !clause.Field.Equals(field))
{
throw new System.ArgumentException("Clauses must have same field.");
}
this.clauses.Add(clause);
}
/// <summary>
/// Return the clauses whose spans are matched. </summary>
public virtual SpanQuery[] Clauses
{
get
{
return clauses.ToArray();
}
}
public override string Field
{
get
{
return field;
}
}
public override void ExtractTerms(ISet<Term> terms)
{
foreach (SpanQuery clause in clauses)
{
clause.ExtractTerms(terms);
}
}
public override object Clone()
{
int sz = clauses.Count;
SpanQuery[] newClauses = new SpanQuery[sz];
for (int i = 0; i < sz; i++)
{
newClauses[i] = (SpanQuery)clauses[i].Clone();
}
SpanOrQuery soq = new SpanOrQuery(newClauses);
soq.Boost = Boost;
return soq;
}
public override Query Rewrite(IndexReader reader)
{
SpanOrQuery clone = null;
for (int i = 0; i < clauses.Count; i++)
{
SpanQuery c = clauses[i];
SpanQuery query = (SpanQuery)c.Rewrite(reader);
if (query != c) // clause rewrote: must clone
{
if (clone == null)
{
clone = (SpanOrQuery)this.Clone();
}
clone.clauses[i] = query;
}
}
if (clone != null)
{
return clone; // some clauses rewrote
}
else
{
return this; // no clauses rewrote
}
}
public override string ToString(string field)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("spanOr([");
IEnumerator<SpanQuery> i = clauses.GetEnumerator();
while (i.MoveNext())
{
SpanQuery clause = i.Current;
buffer.Append(clause.ToString(field));
buffer.Append(", ");
}
//LUCENE TO-DO
if (clauses.Count > 0)
buffer.Remove(buffer.Length - 2, 2);
buffer.Append("])");
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override bool Equals(object o)
{
if (this == o)
{
return true;
}
if (o == null || this.GetType() != o.GetType())
{
return false;
}
SpanOrQuery that = (SpanOrQuery)o;
if (!clauses.SequenceEqual(that.clauses))
{
return false;
}
return Boost == that.Boost;
}
public override int GetHashCode()
{
//If this doesn't work, hash all elemnts together instead. This version was used to reduce time complexity
int h = clauses.Count == 0 ? 0 : HashHelpers.CombineHashCodes(clauses.First().GetHashCode(), clauses.Last().GetHashCode(), clauses.Count);
h ^= (h << 10) | ((int)(((uint)h) >> 23));
h ^= Number.FloatToIntBits(Boost);
return h;
}
private class SpanQueue : Util.PriorityQueue<Spans>
{
private readonly SpanOrQuery OuterInstance;
public SpanQueue(SpanOrQuery outerInstance, int size)
: base(size)
{
this.OuterInstance = outerInstance;
}
public override bool LessThan(Spans spans1, Spans spans2)
{
if (spans1.Doc() == spans2.Doc())
{
if (spans1.Start() == spans2.Start())
{
return spans1.End() < spans2.End();
}
else
{
return spans1.Start() < spans2.Start();
}
}
else
{
return spans1.Doc() < spans2.Doc();
}
}
}
public override Spans GetSpans(AtomicReaderContext context, Bits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
if (clauses.Count == 1) // optimize 1-clause case
{
return (clauses[0]).GetSpans(context, acceptDocs, termContexts);
}
return new SpansAnonymousInnerClassHelper(this, context, acceptDocs, termContexts);
}
private class SpansAnonymousInnerClassHelper : Spans
{
private readonly SpanOrQuery OuterInstance;
private AtomicReaderContext Context;
private Bits AcceptDocs;
private IDictionary<Term, TermContext> TermContexts;
public SpansAnonymousInnerClassHelper(SpanOrQuery outerInstance, AtomicReaderContext context, Bits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
this.OuterInstance = outerInstance;
this.Context = context;
this.AcceptDocs = acceptDocs;
this.TermContexts = termContexts;
queue = null;
}
private SpanQueue queue;
private long cost;
private bool InitSpanQueue(int target)
{
queue = new SpanQueue(OuterInstance, OuterInstance.clauses.Count);
IEnumerator<SpanQuery> i = OuterInstance.clauses.GetEnumerator();
while (i.MoveNext())
{
Spans spans = i.Current.GetSpans(Context, AcceptDocs, TermContexts);
cost += spans.Cost();
if (((target == -1) && spans.Next()) || ((target != -1) && spans.SkipTo(target)))
{
queue.Add(spans);
}
}
return queue.Size() != 0;
}
public override bool Next()
{
if (queue == null)
{
return InitSpanQueue(-1);
}
if (queue.Size() == 0) // all done
{
return false;
}
if (Top().Next()) // move to next
{
queue.UpdateTop();
return true;
}
queue.Pop(); // exhausted a clause
return queue.Size() != 0;
}
private Spans Top()
{
return queue.Top();
}
public override bool SkipTo(int target)
{
if (queue == null)
{
return InitSpanQueue(target);
}
bool skipCalled = false;
while (queue.Size() != 0 && Top().Doc() < target)
{
if (Top().SkipTo(target))
{
queue.UpdateTop();
}
else
{
queue.Pop();
}
skipCalled = true;
}
if (skipCalled)
{
return queue.Size() != 0;
}
return Next();
}
public override int Doc()
{
return Top().Doc();
}
public override int Start()
{
return Top().Start();
}
public override int End()
{
return Top().End();
}
public override ICollection<byte[]> Payload
{
get
{
List<byte[]> result = null;
Spans theTop = Top();
if (theTop != null && theTop.PayloadAvailable)
{
result = new List<byte[]>(theTop.Payload);
}
return result;
}
}
public override bool PayloadAvailable
{
get
{
Spans top = Top();
return top != null && top.PayloadAvailable;
}
}
public override string ToString()
{
return "spans(" + OuterInstance + ")@" + ((queue == null) ? "START" : (queue.Size() > 0 ? (Doc() + ":" + Start() + "-" + End()) : "END"));
}
public override long Cost()
{
return cost;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MyWaves.Web.Areas.HelpPage.ModelDescriptions;
using MyWaves.Web.Areas.HelpPage.Models;
namespace MyWaves.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* 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.
*/
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Apache.Ignite.Core.Tests.Cache.Query
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Queries tests.
/// </summary>
public class CacheQueriesTest
{
/** Grid count. */
private const int GridCnt = 2;
/** Cache name. */
private const string CacheName = "cache";
/** Path to XML configuration. */
private const string CfgPath = "config\\cache-query.xml";
/** Maximum amount of items in cache. */
private const int MaxItemCnt = 100;
/// <summary>
/// Fixture setup.
/// </summary>
[TestFixtureSetUp]
public void StartGrids()
{
for (int i = 0; i < GridCnt; i++)
{
Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
NameMapper = GetNameMapper()
},
SpringConfigUrl = CfgPath,
IgniteInstanceName = "grid-" + i
});
}
}
/// <summary>
/// Gets the name mapper.
/// </summary>
protected virtual IBinaryNameMapper GetNameMapper()
{
return BinaryBasicNameMapper.FullNameInstance;
}
/// <summary>
/// Fixture teardown.
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
///
/// </summary>
[TearDown]
public void AfterTest()
{
var cache = Cache();
for (int i = 0; i < GridCnt; i++)
{
cache.Clear();
Assert.IsTrue(cache.IsEmpty());
}
TestUtils.AssertHandleRegistryIsEmpty(300,
Enumerable.Range(0, GridCnt).Select(x => Ignition.GetIgnite("grid-" + x)).ToArray());
Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
/// Gets the ignite.
/// </summary>
private static IIgnite GetIgnite()
{
return Ignition.GetIgnite("grid-0");
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static ICache<int, QueryPerson> Cache()
{
return GetIgnite().GetCache<int, QueryPerson>(CacheName);
}
/// <summary>
/// Test arguments validation for SQL queries.
/// </summary>
[Test]
public void TestValidationSql()
{
// 1. No sql.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new SqlQuery(typeof(QueryPerson), null)); });
// 2. No type.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new SqlQuery((string)null, "age >= 50")); });
}
/// <summary>
/// Test arguments validation for SQL fields queries.
/// </summary>
[Test]
public void TestValidationSqlFields()
{
// 1. No sql.
Assert.Throws<ArgumentException>(() => { Cache().QueryFields(new SqlFieldsQuery(null)); });
}
/// <summary>
/// Test arguments validation for TEXT queries.
/// </summary>
[Test]
public void TestValidationText()
{
// 1. No text.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new TextQuery(typeof(QueryPerson), null)); });
// 2. No type.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new TextQuery((string)null, "Ivanov")); });
}
/// <summary>
/// Cursor tests.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")]
public void TestCursor()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(1, new QueryPerson("Petrov", 40));
Cache().Put(1, new QueryPerson("Sidorov", 50));
SqlQuery qry = new SqlQuery(typeof(QueryPerson), "age >= 20");
// 1. Test GetAll().
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
cursor.GetAll();
Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); });
Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); });
}
// 2. Test GetEnumerator.
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
cursor.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); });
Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); });
}
}
/// <summary>
/// Test enumerator.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "UnusedVariable")]
public void TestEnumerator()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
Cache().Put(4, new QueryPerson("Unknown", 60));
// 1. Empty result set.
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor =
Cache().Query(new SqlQuery(typeof(QueryPerson), "age = 100")))
{
IEnumerator<ICacheEntry<int, QueryPerson>> e = cursor.GetEnumerator();
Assert.Throws<InvalidOperationException>(() =>
{ ICacheEntry<int, QueryPerson> entry = e.Current; });
Assert.IsFalse(e.MoveNext());
Assert.Throws<InvalidOperationException>(() =>
{ ICacheEntry<int, QueryPerson> entry = e.Current; });
Assert.Throws<NotSupportedException>(() => e.Reset());
e.Dispose();
}
SqlQuery qry = new SqlQuery(typeof (QueryPerson), "age < 60");
Assert.AreEqual(QueryBase.DefaultPageSize, qry.PageSize);
// 2. Page size is bigger than result set.
qry.PageSize = 4;
CheckEnumeratorQuery(qry);
// 3. Page size equal to result set.
qry.PageSize = 3;
CheckEnumeratorQuery(qry);
// 4. Page size if less than result set.
qry.PageSize = 2;
CheckEnumeratorQuery(qry);
}
/// <summary>
/// Test SQL query arguments passing.
/// </summary>
[Test]
public void TestSqlQueryArguments()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
// 1. Empty result set.
using (
IQueryCursor<ICacheEntry<int, QueryPerson>> cursor =
Cache().Query(new SqlQuery(typeof(QueryPerson), "age < ?", 50)))
{
foreach (ICacheEntry<int, QueryPerson> entry in cursor.GetAll())
Assert.IsTrue(entry.Key == 1 || entry.Key == 2);
}
}
/// <summary>
/// Test SQL fields query arguments passing.
/// </summary>
[Test]
public void TestSqlFieldsQueryArguments()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
// 1. Empty result set.
using (
IQueryCursor<IList> cursor = Cache().QueryFields(
new SqlFieldsQuery("SELECT age FROM QueryPerson WHERE age < ?", 50)))
{
foreach (IList entry in cursor.GetAll())
Assert.IsTrue((int) entry[0] < 50);
}
}
/// <summary>
/// Check query result for enumerator test.
/// </summary>
/// <param name="qry">QUery.</param>
private void CheckEnumeratorQuery(SqlQuery qry)
{
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
bool first = false;
bool second = false;
bool third = false;
foreach (var entry in cursor)
{
if (entry.Key == 1)
{
first = true;
Assert.AreEqual("Ivanov", entry.Value.Name);
Assert.AreEqual(30, entry.Value.Age);
}
else if (entry.Key == 2)
{
second = true;
Assert.AreEqual("Petrov", entry.Value.Name);
Assert.AreEqual(40, entry.Value.Age);
}
else if (entry.Key == 3)
{
third = true;
Assert.AreEqual("Sidorov", entry.Value.Name);
Assert.AreEqual(50, entry.Value.Age);
}
else
Assert.Fail("Unexpected value: " + entry);
}
Assert.IsTrue(first && second && third);
}
}
/// <summary>
/// Check SQL query.
/// </summary>
[Test]
public void TestSqlQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary,
[Values(true, false)] bool distrJoin)
{
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, MaxItemCnt, x => x < 50);
// 2. Validate results.
var qry = new SqlQuery(typeof(QueryPerson), "age < 50", loc)
{
EnableDistributedJoins = distrJoin,
ReplicatedOnly = false,
Timeout = TimeSpan.FromSeconds(3)
};
Assert.AreEqual(string.Format("SqlQuery [Sql=age < 50, Arguments=[], Local={0}, " +
"PageSize=1024, EnableDistributedJoins={1}, Timeout={2}, " +
"ReplicatedOnly=False]", loc, distrJoin, qry.Timeout), qry.ToString());
ValidateQueryResults(cache, qry, exp, keepBinary);
}
/// <summary>
/// Check SQL fields query.
/// </summary>
[Test]
public void TestSqlFieldsQuery([Values(true, false)] bool loc, [Values(true, false)] bool distrJoin,
[Values(true, false)] bool enforceJoinOrder)
{
int cnt = MaxItemCnt;
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, cnt, x => x < 50);
// 2. Validate results.
var qry = new SqlFieldsQuery("SELECT name, age FROM QueryPerson WHERE age < 50")
{
EnableDistributedJoins = distrJoin,
EnforceJoinOrder = enforceJoinOrder,
Colocated = !distrJoin,
ReplicatedOnly = false,
Local = loc,
Timeout = TimeSpan.FromSeconds(2)
};
using (IQueryCursor<IList> cursor = cache.QueryFields(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
foreach (var entry in cursor.GetAll())
{
Assert.AreEqual(2, entry.Count);
Assert.AreEqual(entry[0].ToString(), entry[1].ToString());
exp0.Remove((int)entry[1]);
}
Assert.AreEqual(0, exp0.Count);
}
using (IQueryCursor<IList> cursor = cache.QueryFields(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
foreach (var entry in cursor)
{
Assert.AreEqual(entry[0].ToString(), entry[1].ToString());
exp0.Remove((int)entry[1]);
}
Assert.AreEqual(0, exp0.Count);
}
}
/// <summary>
/// Check text query.
/// </summary>
[Test]
public void TestTextQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary)
{
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, MaxItemCnt, x => x.ToString().StartsWith("1"));
// 2. Validate results.
var qry = new TextQuery(typeof(QueryPerson), "1*", loc);
ValidateQueryResults(cache, qry, exp, keepBinary);
}
/// <summary>
/// Check scan query.
/// </summary>
[Test]
public void TestScanQuery([Values(true, false)] bool loc)
{
CheckScanQuery<QueryPerson>(loc, false);
}
/// <summary>
/// Check scan query in binary mode.
/// </summary>
[Test]
public void TestScanQueryBinary([Values(true, false)] bool loc)
{
CheckScanQuery<IBinaryObject>(loc, true);
}
/// <summary>
/// Check scan query with partitions.
/// </summary>
[Test]
public void TestScanQueryPartitions([Values(true, false)] bool loc)
{
CheckScanQueryPartitions<QueryPerson>(loc, false);
}
/// <summary>
/// Check scan query with partitions in binary mode.
/// </summary>
[Test]
public void TestScanQueryPartitionsBinary([Values(true, false)] bool loc)
{
CheckScanQueryPartitions<IBinaryObject>(loc, true);
}
/// <summary>
/// Tests that query attempt on non-indexed cache causes an exception.
/// </summary>
[Test]
public void TestIndexingDisabledError()
{
var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>("nonindexed_cache");
// Text query.
var err = Assert.Throws<IgniteException>(() => cache.Query(new TextQuery(typeof(QueryPerson), "1*")));
Assert.AreEqual("Indexing is disabled for cache: nonindexed_cache. " +
"Use setIndexedTypes or setTypeMetadata methods on CacheConfiguration to enable.", err.Message);
// SQL query.
err = Assert.Throws<IgniteException>(() => cache.Query(new SqlQuery(typeof(QueryPerson), "age < 50")));
Assert.AreEqual("Failed to find SQL table for type: QueryPerson", err.Message);
}
/// <summary>
/// Check scan query.
/// </summary>
/// <param name="loc">Local query flag.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private static void CheckScanQuery<TV>(bool loc, bool keepBinary)
{
var cache = Cache();
int cnt = MaxItemCnt;
// No predicate
var exp = PopulateCache(cache, loc, cnt, x => true);
var qry = new ScanQuery<int, TV>();
ValidateQueryResults(cache, qry, exp, keepBinary);
// Serializable
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>());
ValidateQueryResults(cache, qry, exp, keepBinary);
// Binarizable
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new BinarizableScanQueryFilter<TV>());
ValidateQueryResults(cache, qry, exp, keepBinary);
// Invalid
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new InvalidScanQueryFilter<TV>());
Assert.Throws<BinaryObjectException>(() => ValidateQueryResults(cache, qry, exp, keepBinary));
// Exception
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV> {ThrowErr = true});
var ex = Assert.Throws<IgniteException>(() => ValidateQueryResults(cache, qry, exp, keepBinary));
Assert.AreEqual(ScanQueryFilter<TV>.ErrMessage, ex.Message);
}
/// <summary>
/// Checks scan query with partitions.
/// </summary>
/// <param name="loc">Local query flag.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private void CheckScanQueryPartitions<TV>(bool loc, bool keepBinary)
{
StopGrids();
StartGrids();
var cache = Cache();
int cnt = MaxItemCnt;
var aff = cache.Ignite.GetAffinity(CacheName);
var exp = PopulateCache(cache, loc, cnt, x => true); // populate outside the loop (slow)
for (var part = 0; part < aff.Partitions; part++)
{
//var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys
var exp0 = new HashSet<int>();
foreach (var x in exp)
if (aff.GetPartition(x) == part)
exp0.Add(x);
var qry = new ScanQuery<int, TV> { Partition = part };
ValidateQueryResults(cache, qry, exp0, keepBinary);
}
// Partitions with predicate
exp = PopulateCache(cache, loc, cnt, x => x < 50); // populate outside the loop (slow)
for (var part = 0; part < aff.Partitions; part++)
{
//var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys
var exp0 = new HashSet<int>();
foreach (var x in exp)
if (aff.GetPartition(x) == part)
exp0.Add(x);
var qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()) { Partition = part };
ValidateQueryResults(cache, qry, exp0, keepBinary);
}
}
/// <summary>
/// Tests custom schema name.
/// </summary>
[Test]
public void TestCustomSchema()
{
var doubles = GetIgnite().GetOrCreateCache<int, double>(new CacheConfiguration("doubles", typeof(double)));
var strings = GetIgnite().GetOrCreateCache<int, string>(new CacheConfiguration("strings", typeof(string)));
doubles[1] = 36.6;
strings[1] = "foo";
// Default schema.
var res = doubles.QueryFields(new SqlFieldsQuery(
"select S._val from double as D join \"strings\".string as S on S._key = D._key"))
.Select(x => (string) x[0])
.Single();
Assert.AreEqual("foo", res);
// Custom schema.
res = doubles.QueryFields(new SqlFieldsQuery(
"select S._val from \"doubles\".double as D join string as S on S._key = D._key")
{
Schema = strings.Name
})
.Select(x => (string)x[0])
.Single();
Assert.AreEqual("foo", res);
}
/// <summary>
/// Tests the distributed joins flag.
/// </summary>
[Test]
public void TestDistributedJoins()
{
var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>(
new CacheConfiguration("replicatedCache")
{
QueryEntities = new[]
{
new QueryEntity(typeof(int), typeof(QueryPerson))
{
Fields = new[] {new QueryField("age", "int")}
}
}
});
const int count = 100;
cache.PutAll(Enumerable.Range(0, count).ToDictionary(x => x, x => new QueryPerson("Name" + x, x)));
// Test non-distributed join: returns partial results
var sql = "select T0.Age from QueryPerson as T0 " +
"inner join QueryPerson as T1 on ((? - T1.Age - 1) = T0._key)";
var res = cache.QueryFields(new SqlFieldsQuery(sql, count)).GetAll().Distinct().Count();
Assert.Greater(res, 0);
Assert.Less(res, count);
// Test distributed join: returns complete results
res = cache.QueryFields(new SqlFieldsQuery(sql, count) {EnableDistributedJoins = true})
.GetAll().Distinct().Count();
Assert.AreEqual(count, res);
}
/// <summary>
/// Tests the get configuration.
/// </summary>
[Test]
public void TestGetConfiguration()
{
var entity = Cache().GetConfiguration().QueryEntities.Single();
Assert.AreEqual(typeof(int), entity.Fields.Single(x => x.Name == "age").FieldType);
Assert.AreEqual(typeof(string), entity.Fields.Single(x => x.Name == "name").FieldType);
}
/// <summary>
/// Tests custom key and value field names.
/// </summary>
[Test]
public void TestCustomKeyValueFieldNames()
{
// Check select * with default config - does not include _key, _val.
var cache = Cache();
cache[1] = new QueryPerson("Joe", 48);
var row = cache.QueryFields(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0];
Assert.AreEqual(2, row.Count);
Assert.AreEqual(48, row[0]);
Assert.AreEqual("Joe", row[1]);
// Check select * with custom names - fields are included.
cache = GetIgnite().GetOrCreateCache<int, QueryPerson>(
new CacheConfiguration("customKeyVal")
{
QueryEntities = new[]
{
new QueryEntity(typeof(int), typeof(QueryPerson))
{
Fields = new[]
{
new QueryField("age", "int"),
new QueryField("FullKey", "int"),
new QueryField("FullVal", "QueryPerson")
},
KeyFieldName = "FullKey",
ValueFieldName = "FullVal"
}
}
});
cache[1] = new QueryPerson("John", 33);
row = cache.QueryFields(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0];
Assert.AreEqual(3, row.Count);
Assert.AreEqual(33, row[0]);
Assert.AreEqual(1, row[1]);
var person = (QueryPerson) row[2];
Assert.AreEqual("John", person.Name);
// Check explicit select.
row = cache.QueryFields(new SqlFieldsQuery("select FullKey from QueryPerson")).GetAll()[0];
Assert.AreEqual(1, row[0]);
}
/// <summary>
/// Tests query timeouts.
/// </summary>
[Test]
public void TestSqlQueryTimeout()
{
var cache = Cache();
PopulateCache(cache, false, 20000, x => true);
var sqlQry = new SqlQuery(typeof(QueryPerson), "WHERE age < 500 AND name like '%1%'")
{
Timeout = TimeSpan.FromMilliseconds(2)
};
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
var ex = Assert.Throws<CacheException>(() => cache.Query(sqlQry).ToArray());
Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing."));
}
/// <summary>
/// Tests fields query timeouts.
/// </summary>
[Test]
public void TestSqlFieldsQueryTimeout()
{
var cache = Cache();
PopulateCache(cache, false, 20000, x => true);
var fieldsQry = new SqlFieldsQuery("SELECT * FROM QueryPerson WHERE age < 5000 AND name like '%0%'")
{
Timeout = TimeSpan.FromMilliseconds(3)
};
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
var ex = Assert.Throws<CacheException>(() => cache.QueryFields(fieldsQry).ToArray());
Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing."));
}
/// <summary>
/// Validates the query results.
/// </summary>
/// <param name="cache">Cache.</param>
/// <param name="qry">Query.</param>
/// <param name="exp">Expected keys.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private static void ValidateQueryResults(ICache<int, QueryPerson> cache, QueryBase qry, HashSet<int> exp,
bool keepBinary)
{
if (keepBinary)
{
var cache0 = cache.WithKeepBinary<int, IBinaryObject>();
using (var cursor = cache0.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor.GetAll())
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name"));
Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age"));
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
using (var cursor = cache0.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor)
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name"));
Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age"));
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
}
else
{
using (var cursor = cache.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor.GetAll())
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.Name);
Assert.AreEqual(entry.Key, entry.Value.Age);
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
using (var cursor = cache.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor)
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.Name);
Assert.AreEqual(entry.Key, entry.Value.Age);
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
}
}
/// <summary>
/// Asserts that all expected entries have been received.
/// </summary>
private static void AssertMissingExpectedKeys(ICollection<int> exp, ICache<int, QueryPerson> cache,
IList<ICacheEntry<int, object>> all)
{
if (exp.Count == 0)
return;
var sb = new StringBuilder();
var aff = cache.Ignite.GetAffinity(cache.Name);
foreach (var key in exp)
{
var part = aff.GetPartition(key);
sb.AppendFormat(
"Query did not return expected key '{0}' (exists: {1}), partition '{2}', partition nodes: ",
key, cache.Get(key) != null, part);
var partNodes = aff.MapPartitionToPrimaryAndBackups(part);
foreach (var node in partNodes)
sb.Append(node).Append(" ");
sb.AppendLine(";");
}
sb.Append("Returned keys: ");
foreach (var e in all)
sb.Append(e.Key).Append(" ");
sb.AppendLine(";");
Assert.Fail(sb.ToString());
}
/// <summary>
/// Populates the cache with random entries and returns expected results set according to filter.
/// </summary>
/// <param name="cache">The cache.</param>
/// <param name="cnt">Amount of cache entries to create.</param>
/// <param name="loc">Local query flag.</param>
/// <param name="expectedEntryFilter">The expected entry filter.</param>
/// <returns>Expected results set.</returns>
private static HashSet<int> PopulateCache(ICache<int, QueryPerson> cache, bool loc, int cnt,
Func<int, bool> expectedEntryFilter)
{
var rand = new Random();
for (var i = 0; i < cnt; i++)
{
var val = rand.Next(cnt);
cache.Put(val, new QueryPerson(val.ToString(), val));
}
var entries = loc
? cache.GetLocalEntries(CachePeekMode.Primary)
: cache;
return new HashSet<int>(entries.Select(x => x.Key).Where(expectedEntryFilter));
}
}
/// <summary>
/// Person.
/// </summary>
public class QueryPerson
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="age">Age.</param>
public QueryPerson(string name, int age)
{
Name = name;
Age = age % 2000;
Birthday = DateTime.UtcNow.AddYears(-Age);
}
/// <summary>
/// Name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Age.
/// </summary>
public int Age { get; set; }
/// <summary>
/// Gets or sets the birthday.
/// </summary>
[QuerySqlField] // Enforce Timestamp serialization
public DateTime Birthday { get; set; }
}
/// <summary>
/// Query filter.
/// </summary>
[Serializable]
public class ScanQueryFilter<TV> : ICacheEntryFilter<int, TV>
{
// Error message
public const string ErrMessage = "Error in ScanQueryFilter.Invoke";
// Error flag
public bool ThrowErr { get; set; }
// Injection test
[InstanceResource]
public IIgnite Ignite { get; set; }
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, TV> entry)
{
Assert.IsNotNull(Ignite);
if (ThrowErr)
throw new Exception(ErrMessage);
return entry.Key < 50;
}
}
/// <summary>
/// binary query filter.
/// </summary>
public class BinarizableScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable
{
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
var w = writer.GetRawWriter();
w.WriteBoolean(ThrowErr);
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
var r = reader.GetRawReader();
ThrowErr = r.ReadBoolean();
}
}
/// <summary>
/// Filter that can't be serialized.
/// </summary>
public class InvalidScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.Linq;
using osu.Framework;
using osu.Framework.Caching;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using OpenTK;
using OpenTK.Graphics;
namespace osu.Game.Screens.Play
{
public class SquareGraph : BufferedContainer
{
private Column[] columns = { };
public int ColumnCount => columns.Length;
public override bool HandleInput => false;
private int progress;
public int Progress
{
get { return progress; }
set
{
if (value == progress) return;
progress = value;
redrawProgress();
}
}
private float[] calculatedValues = { }; // values but adjusted to fit the amount of columns
private int[] values;
public int[] Values
{
get { return values; }
set
{
if (value == values) return;
values = value;
layout.Invalidate();
}
}
private Color4 fillColour;
public Color4 FillColour
{
get { return fillColour; }
set
{
if (value == fillColour) return;
fillColour = value;
redrawFilled();
}
}
public SquareGraph()
{
CacheDrawnFrameBuffer = true;
}
private Cached layout = new Cached();
public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true)
{
if ((invalidation & Invalidation.DrawSize) > 0)
layout.Invalidate();
return base.Invalidate(invalidation, source, shallPropagate);
}
protected override void Update()
{
base.Update();
layout.Refresh(recreateGraph);
}
/// <summary>
/// Redraws all the columns to match their lit/dimmed state.
/// </summary>
private void redrawProgress()
{
for (int i = 0; i < columns.Length; i++)
columns[i].State = i <= progress ? ColumnState.Lit : ColumnState.Dimmed;
ForceRedraw();
}
/// <summary>
/// Redraws the filled amount of all the columns.
/// </summary>
private void redrawFilled()
{
for (int i = 0; i < ColumnCount; i++)
columns[i].Filled = calculatedValues.ElementAtOrDefault(i);
ForceRedraw();
}
/// <summary>
/// Takes <see cref="Values"/> and adjusts it to fit the amount of columns.
/// </summary>
private void recalculateValues()
{
var newValues = new List<float>();
if (values == null)
{
for (float i = 0; i < ColumnCount; i++)
newValues.Add(0);
return;
}
var max = values.Max();
float step = values.Length / (float)ColumnCount;
for (float i = 0; i < values.Length; i += step)
{
newValues.Add((float)values[(int)i] / max);
}
calculatedValues = newValues.ToArray();
}
/// <summary>
/// Recreates the entire graph.
/// </summary>
private void recreateGraph()
{
var newColumns = new List<Column>();
for (float x = 0; x < DrawWidth; x += Column.WIDTH)
{
newColumns.Add(new Column
{
LitColour = fillColour,
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Height = DrawHeight,
Position = new Vector2(x, 0),
State = ColumnState.Dimmed,
});
}
columns = newColumns.ToArray();
Children = columns;
recalculateValues();
redrawFilled();
redrawProgress();
}
public class Column : Container, IStateful<ColumnState>
{
protected readonly Color4 EmptyColour = Color4.White.Opacity(20);
public Color4 LitColour = Color4.LightBlue;
protected readonly Color4 DimmedColour = Color4.White.Opacity(140);
private float cubeCount => DrawHeight / WIDTH;
private const float cube_size = 4;
private const float padding = 2;
public const float WIDTH = cube_size + padding;
private readonly List<Box> drawableRows = new List<Box>();
private float filled;
public float Filled
{
get { return filled; }
set
{
if (value == filled) return;
filled = value;
fillActive();
}
}
private ColumnState state;
public ColumnState State
{
get { return state; }
set
{
if (value == state) return;
state = value;
if (IsLoaded)
fillActive();
}
}
public Column()
{
Width = WIDTH;
}
protected override void LoadComplete()
{
for (int r = 0; r < cubeCount; r++)
{
drawableRows.Add(new Box
{
Size = new Vector2(cube_size),
Position = new Vector2(0, r * WIDTH + padding),
});
}
Children = drawableRows;
// Reverse drawableRows so when iterating through them they start at the bottom
drawableRows.Reverse();
fillActive();
}
private void fillActive()
{
Color4 colour = State == ColumnState.Lit ? LitColour : DimmedColour;
int countFilled = (int)MathHelper.Clamp(filled * drawableRows.Count, 0, drawableRows.Count);
for (int i = 0; i < drawableRows.Count; i++)
drawableRows[i].Colour = i < countFilled ? colour : EmptyColour;
}
}
public enum ColumnState
{
Lit,
Dimmed
}
}
}
| |
using System.Collections;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Iana;
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.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
namespace Org.BouncyCastle.Security
{
public sealed class GeneratorUtilities
{
private GeneratorUtilities()
{
}
private static readonly IDictionary kgAlgorithms = Platform.CreateHashtable();
private static readonly IDictionary kpgAlgorithms = Platform.CreateHashtable();
private static readonly IDictionary defaultKeySizes = Platform.CreateHashtable();
static GeneratorUtilities()
{
//
// key generators.
//
AddKgAlgorithm("AES",
"AESWRAP");
AddKgAlgorithm("AES128",
"2.16.840.1.101.3.4.2",
NistObjectIdentifiers.IdAes128Cbc,
NistObjectIdentifiers.IdAes128Cfb,
NistObjectIdentifiers.IdAes128Ecb,
NistObjectIdentifiers.IdAes128Ofb,
NistObjectIdentifiers.IdAes128Wrap);
AddKgAlgorithm("AES192",
"2.16.840.1.101.3.4.22",
NistObjectIdentifiers.IdAes192Cbc,
NistObjectIdentifiers.IdAes192Cfb,
NistObjectIdentifiers.IdAes192Ecb,
NistObjectIdentifiers.IdAes192Ofb,
NistObjectIdentifiers.IdAes192Wrap);
AddKgAlgorithm("AES256",
"2.16.840.1.101.3.4.42",
NistObjectIdentifiers.IdAes256Cbc,
NistObjectIdentifiers.IdAes256Cfb,
NistObjectIdentifiers.IdAes256Ecb,
NistObjectIdentifiers.IdAes256Ofb,
NistObjectIdentifiers.IdAes256Wrap);
AddKgAlgorithm("BLOWFISH",
"1.3.6.1.4.1.3029.1.2");
AddKgAlgorithm("CAMELLIA",
"CAMELLIAWRAP");
AddKgAlgorithm("CAMELLIA128",
NttObjectIdentifiers.IdCamellia128Cbc,
NttObjectIdentifiers.IdCamellia128Wrap);
AddKgAlgorithm("CAMELLIA192",
NttObjectIdentifiers.IdCamellia192Cbc,
NttObjectIdentifiers.IdCamellia192Wrap);
AddKgAlgorithm("CAMELLIA256",
NttObjectIdentifiers.IdCamellia256Cbc,
NttObjectIdentifiers.IdCamellia256Wrap);
AddKgAlgorithm("CAST5",
"1.2.840.113533.7.66.10");
AddKgAlgorithm("CAST6");
AddKgAlgorithm("DES",
OiwObjectIdentifiers.DesCbc,
OiwObjectIdentifiers.DesCfb,
OiwObjectIdentifiers.DesEcb,
OiwObjectIdentifiers.DesOfb);
AddKgAlgorithm("DESEDE",
"DESEDEWRAP",
OiwObjectIdentifiers.DesEde);
AddKgAlgorithm("DESEDE3",
PkcsObjectIdentifiers.DesEde3Cbc,
PkcsObjectIdentifiers.IdAlgCms3DesWrap);
AddKgAlgorithm("GOST28147",
"GOST",
"GOST-28147",
CryptoProObjectIdentifiers.GostR28147Cbc);
AddKgAlgorithm("HC128");
AddKgAlgorithm("HC256");
AddKgAlgorithm("IDEA",
"1.3.6.1.4.1.188.7.1.1.2");
AddKgAlgorithm("NOEKEON");
AddKgAlgorithm("RC2",
PkcsObjectIdentifiers.RC2Cbc,
PkcsObjectIdentifiers.IdAlgCmsRC2Wrap);
AddKgAlgorithm("RC4",
"ARC4",
"1.2.840.113549.3.4");
AddKgAlgorithm("RC5",
"RC5-32");
AddKgAlgorithm("RC5-64");
AddKgAlgorithm("RC6");
AddKgAlgorithm("RIJNDAEL");
AddKgAlgorithm("SALSA20");
AddKgAlgorithm("SEED",
KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap,
KisaObjectIdentifiers.IdSeedCbc);
AddKgAlgorithm("SERPENT");
AddKgAlgorithm("SKIPJACK");
AddKgAlgorithm("TEA");
AddKgAlgorithm("TWOFISH");
AddKgAlgorithm("VMPC");
AddKgAlgorithm("VMPC-KSA3");
AddKgAlgorithm("XTEA");
//
// HMac key generators
//
AddHMacKeyGenerator("MD2");
AddHMacKeyGenerator("MD4");
AddHMacKeyGenerator("MD5",
IanaObjectIdentifiers.HmacMD5);
AddHMacKeyGenerator("SHA1",
PkcsObjectIdentifiers.IdHmacWithSha1,
IanaObjectIdentifiers.HmacSha1);
AddHMacKeyGenerator("SHA224",
PkcsObjectIdentifiers.IdHmacWithSha224);
AddHMacKeyGenerator("SHA256",
PkcsObjectIdentifiers.IdHmacWithSha256);
AddHMacKeyGenerator("SHA384",
PkcsObjectIdentifiers.IdHmacWithSha384);
AddHMacKeyGenerator("SHA512",
PkcsObjectIdentifiers.IdHmacWithSha512);
AddHMacKeyGenerator("RIPEMD128");
AddHMacKeyGenerator("RIPEMD160",
IanaObjectIdentifiers.HmacRipeMD160);
AddHMacKeyGenerator("TIGER",
IanaObjectIdentifiers.HmacTiger);
//
// key pair generators.
//
AddKpgAlgorithm("DH",
"DIFFIEHELLMAN");
AddKpgAlgorithm("DSA");
AddKpgAlgorithm("EC",
// TODO Should this be an alias for ECDH?
X9ObjectIdentifiers.DHSinglePassStdDHSha1KdfScheme);
AddKpgAlgorithm("ECDH",
"ECIES");
AddKpgAlgorithm("ECDHC");
AddKpgAlgorithm("ECMQV",
X9ObjectIdentifiers.MqvSinglePassSha1KdfScheme);
AddKpgAlgorithm("ECDSA");
AddKpgAlgorithm("ECGOST3410",
"ECGOST-3410",
"GOST-3410-2001");
AddKpgAlgorithm("ELGAMAL");
AddKpgAlgorithm("GOST3410",
"GOST-3410",
"GOST-3410-94");
AddKpgAlgorithm("RSA",
"1.2.840.113549.1.1.1");
AddDefaultKeySizeEntries(64, "DES");
AddDefaultKeySizeEntries(80, "SKIPJACK");
AddDefaultKeySizeEntries(128, "AES128", "BLOWFISH", "CAMELLIA128", "CAST5", "DESEDE",
"HC128", "HMACMD2", "HMACMD4", "HMACMD5", "HMACRIPEMD128", "IDEA", "NOEKEON",
"RC2", "RC4", "RC5", "SALSA20", "SEED", "TEA", "XTEA", "VMPC", "VMPC-KSA3");
AddDefaultKeySizeEntries(160, "HMACRIPEMD160", "HMACSHA1");
AddDefaultKeySizeEntries(192, "AES", "AES192", "CAMELLIA192", "DESEDE3", "HMACTIGER",
"RIJNDAEL", "SERPENT");
AddDefaultKeySizeEntries(224, "HMACSHA224");
AddDefaultKeySizeEntries(256, "AES256", "CAMELLIA", "CAMELLIA256", "CAST6", "GOST28147",
"HC256", "HMACSHA256", "RC5-64", "RC6", "TWOFISH");
AddDefaultKeySizeEntries(384, "HMACSHA384");
AddDefaultKeySizeEntries(512, "HMACSHA512");
}
private static void AddDefaultKeySizeEntries(int size, params string[] algorithms)
{
foreach (string algorithm in algorithms)
{
defaultKeySizes.Add(algorithm, size);
}
}
private static void AddKgAlgorithm(
string canonicalName,
params object[] aliases)
{
kgAlgorithms[canonicalName] = canonicalName;
foreach (object alias in aliases)
{
kgAlgorithms[alias.ToString()] = canonicalName;
}
}
private static void AddKpgAlgorithm(
string canonicalName,
params object[] aliases)
{
kpgAlgorithms[canonicalName] = canonicalName;
foreach (object alias in aliases)
{
kpgAlgorithms[alias.ToString()] = canonicalName;
}
}
private static void AddHMacKeyGenerator(
string algorithm,
params object[] aliases)
{
string mainName = "HMAC" + algorithm;
kgAlgorithms[mainName] = mainName;
kgAlgorithms["HMAC-" + algorithm] = mainName;
kgAlgorithms["HMAC/" + algorithm] = mainName;
foreach (object alias in aliases)
{
kgAlgorithms[alias.ToString()] = mainName;
}
}
// TODO Consider making this public
internal static string GetCanonicalKeyGeneratorAlgorithm(
string algorithm)
{
return (string) kgAlgorithms[Platform.ToUpperInvariant(algorithm)];
}
// TODO Consider making this public
internal static string GetCanonicalKeyPairGeneratorAlgorithm(
string algorithm)
{
return (string)kpgAlgorithms[Platform.ToUpperInvariant(algorithm)];
}
public static CipherKeyGenerator GetKeyGenerator(
DerObjectIdentifier oid)
{
return GetKeyGenerator(oid.Id);
}
public static CipherKeyGenerator GetKeyGenerator(
string algorithm)
{
string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm);
if (canonicalName == null)
throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised.");
int defaultKeySize = FindDefaultKeySize(canonicalName);
if (defaultKeySize == -1)
throw new SecurityUtilityException("KeyGenerator " + algorithm
+ " (" + canonicalName + ") not supported.");
if (canonicalName == "DES")
return new DesKeyGenerator(defaultKeySize);
if (canonicalName == "DESEDE" || canonicalName == "DESEDE3")
return new DesEdeKeyGenerator(defaultKeySize);
return new CipherKeyGenerator(defaultKeySize);
}
public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator(
DerObjectIdentifier oid)
{
return GetKeyPairGenerator(oid.Id);
}
public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator(
string algorithm)
{
string canonicalName = GetCanonicalKeyPairGeneratorAlgorithm(algorithm);
if (canonicalName == null)
throw new SecurityUtilityException("KeyPairGenerator " + algorithm + " not recognised.");
if (canonicalName == "DH")
return new DHKeyPairGenerator();
if (canonicalName == "DSA")
return new DsaKeyPairGenerator();
// "EC", "ECDH", "ECDHC", "ECDSA", "ECGOST3410", "ECMQV"
if (canonicalName.StartsWith("EC"))
return new ECKeyPairGenerator(canonicalName);
if (canonicalName == "ELGAMAL")
return new ElGamalKeyPairGenerator();
if (canonicalName == "GOST3410")
return new Gost3410KeyPairGenerator();
if (canonicalName == "RSA")
return new RsaKeyPairGenerator();
throw new SecurityUtilityException("KeyPairGenerator " + algorithm
+ " (" + canonicalName + ") not supported.");
}
internal static int GetDefaultKeySize(
DerObjectIdentifier oid)
{
return GetDefaultKeySize(oid.Id);
}
internal static int GetDefaultKeySize(
string algorithm)
{
string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm);
if (canonicalName == null)
throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised.");
int defaultKeySize = FindDefaultKeySize(canonicalName);
if (defaultKeySize == -1)
throw new SecurityUtilityException("KeyGenerator " + algorithm
+ " (" + canonicalName + ") not supported.");
return defaultKeySize;
}
private static int FindDefaultKeySize(
string canonicalName)
{
if (!defaultKeySizes.Contains(canonicalName))
return -1;
return (int)defaultKeySizes[canonicalName];
}
}
}
| |
using NUnit.Framework;
using System;
using System.Linq;
namespace Braintree.Tests.Integration
{
[TestFixture]
public class MerchantIntegrationTest
{
private BraintreeGateway gateway;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway(
"client_id$development$integration_client_id",
"client_secret$development$integration_client_secret"
);
}
[Test]
public void Create_ReturnsMerchantAndCredentials()
{
ResultImpl<Merchant> result = gateway.Merchant.Create(new MerchantRequest {
Email = "name@email.com",
CountryCodeAlpha3 = "USA",
PaymentMethods = new string[] {"credit_card", "paypal"},
Scope = "read_write,shared_vault_transactions",
});
Assert.IsTrue(result.IsSuccess());
Assert.IsFalse(string.IsNullOrEmpty(result.Target.Id));
Assert.AreEqual("name@email.com", result.Target.Email);
Assert.AreEqual("name@email.com", result.Target.CompanyName);
Assert.AreEqual("USA", result.Target.CountryCodeAlpha3);
Assert.AreEqual("US", result.Target.CountryCodeAlpha2);
Assert.AreEqual("840", result.Target.CountryCodeNumeric);
Assert.AreEqual("United States of America", result.Target.CountryName);
Assert.IsTrue(result.Target.Credentials.AccessToken.StartsWith("access_token$"));
Assert.IsTrue(result.Target.Credentials.RefreshToken.StartsWith("refresh_token$"));
Assert.IsTrue(result.Target.Credentials.ExpiresAt > DateTime.Now);
Assert.AreEqual("bearer", result.Target.Credentials.TokenType);
Assert.AreEqual("read_write,shared_vault_transactions", result.Target.Credentials.Scope);
}
[Test]
public void Create_FailsWithInvalidPaymentMethods()
{
ResultImpl<Merchant> result = gateway.Merchant.Create(new MerchantRequest {
Email = "name@email.com",
CountryCodeAlpha3 = "USA",
PaymentMethods = new string[] {"fake_money"}
});
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.MERCHANT_PAYMENT_METHODS_ARE_INVALID,
result.Errors.ForObject("merchant").OnField("payment-methods")[0].Code
);
}
[Test]
public void Create_MultiCurrencyMerchant()
{
gateway = new BraintreeGateway(
"client_id$development$signup_client_id",
"client_secret$development$signup_client_secret"
);
ResultImpl<Merchant> result = gateway.Merchant.Create(new MerchantRequest {
Email = "name@email.com",
CountryCodeAlpha3 = "USA",
PaymentMethods = new string[] {"credit_card", "paypal"},
CompanyName = "Ziarog LTD",
Currencies = new string[] {"GBP", "USD"}
});
Assert.IsTrue(result.IsSuccess());
Assert.IsFalse(string.IsNullOrEmpty(result.Target.Id));
Assert.AreEqual("name@email.com", result.Target.Email);
Assert.AreEqual("Ziarog LTD", result.Target.CompanyName);
Assert.AreEqual("USA", result.Target.CountryCodeAlpha3);
Assert.AreEqual("US", result.Target.CountryCodeAlpha2);
Assert.AreEqual("840", result.Target.CountryCodeNumeric);
Assert.AreEqual("United States of America", result.Target.CountryName);
Assert.IsTrue(result.Target.Credentials.AccessToken.StartsWith("access_token$"));
Assert.IsTrue(result.Target.Credentials.RefreshToken.StartsWith("refresh_token$"));
Assert.IsTrue(result.Target.Credentials.ExpiresAt > DateTime.Now);
Assert.AreEqual("bearer", result.Target.Credentials.TokenType);
Assert.AreEqual(2, result.Target.MerchantAccounts.Length);
var usdMerchantAccount = (from ma in result.Target.MerchantAccounts where ma.Id == "USD" select ma).ToArray()[0];
Assert.AreEqual("USD", usdMerchantAccount.CurrencyIsoCode);
Assert.IsTrue(usdMerchantAccount.IsDefault.Value);
var gbpMerchantAccount = (from ma in result.Target.MerchantAccounts where ma.Id == "GBP" select ma).ToArray()[0];
Assert.AreEqual("GBP", gbpMerchantAccount.CurrencyIsoCode);
Assert.IsFalse(gbpMerchantAccount.IsDefault.Value);
}
[Test]
public void Create_PayPalOnlyMultiCurrencyMerchant()
{
gateway = new BraintreeGateway(
"client_id$development$signup_client_id",
"client_secret$development$signup_client_secret"
);
ResultImpl<Merchant> result = gateway.Merchant.Create(new MerchantRequest {
Email = "name@email.com",
CountryCodeAlpha3 = "USA",
PaymentMethods = new string[] {"paypal"},
CompanyName = "Ziarog LTD",
Currencies = new string[] {"GBP", "USD"},
PayPalAccount = new PayPalOnlyAccountRequest {
ClientId = "paypal_client_id",
ClientSecret = "paypal_client_secret"
}
});
Assert.IsTrue(result.IsSuccess());
Assert.IsFalse(string.IsNullOrEmpty(result.Target.Id));
Assert.AreEqual("name@email.com", result.Target.Email);
Assert.AreEqual("Ziarog LTD", result.Target.CompanyName);
Assert.AreEqual("USA", result.Target.CountryCodeAlpha3);
Assert.AreEqual("US", result.Target.CountryCodeAlpha2);
Assert.AreEqual("840", result.Target.CountryCodeNumeric);
Assert.AreEqual("United States of America", result.Target.CountryName);
Assert.IsTrue(result.Target.Credentials.AccessToken.StartsWith("access_token$"));
Assert.IsTrue(result.Target.Credentials.RefreshToken.StartsWith("refresh_token$"));
Assert.IsTrue(result.Target.Credentials.ExpiresAt > DateTime.Now);
Assert.AreEqual("bearer", result.Target.Credentials.TokenType);
Assert.AreEqual(2, result.Target.MerchantAccounts.Length);
var usdMerchantAccount = (from ma in result.Target.MerchantAccounts where ma.Id == "USD" select ma).ToArray()[0];
Assert.AreEqual("USD", usdMerchantAccount.CurrencyIsoCode);
Assert.IsTrue(usdMerchantAccount.IsDefault.Value);
var gbpMerchantAccount = (from ma in result.Target.MerchantAccounts where ma.Id == "GBP" select ma).ToArray()[0];
Assert.AreEqual("GBP", gbpMerchantAccount.CurrencyIsoCode);
Assert.IsFalse(gbpMerchantAccount.IsDefault.Value);
}
[Test]
public void Create_AllowsCreationOfNonUSMerchantIfOnboardingApplicationIsInternal()
{
gateway = new BraintreeGateway(
"client_id$development$signup_client_id",
"client_secret$development$signup_client_secret"
);
ResultImpl<Merchant> result = gateway.Merchant.Create(new MerchantRequest {
Email = "name@email.com",
CountryCodeAlpha3 = "JPN",
PaymentMethods = new string[] {"paypal"},
PayPalAccount = new PayPalOnlyAccountRequest {
ClientId = "paypal_client_id",
ClientSecret = "paypal_client_secret"
}
});
Assert.IsTrue(result.IsSuccess());
Assert.IsFalse(string.IsNullOrEmpty(result.Target.Id));
Assert.AreEqual("name@email.com", result.Target.Email);
Assert.AreEqual("name@email.com", result.Target.CompanyName);
Assert.AreEqual("JPN", result.Target.CountryCodeAlpha3);
Assert.AreEqual("JP", result.Target.CountryCodeAlpha2);
Assert.AreEqual("392", result.Target.CountryCodeNumeric);
Assert.AreEqual("Japan", result.Target.CountryName);
Assert.IsTrue(result.Target.Credentials.AccessToken.StartsWith("access_token$"));
Assert.IsTrue(result.Target.Credentials.RefreshToken.StartsWith("refresh_token$"));
Assert.IsTrue(result.Target.Credentials.ExpiresAt > DateTime.Now);
Assert.AreEqual("bearer", result.Target.Credentials.TokenType);
Assert.AreEqual(1, result.Target.MerchantAccounts.Length);
var merchantAccount = result.Target.MerchantAccounts[0];
Assert.AreEqual("JPY", merchantAccount.CurrencyIsoCode);
Assert.IsTrue(merchantAccount.IsDefault.Value);
}
[Test]
public void Create_DefaultsToUSDForNonUSMerchantIfOnboardingApplicationIsInternalAndCountryCurrencyNotSupported()
{
gateway = new BraintreeGateway(
"client_id$development$signup_client_id",
"client_secret$development$signup_client_secret"
);
ResultImpl<Merchant> result = gateway.Merchant.Create(new MerchantRequest {
Email = "name@email.com",
CountryCodeAlpha3 = "YEM",
PaymentMethods = new string[] {"paypal"},
PayPalAccount = new PayPalOnlyAccountRequest {
ClientId = "paypal_client_id",
ClientSecret = "paypal_client_secret"
}
});
Assert.IsTrue(result.IsSuccess());
Assert.IsFalse(string.IsNullOrEmpty(result.Target.Id));
Assert.AreEqual("name@email.com", result.Target.Email);
Assert.AreEqual("name@email.com", result.Target.CompanyName);
Assert.AreEqual("YEM", result.Target.CountryCodeAlpha3);
Assert.AreEqual("YE", result.Target.CountryCodeAlpha2);
Assert.AreEqual("887", result.Target.CountryCodeNumeric);
Assert.AreEqual("Yemen", result.Target.CountryName);
Assert.IsTrue(result.Target.Credentials.AccessToken.StartsWith("access_token$"));
Assert.IsTrue(result.Target.Credentials.RefreshToken.StartsWith("refresh_token$"));
Assert.IsTrue(result.Target.Credentials.ExpiresAt > DateTime.Now);
Assert.AreEqual("bearer", result.Target.Credentials.TokenType);
Assert.AreEqual(1, result.Target.MerchantAccounts.Length);
var merchantAccount = result.Target.MerchantAccounts[0];
Assert.AreEqual("USD", merchantAccount.CurrencyIsoCode);
Assert.IsTrue(merchantAccount.IsDefault.Value);
}
[Test]
public void Create_ReturnsErrorIfInvalidCurrencyPassed()
{
gateway = new BraintreeGateway(
"client_id$development$signup_client_id",
"client_secret$development$signup_client_secret"
);
ResultImpl<Merchant> result = gateway.Merchant.Create(new MerchantRequest {
Email = "name@email.com",
CountryCodeAlpha3 = "USA",
PaymentMethods = new string[] {"paypal"},
Currencies = new string[] {"GBP", "FAKE"},
PayPalAccount = new PayPalOnlyAccountRequest {
ClientId = "paypal_client_id",
ClientSecret = "paypal_client_secret"
}
});
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.MERCHANT_CURRENCIES_ARE_INVALID,
result.Errors.ForObject("merchant").OnField("currencies")[0].Code
);
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// 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
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Base for handling both client side and server side calls.
/// Manages native call lifecycle and provides convenience methods.
/// </summary>
internal abstract class AsyncCallBase<TWrite, TRead> : IReceivedMessageCallback, ISendCompletionCallback
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>();
protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message.");
readonly Action<TWrite, SerializationContext> serializer;
readonly Func<DeserializationContext, TRead> deserializer;
protected readonly object myLock = new object();
protected INativeCall call;
protected bool disposed;
protected bool started;
protected bool cancelRequested;
protected TaskCompletionSource<TRead> streamingReadTcs; // Completion of a pending streaming read if not null.
protected TaskCompletionSource<object> streamingWriteTcs; // Completion of a pending streaming write or send close from client if not null.
protected TaskCompletionSource<object> sendStatusFromServerTcs;
protected bool isStreamingWriteCompletionDelayed; // Only used for the client side.
protected bool readingDone; // True if last read (i.e. read with null payload) was already received.
protected bool halfcloseRequested; // True if send close have been initiated.
protected bool finished; // True if close has been received from the peer.
protected bool initialMetadataSent;
protected long streamingWritesCounter; // Number of streaming send operations started so far.
public AsyncCallBase(Action<TWrite, SerializationContext> serializer, Func<DeserializationContext, TRead> deserializer)
{
this.serializer = GrpcPreconditions.CheckNotNull(serializer);
this.deserializer = GrpcPreconditions.CheckNotNull(deserializer);
}
/// <summary>
/// Requests cancelling the call.
/// </summary>
public void Cancel()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.Cancel();
}
}
}
/// <summary>
/// Requests cancelling the call with given status.
/// </summary>
protected void CancelWithStatus(Status status)
{
lock (myLock)
{
cancelRequested = true;
if (!disposed)
{
call.CancelWithStatus(status);
}
}
}
protected void InitializeInternal(INativeCall call)
{
lock (myLock)
{
this.call = call;
}
}
/// <summary>
/// Initiates sending a message. Only one send operation can be active at a time.
/// </summary>
protected Task SendMessageInternalAsync(TWrite msg, WriteFlags writeFlags)
{
using (var serializationScope = DefaultSerializationContext.GetInitializedThreadLocalScope())
{
var payload = UnsafeSerialize(msg, serializationScope.Context);
lock (myLock)
{
GrpcPreconditions.CheckState(started);
var earlyResult = CheckSendAllowedOrEarlyResult();
if (earlyResult != null)
{
return earlyResult;
}
call.StartSendMessage(SendCompletionCallback, payload, writeFlags, !initialMetadataSent);
initialMetadataSent = true;
streamingWritesCounter++;
streamingWriteTcs = new TaskCompletionSource<object>();
return streamingWriteTcs.Task;
}
}
}
/// <summary>
/// Initiates reading a message. Only one read operation can be active at a time.
/// </summary>
protected Task<TRead> ReadMessageInternalAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
if (readingDone)
{
// the last read that returns null or throws an exception is idempotent
// and maintains its state.
GrpcPreconditions.CheckState(streamingReadTcs != null, "Call does not support streaming reads.");
return streamingReadTcs.Task;
}
GrpcPreconditions.CheckState(streamingReadTcs == null, "Only one read can be pending at a time");
GrpcPreconditions.CheckState(!disposed);
call.StartReceiveMessage(ReceivedMessageCallback);
streamingReadTcs = new TaskCompletionSource<TRead>();
return streamingReadTcs.Task;
}
}
/// <summary>
/// If there are no more pending actions and no new actions can be started, releases
/// the underlying native resources.
/// </summary>
protected bool ReleaseResourcesIfPossible()
{
if (!disposed && call != null)
{
bool noMoreSendCompletions = streamingWriteTcs == null && (halfcloseRequested || cancelRequested || finished);
if (noMoreSendCompletions && readingDone && finished)
{
ReleaseResources();
return true;
}
}
return false;
}
protected abstract bool IsClient
{
get;
}
/// <summary>
/// Returns an exception to throw for a failed send operation.
/// It is only allowed to call this method for a call that has already finished.
/// </summary>
protected abstract Exception GetRpcExceptionClientOnly();
protected void ReleaseResources()
{
if (call != null)
{
call.Dispose();
}
disposed = true;
OnAfterReleaseResourcesLocked();
}
protected virtual void OnAfterReleaseResourcesLocked()
{
}
protected virtual void OnAfterReleaseResourcesUnlocked()
{
}
/// <summary>
/// Checks if sending is allowed and possibly returns a Task that allows short-circuiting the send
/// logic by directly returning the write operation result task. Normally, null is returned.
/// </summary>
protected abstract Task CheckSendAllowedOrEarlyResult();
// runs the serializer, propagating any exceptions being thrown without modifying them
protected SliceBufferSafeHandle UnsafeSerialize(TWrite msg, DefaultSerializationContext context)
{
serializer(msg, context);
return context.GetPayload();
}
protected Exception TryDeserialize(IBufferReader reader, out TRead msg)
{
DefaultDeserializationContext context = null;
try
{
context = DefaultDeserializationContext.GetInitializedThreadLocal(reader);
msg = deserializer(context);
return null;
}
catch (Exception e)
{
msg = default(TRead);
return e;
}
finally
{
context?.Reset();
}
}
/// <summary>
/// Handles send completion (including SendCloseFromClient).
/// </summary>
protected void HandleSendFinished(bool success)
{
bool delayCompletion = false;
TaskCompletionSource<object> origTcs = null;
bool releasedResources;
lock (myLock)
{
if (!success && !finished && IsClient) {
// We should be setting this only once per call, following writes will be short circuited
// because they cannot start until the entire call finishes.
GrpcPreconditions.CheckState(!isStreamingWriteCompletionDelayed);
// leave streamingWriteTcs set, it will be completed once call finished.
isStreamingWriteCompletionDelayed = true;
delayCompletion = true;
}
else
{
origTcs = streamingWriteTcs;
streamingWriteTcs = null;
}
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (!success)
{
if (!delayCompletion)
{
if (IsClient)
{
GrpcPreconditions.CheckState(finished); // implied by !success && !delayCompletion && IsClient
origTcs.SetException(GetRpcExceptionClientOnly());
}
else
{
origTcs.SetException (new IOException("Error sending from server."));
}
}
// if delayCompletion == true, postpone SetException until call finishes.
}
else
{
origTcs.SetResult(null);
}
}
/// <summary>
/// Handles send status from server completion.
/// </summary>
protected void HandleSendStatusFromServerFinished(bool success)
{
bool releasedResources;
lock (myLock)
{
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (!success)
{
sendStatusFromServerTcs.SetException(new IOException("Error sending status from server."));
}
else
{
sendStatusFromServerTcs.SetResult(null);
}
}
/// <summary>
/// Handles streaming read completion.
/// </summary>
protected void HandleReadFinished(bool success, IBufferReader receivedMessageReader)
{
// if success == false, the message reader will report null payload. It that case we will
// treat this completion as the last read an rely on C core to handle the failed
// read (e.g. deliver approriate statusCode on the clientside).
TRead msg = default(TRead);
var deserializeException = (success && receivedMessageReader.TotalLength.HasValue) ? TryDeserialize(receivedMessageReader, out msg) : null;
TaskCompletionSource<TRead> origTcs = null;
bool releasedResources;
lock (myLock)
{
origTcs = streamingReadTcs;
if (!receivedMessageReader.TotalLength.HasValue)
{
// This was the last read.
readingDone = true;
}
if (deserializeException != null && IsClient)
{
readingDone = true;
// TODO(jtattermusch): it might be too late to set the status
CancelWithStatus(DeserializeResponseFailureStatus);
}
if (!readingDone)
{
streamingReadTcs = null;
}
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (deserializeException != null && !IsClient)
{
origTcs.SetException(new IOException("Failed to deserialize request message.", deserializeException));
return;
}
origTcs.SetResult(msg);
}
protected ISendCompletionCallback SendCompletionCallback => this;
void ISendCompletionCallback.OnSendCompletion(bool success)
{
HandleSendFinished(success);
}
IReceivedMessageCallback ReceivedMessageCallback => this;
void IReceivedMessageCallback.OnReceivedMessage(bool success, IBufferReader receivedMessageReader)
{
HandleReadFinished(success, receivedMessageReader);
}
internal CancellationTokenRegistration RegisterCancellationCallbackForToken(CancellationToken cancellationToken)
{
if (cancellationToken.CanBeCanceled) return cancellationToken.Register(CancelCallFromToken, this);
return default(CancellationTokenRegistration);
}
private static readonly Action<object> CancelCallFromToken = state => ((AsyncCallBase<TWrite, TRead>)state).Cancel();
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
using mvc5.Models;
using mvc5.Services;
using mvc5.ViewModels.Manage;
namespace mvc5.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// GET: /Manage/RemovePhoneNumber
[HttpGet]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.GetUserId());
return new ChallengeResult(provider, properties);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId());
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
#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.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Internal.Runtime.Augments;
using Microsoft.Win32.SafeHandles;
namespace System.Threading
{
/// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// // Wait subsystem
///
/// ////////////////////////////////////////////////////////////////
/// // Types
///
/// <see cref="WaitSubsystem"/>
/// - Static API surface for dealing with synchronization objects that support multi-wait, and to put a thread into a wait
/// state, on Unix
/// - Any interaction with the wait subsystem from outside should go through APIs on this class, and should not directly
/// go through any of the nested classes
///
/// <see cref="WaitableObject"/>
/// - An object that supports the features of <see cref="EventWaitHandle"/>, <see cref="Semaphore"/>, and
/// <see cref="Mutex"/>. The handle of each of those classes is associated with a <see cref="WaitableObject"/>.
///
/// <see cref="ThreadWaitInfo"/>
/// - Keeps information about a thread's wait and provides functionlity to put a thread into a wait state and to take it
/// out of a wait state. Each thread has an instance available through <see cref="RuntimeThread.WaitInfo"/>.
///
/// <see cref="HandleManager"/>
/// - Provides functionality to allocate a handle associated with a <see cref="WaitableObject"/>, to retrieve the object
/// from a handle, and to delete a handle.
///
/// <see cref="WaitHandleArray{T}"/>
/// - Used to precreate an array that will be used for storing information about a multi-wait operation, and dynamically
/// resize up to the maximum capacity <see cref="WaitHandle.MaxWaitHandles"/> as needed
///
/// <see cref="LowLevelLock"/> and <see cref="LowLevelMonitor"/>
/// - These are "low level" in the sense they don't depend on this wait subsystem, and any waits done are not
/// interruptible
/// - <see cref="LowLevelLock"/> is used for the process-wide lock <see cref="s_lock"/>
/// - <see cref="LowLevelMonitor"/> is the main system dependency of the wait subsystem, and all waits are done through
/// it. It is backed by a C++ equivalent in CoreLib.Native's pal_threading.*, which wraps a pthread mutex/condition
/// pair. Each thread has an instance in <see cref="ThreadWaitInfo._waitMonitor"/>, which is used to synchronize the
/// thread's wait state and for waiting. <see cref="LowLevelLock"/> also uses an instance of
/// <see cref="LowLevelMonitor"/> for waiting.
///
/// ////////////////////////////////////////////////////////////////
/// // Design goals
///
/// Behave similarly to wait operations on Windows
/// - The design is similar to the one used by CoreCLR's PAL, but much simpler due to there being no need for supporting
/// process/thread waits, or cross-process multi-waits (which CoreCLR also does not support but there are many design
/// elements specific to it)
/// - Waiting
/// - A waiter keeps an array of objects on which it is waiting (see <see cref="ThreadWaitInfo._waitedObjects"/>).
/// - The waiter registers a <see cref="ThreadWaitInfo.WaitedListNode"/> with each <see cref="WaitableObject"/>
/// - The waiter waits on its own <see cref="ThreadWaitInfo._waitMonitor"/> to go into a wait state
/// - Upon timeout, the waiter unregisters the wait and continues
/// - Sleeping
/// - Sleeping is just another way of waiting, only there would not be any waited objects
/// - Signaling
/// - A signaler iterates over waiters and tries to release waiters based on the signal count
/// - For each waiter, the signaler checks if the waiter's wait can be terminated
/// - When a waiter's wait can be terminated, the signaler does everything necesary before waking the waiter, such that
/// the waiter can simply continue after awakening, including unregistering the wait and assigning ownership if
/// applicable
/// - Interrupting
/// - Interrupting is just another way of signaling a waiting thread. The interrupter unregisters the wait and wakes the
/// waiter.
/// - Wait release fairness
/// - As mentioned above in how signaling works, waiters are released in fair order (first come, first served)
/// - This is mostly done to match the behavior of synchronization objects in Windows, which are also fair
/// - Events have an implicit requirement to be fair
/// - For a <see cref="ManualResetEvent"/>, Set/Reset in quick succession requires that it wakes up all waiters,
/// implying that the design cannot be to signal a thread to wake and have it check the state when it awakens some
/// time in the future
/// - For an <see cref="AutoResetEvent"/>, Set/Set in quick succession requires that it wakes up two threads, implying
/// that a Set/Wait in quick succession cannot have the calling thread accept its own signal if there is a waiter
/// - There is an advantage to being fair, as it guarantees that threads are only awakened when necessary. That is, a
/// thread will never wake up and find that it has to go back to sleep because the wait is not satisfied (except due
/// to spurious wakeups caused by external factors).
/// - Synchronization
/// - A process-wide lock <see cref="s_lock"/> is used to synchronize most operations and the signal state of all
/// <see cref="WaitableObject"/>s in the process. Given that it is recommended to use alternative synchronization
/// types (<see cref="ManualResetEventSlim"/>, <see cref="SemaphoreSlim"/>, <see cref="Monitor"/>) for single-wait
/// cases, it is probably not worth optimizing for the single-wait case. It is possible with a small design change to
/// bypass the lock and use interlocked operations for uncontended cases, but at the cost of making multi-waits more
/// complicated and slower.
/// - The wait state of a thread (<see cref="ThreadWaitInfo._waitSignalState"/>), among other things, is synchornized
/// using the thread's <see cref="ThreadWaitInfo._waitMonitor"/>, so signalers and interrupters acquire the monitor's
/// lock before checking the wait state of a thread and signaling the thread to wake up.
///
/// Self-consistent in the event of any exception
/// - Try/finally is used extensively, including around any operation that could fail due to out-of-memory
///
/// Decent balance between memory usage and performance
/// - <see cref="WaitableObject"/> is intended to be as small as possible while avoiding virtual calls and casts
/// - As <see cref="Mutex"/> is not commonly used and requires more state, some of its state is separated into
/// <see cref="WaitableObject._ownershipInfo"/>
/// - When support for cross-process objects is added, the current thought is to have an <see cref="object"/> field that
/// is used for both cross-process state and ownership state.
///
/// No allocation in typical cases of any operation except where necessary
/// - Since the maximum number of wait handles for a multi-wait operation is limited to
/// <see cref="WaitHandle.MaxWaitHandles"/>, arrays necessary for holding information about a multi-wait, and list nodes
/// necessary for registering a wait, are precreated using <see cref="WaitHandleArray{T}"/> with a low initial capacity
/// that covers most typical cases
/// - Threads track owned mutexes by linking the <see cref="WaitableObject.OwnershipInfo"/> instance into a linked list
/// <see cref="ThreadWaitInfo.LockedMutexesHead"/>. <see cref="WaitableObject.OwnershipInfo"/> is itself a list node,
/// and is created along with the mutex <see cref="WaitableObject"/>.
///
/// Minimal p/invokes in typical uncontended cases
/// - <see cref="HandleManager"/> currently uses <see cref="Runtime.InteropServices.GCHandle"/> in the interest of
/// simplicity, which p/invokes and does a cast to get the <see cref="WaitableObject"/> from a handle
/// - Most of the wait subsystem is written in C#, so there is no initially required p/invoke
/// - <see cref="LowLevelLock"/>, used by the process-wide lock <see cref="s_lock"/>, uses interlocked operations to
/// acquire and release the lock when there is no need to wait or to release a waiter. This is significantly faster than
/// using <see cref="LowLevelMonitor"/> as a lock, which uses pthread mutex functionality through p/invoke. The lock is
/// typically not held for very long, especially since allocations inside the lock will be rare.
/// - Since <see cref="s_lock"/> provides mutual exclusion for the states of all <see cref="WaitableObject"/>s in the
/// process, any operation that does not involve waiting or releasing a wait can occur with minimal p/invokes
///
/// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[EagerStaticClassConstruction] // the wait subsystem is used during lazy class construction
internal static partial class WaitSubsystem
{
private static readonly LowLevelLock s_lock = new LowLevelLock();
private static SafeWaitHandle NewHandle(WaitableObject waitableObject)
{
IntPtr handle = HandleManager.NewHandle(waitableObject);
SafeWaitHandle safeWaitHandle = null;
try
{
safeWaitHandle = new SafeWaitHandle(handle, ownsHandle: true);
return safeWaitHandle;
}
finally
{
if (safeWaitHandle == null)
{
HandleManager.DeleteHandle(handle);
}
}
}
public static SafeWaitHandle NewEvent(bool initiallySignaled, EventResetMode resetMode)
{
return NewHandle(WaitableObject.NewEvent(initiallySignaled, resetMode));
}
public static SafeWaitHandle NewSemaphore(int initialSignalCount, int maximumSignalCount)
{
return NewHandle(WaitableObject.NewSemaphore(initialSignalCount, maximumSignalCount));
}
public static SafeWaitHandle NewMutex(bool initiallyOwned)
{
WaitableObject waitableObject = WaitableObject.NewMutex();
SafeWaitHandle safeWaitHandle = NewHandle(waitableObject);
if (!initiallyOwned)
{
return safeWaitHandle;
}
/// Acquire the mutex. A thread's <see cref="ThreadWaitInfo"/> has a reference to all <see cref="Mutex"/>es locked
/// by the thread. See <see cref="ThreadWaitInfo.LockedMutexesHead"/>. So, acquire the lock only after all
/// possibilities for exceptions have been exhausted.
ThreadWaitInfo waitInfo = RuntimeThread.CurrentThread.WaitInfo;
bool acquiredLock = waitableObject.Wait(waitInfo, timeoutMilliseconds: 0, interruptible: false, prioritize: false);
Debug.Assert(acquiredLock);
return safeWaitHandle;
}
public static void DeleteHandle(IntPtr handle)
{
HandleManager.DeleteHandle(handle);
}
public static void SetEvent(IntPtr handle)
{
SetEvent(HandleManager.FromHandle(handle));
}
public static void SetEvent(WaitableObject waitableObject)
{
Debug.Assert(waitableObject != null);
s_lock.Acquire();
try
{
waitableObject.SignalEvent();
}
finally
{
s_lock.Release();
}
}
public static void ResetEvent(IntPtr handle)
{
ResetEvent(HandleManager.FromHandle(handle));
}
public static void ResetEvent(WaitableObject waitableObject)
{
Debug.Assert(waitableObject != null);
s_lock.Acquire();
try
{
waitableObject.UnsignalEvent();
}
finally
{
s_lock.Release();
}
}
public static int ReleaseSemaphore(IntPtr handle, int count)
{
Debug.Assert(count > 0);
return ReleaseSemaphore(HandleManager.FromHandle(handle), count);
}
public static int ReleaseSemaphore(WaitableObject waitableObject, int count)
{
Debug.Assert(waitableObject != null);
Debug.Assert(count > 0);
s_lock.Acquire();
try
{
return waitableObject.SignalSemaphore(count);
}
finally
{
s_lock.Release();
}
}
public static void ReleaseMutex(IntPtr handle)
{
ReleaseMutex(HandleManager.FromHandle(handle));
}
public static void ReleaseMutex(WaitableObject waitableObject)
{
Debug.Assert(waitableObject != null);
s_lock.Acquire();
try
{
waitableObject.SignalMutex();
}
finally
{
s_lock.Release();
}
}
public static bool Wait(IntPtr handle, int timeoutMilliseconds, bool interruptible)
{
Debug.Assert(timeoutMilliseconds >= -1);
return Wait(HandleManager.FromHandle(handle), timeoutMilliseconds, interruptible);
}
public static bool Wait(
WaitableObject waitableObject,
int timeoutMilliseconds,
bool interruptible = true,
bool prioritize = false)
{
Debug.Assert(waitableObject != null);
Debug.Assert(timeoutMilliseconds >= -1);
return waitableObject.Wait(RuntimeThread.CurrentThread.WaitInfo, timeoutMilliseconds, interruptible, prioritize);
}
public static int Wait(
RuntimeThread currentThread,
SafeWaitHandle[] safeWaitHandles,
WaitHandle[] waitHandles,
int numWaitHandles,
bool waitForAll,
int timeoutMilliseconds)
{
Debug.Assert(currentThread == RuntimeThread.CurrentThread);
Debug.Assert(safeWaitHandles != null);
Debug.Assert(numWaitHandles > 0);
Debug.Assert(numWaitHandles <= safeWaitHandles.Length);
Debug.Assert(numWaitHandles <= waitHandles.Length);
Debug.Assert(numWaitHandles <= WaitHandle.MaxWaitHandles);
Debug.Assert(timeoutMilliseconds >= -1);
ThreadWaitInfo waitInfo = currentThread.WaitInfo;
WaitableObject[] waitableObjects = waitInfo.GetWaitedObjectArray(numWaitHandles);
bool success = false;
try
{
for (int i = 0; i < numWaitHandles; ++i)
{
Debug.Assert(safeWaitHandles[i] != null);
WaitableObject waitableObject = HandleManager.FromHandle(safeWaitHandles[i].DangerousGetHandle());
if (waitForAll)
{
/// Check if this is a duplicate, as wait-for-all does not support duplicates. Including the parent
/// loop, this becomes a brute force O(n^2) search, which is intended since the typical array length is
/// short enough that this would actually be faster than other alternatives. Also, the worst case is not
/// so bad considering that the array length is limited by <see cref="WaitHandle.MaxWaitHandles"/>.
for (int j = 0; j < i; ++j)
{
if (waitableObject == waitableObjects[j])
{
throw new DuplicateWaitObjectException("waitHandles[" + i + ']');
}
}
}
waitableObjects[i] = waitableObject;
}
success = true;
}
finally
{
if (!success)
{
for (int i = 0; i < numWaitHandles; ++i)
{
waitableObjects[i] = null;
}
}
}
if (numWaitHandles == 1)
{
WaitableObject waitableObject = waitableObjects[0];
waitableObjects[0] = null;
return
waitableObject.Wait(waitInfo, timeoutMilliseconds, interruptible: true, prioritize : false)
? 0
: WaitHandle.WaitTimeout;
}
return
WaitableObject.Wait(
waitableObjects,
numWaitHandles,
waitForAll,
waitInfo,
timeoutMilliseconds,
interruptible: true,
prioritize: false,
waitHandlesForAbandon: waitHandles);
}
public static int Wait(
RuntimeThread currentThread,
WaitableObject waitableObject0,
WaitableObject waitableObject1,
bool waitForAll,
int timeoutMilliseconds,
bool interruptible = true,
bool prioritize = false)
{
Debug.Assert(currentThread == RuntimeThread.CurrentThread);
Debug.Assert(waitableObject0 != null);
Debug.Assert(waitableObject1 != null);
Debug.Assert(waitableObject1 != waitableObject0);
Debug.Assert(timeoutMilliseconds >= -1);
ThreadWaitInfo waitInfo = currentThread.WaitInfo;
int count = 2;
WaitableObject[] waitableObjects = waitInfo.GetWaitedObjectArray(count);
waitableObjects[0] = waitableObject0;
waitableObjects[1] = waitableObject1;
return
WaitableObject.Wait(
waitableObjects,
count,
waitForAll,
waitInfo,
timeoutMilliseconds,
interruptible,
prioritize,
waitHandlesForAbandon: null);
}
public static bool SignalAndWait(
IntPtr handleToSignal,
IntPtr handleToWaitOn,
int timeoutMilliseconds)
{
Debug.Assert(timeoutMilliseconds >= -1);
return
SignalAndWait(
HandleManager.FromHandle(handleToSignal),
HandleManager.FromHandle(handleToWaitOn),
timeoutMilliseconds);
}
public static bool SignalAndWait(
WaitableObject waitableObjectToSignal,
WaitableObject waitableObjectToWaitOn,
int timeoutMilliseconds,
bool interruptible = true,
bool prioritize = false)
{
Debug.Assert(waitableObjectToSignal != null);
Debug.Assert(waitableObjectToWaitOn != null);
Debug.Assert(timeoutMilliseconds >= -1);
ThreadWaitInfo waitInfo = RuntimeThread.CurrentThread.WaitInfo;
bool waitCalled = false;
s_lock.Acquire();
try
{
// A pending interrupt does not signal the specified handle
if (interruptible && waitInfo.CheckAndResetPendingInterrupt)
{
throw new ThreadInterruptedException();
}
waitableObjectToSignal.Signal(1);
waitCalled = true;
return waitableObjectToWaitOn.Wait_Locked(waitInfo, timeoutMilliseconds, interruptible, prioritize);
}
finally
{
// Once the wait function is called, it will release the lock
if (waitCalled)
{
s_lock.VerifyIsNotLocked();
}
else
{
s_lock.Release();
}
}
}
public static void UninterruptibleSleep0()
{
ThreadWaitInfo.UninterruptibleSleep0();
}
public static void Sleep(int timeoutMilliseconds, bool interruptible = true)
{
ThreadWaitInfo.Sleep(timeoutMilliseconds, interruptible);
}
public static void Interrupt(RuntimeThread thread)
{
Debug.Assert(thread != null);
s_lock.Acquire();
try
{
thread.WaitInfo.TrySignalToInterruptWaitOrRecordPendingInterrupt();
}
finally
{
s_lock.Release();
}
}
public static void OnThreadExiting(RuntimeThread thread)
{
thread.WaitInfo.OnThreadExiting();
}
}
}
| |
//
// Sqlite.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Hyena;
namespace Hyena.Data.Sqlite
{
public class Connection : IDisposable
{
IntPtr ptr;
internal IntPtr Ptr { get { return ptr; } }
internal List<Statement> Statements = new List<Statement> ();
public string DbPath { get; private set; }
public long LastInsertRowId {
get { return Native.sqlite3_last_insert_rowid (Ptr); }
}
public Connection (string dbPath)
{
DbPath = dbPath;
CheckError (Native.sqlite3_open (Native.GetUtf8Bytes (dbPath), out ptr));
if (ptr == IntPtr.Zero)
throw new Exception ("Unable to open connection");
Native.sqlite3_extended_result_codes (ptr, 1);
AddFunction<BinaryFunction> ();
AddFunction<CollationKeyFunction> ();
AddFunction<SearchKeyFunction> ();
AddFunction<Md5Function> ();
}
public void Dispose ()
{
if (ptr != IntPtr.Zero) {
lock (Statements) {
var stmts = Statements.ToArray ();
if (stmts.Length > 0)
Hyena.Log.DebugFormat ("Connection disposing of {0} remaining statements", stmts.Length);
foreach (var stmt in stmts) {
stmt.Dispose ();
}
}
CheckError (Native.sqlite3_close (ptr));
ptr = IntPtr.Zero;
}
}
~Connection ()
{
Dispose ();
}
internal void CheckError (int errorCode)
{
CheckError (errorCode, "");
}
internal void CheckError (int errorCode, string sql)
{
if (errorCode == 0 || errorCode == 100 || errorCode == 101)
return;
string errmsg = Native.sqlite3_errmsg16 (Ptr).PtrToString ();
if (sql != null) {
errmsg = String.Format ("{0} (SQL: {1})", errmsg, sql);
}
throw new SqliteException (errorCode, errmsg);
}
public Statement CreateStatement (string sql)
{
return new Statement (this, sql);
}
public QueryReader Query (string sql)
{
return new Statement (this, sql) { ReaderDisposes = true }.Query ();
}
public T Query<T> (string sql)
{
using (var stmt = new Statement (this, sql)) {
return stmt.Query<T> ();
}
}
public void Execute (string sql)
{
// TODO
// * The application must insure that the 1st parameter to sqlite3_exec() is a valid and open database connection.
// * The application must not close database connection specified by the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
// * The application must not modify the SQL statement text passed into the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
CheckError (Native.sqlite3_exec (Ptr, Native.GetUtf8Bytes (sql), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero), sql);
}
// We need to keep a managed ref to the function objects we create so
// they won't get GC'd
List<SqliteFunction> functions = new List<SqliteFunction> ();
const int UTF16 = 4;
public void AddFunction<T> () where T : SqliteFunction
{
var type = typeof (T);
var pr = (SqliteFunctionAttribute)type.GetCustomAttributes (typeof (SqliteFunctionAttribute), false).First ();
var f = (SqliteFunction) Activator.CreateInstance (typeof (T));
f._InvokeFunc = (pr.FuncType == FunctionType.Scalar) ? new SqliteCallback(f.ScalarCallback) : null;
f._StepFunc = (pr.FuncType == FunctionType.Aggregate) ? new SqliteCallback(f.StepCallback) : null;
f._FinalFunc = (pr.FuncType == FunctionType.Aggregate) ? new SqliteFinalCallback(f.FinalCallback) : null;
f._CompareFunc = (pr.FuncType == FunctionType.Collation) ? new SqliteCollation(f.CompareCallback) : null;
if (pr.FuncType != FunctionType.Collation) {
CheckError (Native.sqlite3_create_function16 (
ptr, pr.Name, pr.Arguments, UTF16, IntPtr.Zero,
f._InvokeFunc, f._StepFunc, f._FinalFunc
));
} else {
CheckError (Native.sqlite3_create_collation16 (
ptr, pr.Name, UTF16, IntPtr.Zero, f._CompareFunc
));
}
functions.Add (f);
}
public void RemoveFunction<T> () where T : SqliteFunction
{
var type = typeof (T);
var pr = (SqliteFunctionAttribute)type.GetCustomAttributes (typeof (SqliteFunctionAttribute), false).First ();
if (pr.FuncType != FunctionType.Collation) {
CheckError (Native.sqlite3_create_function16 (
ptr, pr.Name, pr.Arguments, UTF16, IntPtr.Zero,
null, null, null
));
} else {
CheckError (Native.sqlite3_create_collation16 (
ptr, pr.Name, UTF16, IntPtr.Zero, null
));
}
var func = functions.FirstOrDefault (f => f is T);
if (func != null) {
functions.Remove (func);
}
}
}
public class SqliteException : Exception
{
public int ErrorCode { get; private set; }
public SqliteException (int errorCode, string message) : base (String.Format ("Sqlite error {0}: {1}", errorCode, message))
{
ErrorCode = errorCode;
}
}
public interface IDataReader : IDisposable
{
bool Read ();
object this[int i] { get; }
object this[string columnName] { get; }
T Get<T> (int i);
T Get<T> (string columnName);
object Get (int i, Type asType);
int FieldCount { get; }
string [] FieldNames { get; }
}
public class Statement : IDisposable, IEnumerable<IDataReader>
{
IntPtr ptr;
Connection connection;
bool bound;
QueryReader reader;
bool disposed;
internal bool Reading { get; set; }
internal IntPtr Ptr { get { return ptr; } }
internal bool Bound { get { return bound; } }
internal Connection Connection { get { return connection; } }
public bool IsDisposed { get { return disposed; } }
public string CommandText { get; private set; }
public int ParameterCount { get; private set; }
public bool ReaderDisposes { get; internal set; }
internal event EventHandler Disposed;
internal Statement (Connection connection, string sql)
{
CommandText = sql;
this.connection = connection;
IntPtr pzTail = IntPtr.Zero;
CheckError (Native.sqlite3_prepare16_v2 (connection.Ptr, sql, -1, out ptr, out pzTail));
lock (Connection.Statements) {
Connection.Statements.Add (this);
}
if (pzTail != IntPtr.Zero && Marshal.ReadByte (pzTail) != 0) {
Dispose ();
throw new ArgumentException ("sql", String.Format ("This sqlite binding does not support multiple commands in one statement:\n {0}", sql));
}
ParameterCount = Native.sqlite3_bind_parameter_count (ptr);
reader = new QueryReader () { Statement = this };
}
internal void CheckReading ()
{
CheckDisposed ();
if (!Reading) {
throw new InvalidOperationException ("Statement is not readable");
}
}
internal void CheckDisposed ()
{
if (disposed) {
throw new InvalidOperationException ("Statement is disposed");
}
}
public void Dispose ()
{
if (disposed)
return;
disposed = true;
if (ptr != IntPtr.Zero) {
// Don't check for error here, because if the most recent evaluation had an error finalize will return it too
// See http://sqlite.org/c3ref/finalize.html
Native.sqlite3_finalize (ptr);
ptr = IntPtr.Zero;
lock (Connection.Statements) {
Connection.Statements.Remove (this);
}
var h = Disposed;
if (h != null) {
h (this, EventArgs.Empty);
}
}
}
~Statement ()
{
Dispose ();
}
object [] null_val = new object [] { null };
public Statement Bind (params object [] vals)
{
Reset ();
if (vals == null && ParameterCount == 1)
vals = null_val;
if (vals == null || vals.Length != ParameterCount || ParameterCount == 0)
throw new ArgumentException ("vals", String.Format ("Statement has {0} parameters", ParameterCount));
for (int i = 1; i <= vals.Length; i++) {
int code = 0;
object o = SqliteUtils.ToDbFormat (vals[i - 1]);
if (o == null)
code = Native.sqlite3_bind_null (Ptr, i);
else if (o is double)
code = Native.sqlite3_bind_double (Ptr, i, (double)o);
else if (o is float)
code = Native.sqlite3_bind_double (Ptr, i, (double)(float)o);
else if (o is int)
code = Native.sqlite3_bind_int (Ptr, i, (int)o);
else if (o is uint)
code = Native.sqlite3_bind_int (Ptr, i, (int)(uint)o);
else if (o is long)
code = Native.sqlite3_bind_int64 (Ptr, i, (long)o);
else if (o is ulong)
code = Native.sqlite3_bind_int64 (Ptr, i, (long)(ulong)o);
else if (o is byte[]) {
byte [] bytes = o as byte[];
code = Native.sqlite3_bind_blob (Ptr, i, bytes, bytes.Length, (IntPtr)(-1));
} else {
// C# strings are UTF-16, so 2 bytes per char
// -1 for the last arg is the TRANSIENT destructor type so that sqlite will make its own copy of the string
string str = (o as string) ?? o.ToString ();
code = Native.sqlite3_bind_text16 (Ptr, i, str, str.Length * 2, (IntPtr)(-1));
}
CheckError (code);
}
bound = true;
return this;
}
internal void CheckError (int code)
{
connection.CheckError (code, CommandText);
}
private void Reset ()
{
CheckDisposed ();
if (Reading) {
throw new InvalidOperationException ("Can't reset statement while it's being read; make sure to Dispose any IDataReaders");
}
CheckError (Native.sqlite3_reset (ptr));
}
public IEnumerator<IDataReader> GetEnumerator ()
{
Reset ();
while (reader.Read ()) {
yield return reader;
}
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public Statement Execute ()
{
Reset ();
using (reader) {
reader.Read ();
}
return this;
}
public T Query<T> ()
{
Reset ();
using (reader) {
return reader.Read () ? reader.Get<T> (0) : (T) SqliteUtils.FromDbFormat <T> (null);
}
}
public QueryReader Query ()
{
Reset ();
return reader;
}
}
public class QueryReader : IDataReader
{
Dictionary<string, int> columns;
int column_count = -1;
internal Statement Statement { get; set; }
IntPtr Ptr { get { return Statement.Ptr; } }
public void Dispose ()
{
Statement.Reading = false;
if (Statement.ReaderDisposes) {
Statement.Dispose ();
}
}
public int FieldCount {
get {
if (column_count == -1) {
Statement.CheckDisposed ();
column_count = Native.sqlite3_column_count (Ptr);
}
return column_count;
}
}
string [] field_names;
public string [] FieldNames {
get {
if (field_names == null) {
field_names = Columns.Keys.OrderBy (f => Columns[f]).ToArray ();
}
return field_names;
}
}
public bool Read ()
{
Statement.CheckDisposed ();
if (Statement.ParameterCount > 0 && !Statement.Bound)
throw new InvalidOperationException ("Statement not bound");
int code = Native.sqlite3_step (Ptr);
if (code == ROW) {
Statement.Reading = true;
return true;
} else {
Statement.Reading = false;
Statement.CheckError (code);
return false;
}
}
public object this[int i] {
get {
Statement.CheckReading ();
int type = Native.sqlite3_column_type (Ptr, i);
switch (type) {
case SQLITE_INTEGER:
return Native.sqlite3_column_int64 (Ptr, i);
case SQLITE_FLOAT:
return Native.sqlite3_column_double (Ptr, i);
case SQLITE3_TEXT:
return Native.sqlite3_column_text16 (Ptr, i).PtrToString ();
case SQLITE_BLOB:
int num_bytes = Native.sqlite3_column_bytes (Ptr, i);
if (num_bytes == 0)
return null;
byte [] bytes = new byte[num_bytes];
Marshal.Copy (Native.sqlite3_column_blob (Ptr, i), bytes, 0, num_bytes);
return bytes;
case SQLITE_NULL:
return null;
default:
throw new Exception (String.Format ("Column is of unknown type {0}", type));
}
}
}
public object this[string columnName] {
get { return this[GetColumnIndex (columnName)]; }
}
public T Get<T> (int i)
{
return (T) Get (i, typeof(T));
}
public object Get (int i, Type asType)
{
return GetAs (this[i], asType);
}
internal static object GetAs (object o, Type type)
{
if (o != null && o.GetType () == type)
return o;
if (o == null)
o = null;
else if (type == typeof(int))
o = (int)(long)o;
else if (type == typeof(uint))
o = (uint)(long)o;
else if (type == typeof(ulong))
o = (ulong)(long)o;
else if (type == typeof(float))
o = (float)(double)o;
if (o != null && o.GetType () == type)
return o;
return SqliteUtils.FromDbFormat (type, o);
}
public T Get<T> (string columnName)
{
return Get<T> (GetColumnIndex (columnName));
}
private Dictionary<string, int> Columns {
get {
if (columns == null) {
columns = new Dictionary<string, int> ();
for (int i = 0; i < FieldCount; i++) {
columns[Native.sqlite3_column_name16 (Ptr, i).PtrToString ()] = i;
}
}
return columns;
}
}
private int GetColumnIndex (string columnName)
{
Statement.CheckReading ();
int col = 0;
if (!Columns.TryGetValue (columnName, out col))
throw new ArgumentException ("columnName");
return col;
}
const int SQLITE_INTEGER = 1;
const int SQLITE_FLOAT = 2;
const int SQLITE3_TEXT = 3;
const int SQLITE_BLOB = 4;
const int SQLITE_NULL = 5;
const int ROW = 100;
const int DONE = 101;
}
internal static class Native
{
const string SQLITE_DLL = "e_sqlite3";
// Connection functions
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_open(byte [] utf8DbPath, out IntPtr db);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_close(IntPtr db);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern long sqlite3_last_insert_rowid (IntPtr db);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_busy_timeout(IntPtr db, int ms);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_errmsg16(IntPtr db);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_create_function16(IntPtr db, string strName, int nArgs, int eTextRep, IntPtr app, SqliteCallback func, SqliteCallback funcstep, SqliteFinalCallback funcfinal);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_aggregate_count(IntPtr context);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_aggregate_context(IntPtr context, int nBytes);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_create_collation16(IntPtr db, string strName, int eTextRep, IntPtr ctx, SqliteCollation fcompare);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_extended_result_codes (IntPtr db, int onoff);
// Statement functions
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_prepare16_v2(IntPtr db, string pSql, int nBytes, out IntPtr stmt, out IntPtr ptrRemain);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_step(IntPtr stmt);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_column_count(IntPtr stmt);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_column_name16(IntPtr stmt, int index);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_column_type(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_column_blob(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_column_bytes(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern double sqlite3_column_double(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern long sqlite3_column_int64(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_column_text16(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_finalize(IntPtr stmt);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_reset(IntPtr stmt);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_exec(IntPtr db, byte [] sql, IntPtr callback, IntPtr cbArg, IntPtr errPtr);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_parameter_index(IntPtr stmt, byte [] paramName);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_parameter_count(IntPtr stmt);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_blob(IntPtr stmt, int param, byte[] val, int nBytes, IntPtr destructorType);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_double(IntPtr stmt, int param, double val);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_int(IntPtr stmt, int param, int val);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_int64(IntPtr stmt, int param, long val);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_null(IntPtr stmt, int param);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_text16 (IntPtr stmt, int param, string val, int numBytes, IntPtr destructorType);
//DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
//internal static extern int sqlite3_bind_zeroblob(IntPtr stmt, int, int n);
// Context functions
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_blob(IntPtr context, byte[] value, int nSize, IntPtr pvReserved);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_double(IntPtr context, double value);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_error(IntPtr context, byte[] strErr, int nLen);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_int(IntPtr context, int value);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_int64(IntPtr context, Int64 value);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_null(IntPtr context);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_text(IntPtr context, byte[] value, int nLen, IntPtr pvReserved);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_error16(IntPtr context, string strName, int nLen);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_text16(IntPtr context, string strName, int nLen, IntPtr pvReserved);
// Value methods
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_value_blob(IntPtr p);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_value_bytes(IntPtr p);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern double sqlite3_value_double(IntPtr p);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_value_int(IntPtr p);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern Int64 sqlite3_value_int64(IntPtr p);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_value_type(IntPtr p);
[DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_value_text16(IntPtr p);
internal static string PtrToString (this IntPtr ptr)
{
return System.Runtime.InteropServices.Marshal.PtrToStringUni (ptr);
}
internal static byte [] GetUtf8Bytes (string str)
{
return Encoding.UTF8.GetBytes (str + '\0');
}
}
}
| |
namespace Office.Excel
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
public class ExcelWorksheet
{
private readonly WorksheetPart worksheetPart;
private readonly Dictionary<uint, Dictionary<uint, Cell>> cells = new Dictionary<uint, Dictionary<uint, Cell>>();
public ExcelWorkbook Workbook { get; private set; }
public string Name { get; private set; }
public WorksheetPart WorksheetPart
{
get { return this.worksheetPart; }
}
public ExcelWorksheet(ExcelWorkbook workbook, string name, WorksheetPart part)
{
this.Workbook = workbook;
this.Name = name;
this.worksheetPart = part;
this.BuildCellIndex();
}
public Cell GetCell(ExcelAddress.Cell address)
{
Dictionary<uint, Cell> rows;
if (this.cells.TryGetValue(address.ColumnIndex, out rows))
{
Cell cell;
if (rows.TryGetValue(address.RowIndex, out cell))
{
return cell;
}
}
throw new KeyNotFoundException(String.Format("No cell exists at {0}", address.CellReferenceString));
}
public ExcelWorksheet Clone(string newName)
{
return this.Workbook.CopySheet(this.Name, newName);
}
public void WriteValue(ExcelAddress.Cell address, object value)
{
var cell = this.GetCell(address);
if (value == null)
{
cell.CellValue = new CellValue(null);
return;
}
var typ = value.GetType();
if (typ == typeof(string))
{
var v = (string)value;
var index = this.Workbook.InsertSharedStringItem(v);
cell.CellValue = new CellValue(index.ToString(CultureInfo.InvariantCulture));
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
return;
}
if (typ == typeof(DateTime))
{
var dt = (DateTime)value;
string dtValue = dt.ToOADate().ToString(CultureInfo.InvariantCulture);
cell.CellValue = new CellValue(dtValue);
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
return;
}
if (ExcelWorkbook.NumericTypes.Contains(typ))
{
cell.CellValue = new CellValue(value.ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
return;
}
throw new InvalidOperationException(string.Format("the type {0} is not currently supported if it is an array values should be boxed to type object[][]", typ.FullName));
}
public void WriteArray(Addressable<DefinedName, ExcelAddress.NamedRange> address, string[] value)
{
var startCell = address.Address;
var currentCell = startCell;
var sheet = this;
foreach (var x in value)
{
sheet.WriteValue(currentCell.StartCell, x);
currentCell = (ExcelAddress.NamedRange)currentCell.MoveLeft();
}
}
public void WriteArray2D(Addressable<DefinedName, ExcelAddress.NamedRange> address, string[][] value)
{
var startCell = address.Address;
var currentCell = startCell;
var sheet = this;
foreach (var ys in value)
{
foreach (var x in ys)
{
sheet.WriteValue(currentCell.StartCell, x);
currentCell = (ExcelAddress.NamedRange)currentCell.MoveLeft();
}
currentCell = (ExcelAddress.NamedRange)currentCell.MoveDown();
}
}
public void WritePagedArray(Addressable<DefinedName, ExcelAddress.NamedRange> address, ExcelPagedArray value)
{
var startCell = address.Address;
var startRowIndex = startCell.RowIndex;
var currentCell = startCell;
var sheet = this;
sheet.CopyRow(startRowIndex, value.PageSize);
var rowsWrittenToThisSheet = 0;
var sheetNumber = 0;
for (var i = 0; i < value.Length; i++)
{
foreach (var x in value[i])
{
sheet.WriteValue(currentCell.StartCell, x);
currentCell = (ExcelAddress.NamedRange)currentCell.MoveLeft();
}
rowsWrittenToThisSheet++;
if (rowsWrittenToThisSheet < value.PageSize)
{
startCell = (ExcelAddress.NamedRange)startCell.MoveDown();
currentCell = startCell;
}
else
{
if ((i + 1) < value.Length)
{
sheetNumber++;
sheet = sheet.Clone(sheet.Name + "_" + sheetNumber);
sheet.CopyRow(address.Address.RowIndex, (int)Math.Min(value.PageSize, value.Length - i - 1));
startCell = address.Address;
currentCell = startCell;
rowsWrittenToThisSheet = 0;
}
}
}
}
public void CopyRow(uint rowIndex, int copies)
{
for (var r = 1; r < copies; r++)
{
this.InsertCopyOfRow(rowIndex, (uint)(rowIndex + r), false);
}
this.BuildCellIndex();
}
public void InsertRow(uint rowIndex, Row insertRow, bool rebuildIndex)
{
this.InsertRowInternal(rowIndex, insertRow, false, rebuildIndex);
}
public void AppendRow(uint rowIndex, Row insertRow, bool rebuildIndex)
{
this.InsertRowInternal(rowIndex, insertRow, true, rebuildIndex);
}
public void InsertCopyOfRow(uint rowIndex, uint targetRowIndex, bool rebuildIndex)
{
var sheetData = this.WorksheetPart.Worksheet.GetFirstChild<SheetData>();
var rows = sheetData.Elements<Row>();
var lastRow = rows.Last().RowIndex;
var currRow = rows.FirstOrDefault(r => r.RowIndex == rowIndex);
if (currRow != null)
{
var newRow = (Row)currRow.CloneNode(true);
if (targetRowIndex >= lastRow)
{
this.AppendRow(targetRowIndex, newRow, rebuildIndex);
}
else
{
this.InsertRow(targetRowIndex, newRow, rebuildIndex);
}
var mergeCells = this.WorksheetPart.Worksheet.Elements<MergeCells>().FirstOrDefault();
if (mergeCells != null)
{
var rowMergedCells = mergeCells.Elements<MergeCell>()
.Select(r => Addressable<MergeCell, ExcelAddress.CellRange>.Lift(r))
.Where(r => r.Address.Match(c => c.RowIndex == rowIndex, c => c.StartCell.RowIndex == rowIndex && c.EndCell.RowIndex == rowIndex))
.Select(r =>
{
var cell = (MergeCell)r.Item.CloneNode(true);
cell.Reference = r.Address.MoveToRow(targetRowIndex).ReferenceString;
return cell;
});
mergeCells.Append(rowMergedCells.Cast<OpenXmlElement>());
}
}
}
public void BuildCellIndex()
{
this.cells.Clear();
foreach (var cell in this.WorksheetPart.Worksheet.Descendants<Cell>())
{
this.EnsureCellIsInLookup(cell);
}
}
private void EnsureCellIsInLookup(Cell cell)
{
var address = ExcelAddress.ParseCellAddress(cell.CellReference);
if (!this.cells.ContainsKey(address.ColumnIndex))
{
this.cells[address.ColumnIndex] = new Dictionary<uint, Cell>();
}
if (!this.cells[address.ColumnIndex].ContainsKey(address.RowIndex))
{
this.cells[address.ColumnIndex][address.RowIndex] = cell;
}
}
private Row InsertRowInternal(uint rowIndex, Row insertRow, bool isNewLastRow, bool rebuildIndex)
{
Worksheet worksheet = this.WorksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
Row retRow = !isNewLastRow ? sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex) : null;
// If the worksheet does not contain a row with the specified row index, insert one.
if (retRow != null)
{
// if retRow is not null and we are inserting a new row, then move all existing rows down.
if (insertRow != null)
{
this.UpdateRowIndexes(rowIndex, false);
this.UpdateMergedCellReferences(rowIndex, false);
this.UpdateHyperlinkReferences(rowIndex, false);
// actually insert the new row into the sheet
retRow = sheetData.InsertBefore(insertRow, retRow); // at this point, retRow still points to the row that had the insert rowIndex
string curIndex = retRow.RowIndex.ToString();
string newIndex = rowIndex.ToString();
foreach (Cell cell in retRow.Elements<Cell>())
{
// Update the references for the rows cells.
cell.CellReference = new StringValue(cell.CellReference.Value.Replace(curIndex, newIndex));
}
// Update the row index.
retRow.RowIndex = rowIndex;
}
}
else
{
// Row doesn't exist yet, shifting not needed.
// Rows must be in sequential order according to RowIndex. Determine where to insert the new row.
Row refRow = !isNewLastRow ? sheetData.Elements<Row>().FirstOrDefault(row => row.RowIndex > rowIndex) : null;
// use the insert row if it exists
retRow = insertRow ?? new Row() { RowIndex = rowIndex };
IEnumerable<Cell> cellsInRow = retRow.Elements<Cell>();
if (cellsInRow.Any())
{
string curIndex = retRow.RowIndex.ToString();
string newIndex = rowIndex.ToString();
foreach (Cell cell in cellsInRow)
{
// Update the references for the rows cells.
cell.CellReference = new StringValue(cell.CellReference.Value.Replace(curIndex, newIndex));
}
// Update the row index.
retRow.RowIndex = rowIndex;
}
sheetData.InsertBefore(retRow, refRow);
}
if (rebuildIndex)
{
this.BuildCellIndex();
}
return retRow;
}
private void UpdateRowIndexes(uint rowIndex, bool isDeletedRow)
{
// Get all the rows in the worksheet with equal or higher row index values than the one being inserted/deleted for reindexing.
IEnumerable<Row> rows = this.WorksheetPart.Worksheet.Descendants<Row>().Where(r => r.RowIndex.Value >= rowIndex);
foreach (Row row in rows)
{
uint newIndex = (isDeletedRow ? row.RowIndex - 1 : row.RowIndex + 1);
string curRowIndex = row.RowIndex.ToString();
string newRowIndex = newIndex.ToString();
foreach (Cell cell in row.Elements<Cell>())
{
// Update the references for the rows cells.
cell.CellReference = new StringValue(cell.CellReference.Value.Replace(curRowIndex, newRowIndex));
}
// Update the row index.
row.RowIndex = newIndex;
}
}
private void UpdateMergedCellReferences(uint rowIndex, bool isDeletedRow)
{
if (this.WorksheetPart.Worksheet.Elements<MergeCells>().Any())
{
MergeCells mergeCells = this.WorksheetPart.Worksheet.Elements<MergeCells>().FirstOrDefault();
if (mergeCells != null)
{
var mergeCellsList =
mergeCells.Elements<MergeCell>()
.Select(r => Addressable<MergeCell, ExcelAddress.CellRange>.Lift(r))
.Where(r => r.Address.Match(c => c.RowIndex >= rowIndex,
c => c.StartCell.RowIndex >= rowIndex || c.EndCell.RowIndex >= rowIndex)
);
if (isDeletedRow)
{
var mergeCellsToDelete =
mergeCellsList.Where(r =>
r.Address.Match(c => c.RowIndex == rowIndex,
c => c.StartCell.RowIndex == rowIndex || c.EndCell.RowIndex == rowIndex));
foreach (var cellToDelete in mergeCellsToDelete)
{
cellToDelete.Item.Remove();
}
// Update the list to contain all merged cells greater than the deleted row index
mergeCellsList =
mergeCells
.Elements<MergeCell>()
.Select(r => Addressable<MergeCell, ExcelAddress.CellRange>.Lift(r))
.Where(r =>
r.Address.Match(c => c.RowIndex > rowIndex,
c => c.StartCell.RowIndex > rowIndex || c.EndCell.RowIndex > rowIndex))
.ToList();
}
// Either increment or decrement the row index on the merged cell reference
foreach (var mergeCell in mergeCellsList.ToArray())
{
var addr = isDeletedRow ? mergeCell.Address.MoveUp() : mergeCell.Address.MoveDown();
mergeCell.Item.Reference = addr.ReferenceString;
}
}
}
}
/// <summary>
/// Updates all hyperlinks in the worksheet when a row is inserted or deleted.
/// </summary>
/// <param name="worksheetPart">Worksheet Part</param>
/// <param name="rowIndex">Row Index being inserted or deleted</param>
/// <param name="isDeletedRow">True if row was deleted, otherwise false</param>
private void UpdateHyperlinkReferences(uint rowIndex, bool isDeletedRow)
{
Hyperlinks hyperlinks = this.WorksheetPart.Worksheet.Elements<Hyperlinks>().FirstOrDefault();
if (hyperlinks != null)
{
Match hyperlinkRowIndexMatch;
uint hyperlinkRowIndex;
foreach (Hyperlink hyperlink in hyperlinks.Elements<Hyperlink>())
{
hyperlinkRowIndexMatch = Regex.Match(hyperlink.Reference.Value, "[0-9]+");
if (hyperlinkRowIndexMatch.Success && UInt32.TryParse(hyperlinkRowIndexMatch.Value, out hyperlinkRowIndex) && hyperlinkRowIndex >= rowIndex)
{
// if being deleted, hyperlink needs to be removed or moved up
if (isDeletedRow)
{
// if hyperlink is on the row being removed, remove it
if (hyperlinkRowIndex == rowIndex)
{
hyperlink.Remove();
}
// else hyperlink needs to be moved up a row
else
{
hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex - 1).ToString());
}
}
// else row is being inserted, move hyperlink down
else
{
hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex + 1).ToString());
}
}
}
// Remove the hyperlinks collection if none remain
if (hyperlinks.Elements<Hyperlink>().Count() == 0)
{
hyperlinks.Remove();
}
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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 Jaroslaw Kowalski 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.Threading;
#if !SILVERLIGHT
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using Xunit;
public class MailTargetTests : NLogTestBase
{
[Fact]
public void SimpleEmailTest()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
CC = "me@myserver.com;you@yourserver.com",
Bcc = "foo@myserver.com;bar@yourserver.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
Assert.Equal("server1", mock.Host);
Assert.Equal(27, mock.Port);
Assert.False(mock.EnableSsl);
Assert.Null(mock.Credentials);
var msg = mock.MessagesSent[0];
Assert.Equal("Hello from NLog", msg.Subject);
Assert.Equal("foo@bar.com", msg.From.Address);
Assert.Equal(1, msg.To.Count);
Assert.Equal("bar@foo.com", msg.To[0].Address);
Assert.Equal(2, msg.CC.Count);
Assert.Equal("me@myserver.com", msg.CC[0].Address);
Assert.Equal("you@yourserver.com", msg.CC[1].Address);
Assert.Equal(2, msg.Bcc.Count);
Assert.Equal("foo@myserver.com", msg.Bcc[0].Address);
Assert.Equal("bar@yourserver.com", msg.Bcc[1].Address);
Assert.Equal(msg.Body, "Info MyLogger log message 1");
}
[Fact]
public void MailTarget_WithNewlineInSubject_SendsMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
CC = "me@myserver.com;you@yourserver.com",
Bcc = "foo@myserver.com;bar@yourserver.com",
Subject = "Hello from NLog\n",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
var msg = mock.MessagesSent[0];
}
[Fact]
public void NtlmEmailTest()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
SmtpAuthentication = SmtpAuthenticationMode.Ntlm,
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(CredentialCache.DefaultNetworkCredentials, mock.Credentials);
}
[Fact]
public void BasicAuthEmailTest()
{
try
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
SmtpAuthentication = SmtpAuthenticationMode.Basic,
SmtpUserName = "${mdc:username}",
SmtpPassword = "${mdc:password}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
MappedDiagnosticsContext.Set("username", "u1");
MappedDiagnosticsContext.Set("password", "p1");
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
var credential = mock.Credentials as NetworkCredential;
Assert.NotNull(credential);
Assert.Equal("u1", credential.UserName);
Assert.Equal("p1", credential.Password);
Assert.Equal(string.Empty, credential.Domain);
}
finally
{
MappedDiagnosticsContext.Clear();
}
}
[Fact]
public void CsvLayoutTest()
{
var layout = new CsvLayout()
{
Delimiter = CsvColumnDelimiterMode.Semicolon,
WithHeader = true,
Columns =
{
new CsvColumn("name", "${logger}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message", "${message}"),
}
};
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
AddNewLines = true,
Layout = layout,
};
layout.Initialize(null);
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
var msg = mock.MessagesSent[0];
string expectedBody = "name;level;message\nMyLogger1;Info;log message 1\nMyLogger2;Debug;log message 2\nMyLogger3;Error;log message 3\n";
Assert.Equal(expectedBody, msg.Body);
}
[Fact]
public void PerMessageServer()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "${logger}.mydomain.com",
Body = "${message}",
AddNewLines = true,
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
// 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com
Assert.Equal(2, mmt.CreatedMocks.Count);
var mock1 = mmt.CreatedMocks[0];
Assert.Equal("MyLogger1.mydomain.com", mock1.Host);
Assert.Equal(1, mock1.MessagesSent.Count);
var msg1 = mock1.MessagesSent[0];
Assert.Equal("log message 1\nlog message 3\n", msg1.Body);
var mock2 = mmt.CreatedMocks[1];
Assert.Equal("MyLogger2.mydomain.com", mock2.Host);
Assert.Equal(1, mock2.MessagesSent.Count);
var msg2 = mock2.MessagesSent[0];
Assert.Equal("log message 2\n", msg2.Body);
}
[Fact]
public void ErrorHandlingTest()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "${logger}",
Body = "${message}",
AddNewLines = true,
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
var exceptions2 = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "ERROR", "log message 2").WithContinuation(exceptions2.Add),
new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Null(exceptions[1]);
Assert.NotNull(exceptions2[0]);
Assert.Equal("Some SMTP error.", exceptions2[0].Message);
// 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com
Assert.Equal(2, mmt.CreatedMocks.Count);
var mock1 = mmt.CreatedMocks[0];
Assert.Equal("MyLogger1", mock1.Host);
Assert.Equal(1, mock1.MessagesSent.Count);
var msg1 = mock1.MessagesSent[0];
Assert.Equal("log message 1\nlog message 3\n", msg1.Body);
var mock2 = mmt.CreatedMocks[1];
Assert.Equal("ERROR", mock2.Host);
Assert.Equal(1, mock2.MessagesSent.Count);
var msg2 = mock2.MessagesSent[0];
Assert.Equal("log message 2\n", msg2.Body);
}
/// <summary>
/// Tests that it is possible to user different email address for each log message,
/// for example by using ${logger}, ${event-context} or any other layout renderer.
/// </summary>
[Fact]
public void PerMessageAddress()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "${logger}@foo.com",
Body = "${message}",
SmtpServer = "server1.mydomain.com",
AddNewLines = true,
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
// 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com
Assert.Equal(2, mmt.CreatedMocks.Count);
var mock1 = mmt.CreatedMocks[0];
Assert.Equal(1, mock1.MessagesSent.Count);
var msg1 = mock1.MessagesSent[0];
Assert.Equal("MyLogger1@foo.com", msg1.To[0].Address);
Assert.Equal("log message 1\nlog message 3\n", msg1.Body);
var mock2 = mmt.CreatedMocks[1];
Assert.Equal(1, mock2.MessagesSent.Count);
var msg2 = mock2.MessagesSent[0];
Assert.Equal("MyLogger2@foo.com", msg2.To[0].Address);
Assert.Equal("log message 2\n", msg2.Body);
}
[Fact]
public void CustomHeaderAndFooter()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
AddNewLines = true,
Layout = "${message}",
Header = "First event: ${logger}",
Footer = "Last event: ${logger}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
var msg = mock.MessagesSent[0];
string expectedBody = "First event: MyLogger1\nlog message 1\nlog message 2\nlog message 3\nLast event: MyLogger3\n";
Assert.Equal(expectedBody, msg.Body);
}
[Fact]
public void DefaultSmtpClientTest()
{
var mailTarget = new MailTarget();
var client = mailTarget.CreateSmtpClient();
Assert.IsType(typeof(MySmtpClient), client);
}
[Fact]
public void ReplaceNewlinesWithBreakInHtmlMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Body = "${level}${newline}${logger}${newline}${message}",
Html = true,
ReplaceNewlineWithBrTagInHtml = true
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.True(messageSent.IsBodyHtml);
var lines = messageSent.Body.Split(new[] { "<br/>" }, StringSplitOptions.RemoveEmptyEntries);
Assert.True(lines.Length == 3);
}
[Fact]
public void NoReplaceNewlinesWithBreakInHtmlMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Body = "${level}${newline}${logger}${newline}${message}",
Html = true,
ReplaceNewlineWithBrTagInHtml = false
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.True(messageSent.IsBodyHtml);
var lines = messageSent.Body.Split(new[] {Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Assert.True(lines.Length == 3);
}
[Fact]
public void MailTarget_WithPriority_SendsMailWithPrioritySet()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Priority = "high"
};
mmt.Initialize(null);
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { }));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.Equal(MailPriority.High, messageSent.Priority);
}
[Fact]
public void MailTarget_WithoutPriority_SendsMailWithNormalPriority()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
};
mmt.Initialize(null);
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { }));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.Equal(MailPriority.Normal, messageSent.Priority);
}
[Fact]
public void MailTarget_WithInvalidPriority_SendsMailWithNormalPriority()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Priority = "invalidPriority"
};
mmt.Initialize(null);
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { }));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.Equal(MailPriority.Normal, messageSent.Priority);
}
[Fact]
public void MailTarget_WithValidToAndEmptyCC_SendsMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
CC = "",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
Assert.Equal(1, mmt.CreatedMocks[0].MessagesSent.Count);
}
[Fact]
public void MailTarget_WithValidToAndEmptyBcc_SendsMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Bcc = "",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
Assert.Equal(1, mmt.CreatedMocks[0].MessagesSent.Count);
}
[Fact]
public void MailTarget_WithEmptyTo_ThrowsNLogRuntimeException()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.NotNull(exceptions[0]);
Assert.IsType<NLogRuntimeException>(exceptions[0]);
}
[Fact]
public void MailTarget_WithEmptyFrom_ThrowsNLogRuntimeException()
{
var mmt = new MockMailTarget
{
From = "",
To = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.NotNull(exceptions[0]);
Assert.IsType<NLogRuntimeException>(exceptions[0]);
}
[Fact]
public void MailTarget_WithEmptySmtpServer_ThrowsNLogRuntimeException()
{
var mmt = new MockMailTarget
{
From = "bar@bar.com",
To = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.NotNull(exceptions[0]);
Assert.IsType<NLogRuntimeException>(exceptions[0]);
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedTo_ThrowsConfigException()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null));
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedFrom_ThrowsConfigException()
{
var mmt = new MockMailTarget
{
To = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null));
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedSmtpServer_should_not_ThrowsConfigException()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true
};
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedSmtpServer_ThrowsConfigException_if_UseSystemNetMailSettings()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = false
};
Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null));
}
/// <summary>
/// Test for https://github.com/NLog/NLog/issues/690
/// </summary>
[Fact]
public void MailTarget_UseSystemNetMailSettings_False_Override_ThrowsNLogRuntimeException_if_DeliveryMethodNotSpecified()
{
var inConfigVal = @"C:\config";
var mmt = new MockMailTarget(inConfigVal)
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
PickupDirectoryLocation = @"C:\TEMP",
UseSystemNetMailSettings = false
};
Assert.Throws<NLogRuntimeException>(() => mmt.ConfigureMailClient());
}
/// <summary>
/// Test for https://github.com/NLog/NLog/issues/690
/// </summary>
[Fact]
public void MailTarget_UseSystemNetMailSettings_False_Override_DeliveryMethod_SpecifiedDeliveryMethod()
{
var inConfigVal = @"C:\config";
var mmt = new MockMailTarget(inConfigVal)
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
PickupDirectoryLocation = @"C:\TEMP",
UseSystemNetMailSettings = false,
DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory
};
mmt.ConfigureMailClient();
Assert.NotEqual(mmt.PickupDirectoryLocation, inConfigVal);
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_True()
{
var inConfigVal = @"C:\config";
var mmt = new MockMailTarget(inConfigVal)
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true
};
mmt.ConfigureMailClient();
Assert.Equal(mmt.SmtpClientPickUpDirectory, inConfigVal);
}
[Fact]
public void MailTarget_WithoutSubject_SendsMessageWithDefaultSubject()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@bar.com",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
Assert.Equal(string.Format("Message from NLog on {0}", Environment.MachineName), mock.MessagesSent[0].Subject);
}
public class MockSmtpClient : ISmtpClient
{
public MockSmtpClient()
{
this.MessagesSent = new List<MailMessage>();
}
public SmtpDeliveryMethod DeliveryMethod { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public int Timeout { get; set; }
public string PickupDirectoryLocation { get; set; }
public ICredentialsByHost Credentials { get; set; }
public bool EnableSsl { get; set; }
public List<MailMessage> MessagesSent { get; private set; }
public new void Send(MailMessage msg)
{
if (string.IsNullOrEmpty(this.Host) && string.IsNullOrEmpty(this.PickupDirectoryLocation))
{
throw new InvalidOperationException("[Host/Pickup directory] is null or empty.");
}
this.MessagesSent.Add(msg);
if (Host == "ERROR")
{
throw new InvalidOperationException("Some SMTP error.");
}
}
public new void Dispose()
{
}
}
public class MockMailTarget : MailTarget
{
private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent.";
public MockSmtpClient Client;
public MockMailTarget()
{
Client = new MockSmtpClient();
}
public MockMailTarget(string configPickUpdirectory)
{
Client = new MockSmtpClient
{
PickupDirectoryLocation = configPickUpdirectory
};
}
public List<MockSmtpClient> CreatedMocks = new List<MockSmtpClient>();
internal override ISmtpClient CreateSmtpClient()
{
var client = new MockSmtpClient();
CreatedMocks.Add(client);
return client;
}
public void ConfigureMailClient()
{
if (UseSystemNetMailSettings) return;
if (this.SmtpServer == null && string.IsNullOrEmpty(this.PickupDirectoryLocation))
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer/PickupDirectoryLocation"));
}
if (this.DeliveryMethod == SmtpDeliveryMethod.Network && this.SmtpServer == null)
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer"));
}
if (this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(this.PickupDirectoryLocation))
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "PickupDirectoryLocation"));
}
if (!string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
{
Client.PickupDirectoryLocation = this.PickupDirectoryLocation;
}
Client.DeliveryMethod = this.DeliveryMethod;
}
public string SmtpClientPickUpDirectory { get { return Client.PickupDirectoryLocation; } }
}
}
}
#endif
| |
// Copyright (c) 2012, Event Store LLP
// 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 Event Store LLP 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
// HOLDER 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.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using EventStore.Core.Data;
using EventStore.Core.Messages;
using EventStore.Core.Services.Transport.Tcp;
using EventStore.Transport.Tcp;
namespace EventStore.TestClient.Commands
{
internal class WriteFloodProcessor : ICmdProcessor
{
public string Usage { get { return "WRFL [<clients> <requests> [<streams-cnt> [<size>]]]"; } }
public string Keyword { get { return "WRFL"; } }
public bool Execute(CommandProcessorContext context, string[] args)
{
int clientsCnt = 1;
long requestsCnt = 5000;
int streamsCnt = 1000;
int size = 256;
if (args.Length > 0)
{
if (args.Length < 2 || args.Length > 4)
return false;
try
{
clientsCnt = int.Parse(args[0]);
requestsCnt = long.Parse(args[1]);
if (args.Length >= 3)
streamsCnt = int.Parse(args[2]);
if (args.Length >= 4)
size = int.Parse(args[3]);
}
catch
{
return false;
}
}
WriteFlood(context, clientsCnt, requestsCnt, streamsCnt, size);
return true;
}
private void WriteFlood(CommandProcessorContext context, int clientsCnt, long requestsCnt, int streamsCnt, int size)
{
context.IsAsync();
var doneEvent = new ManualResetEventSlim(false);
var clients = new List<TcpTypedConnection<byte[]>>();
var threads = new List<Thread>();
long succ = 0;
long fail = 0;
long prepTimeout = 0;
long commitTimeout = 0;
long forwardTimeout = 0;
long wrongExpVersion = 0;
long streamDeleted = 0;
long all = 0;
var streams = Enumerable.Range(0, streamsCnt).Select(x => Guid.NewGuid().ToString()).ToArray();
//var streams = Enumerable.Range(0, streamsCnt).Select(x => string.Format("stream-{0}", x)).ToArray();
var sw2 = new Stopwatch();
for (int i = 0; i < clientsCnt; i++)
{
var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
long sent = 0;
long received = 0;
var rnd = new Random();
var client = context.Client.CreateTcpConnection(
context,
(conn, pkg) =>
{
if (pkg.Command != TcpCommand.WriteEventsCompleted)
{
context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
return;
}
var dto = pkg.Data.Deserialize<TcpClientMessageDto.WriteEventsCompleted>();
switch(dto.Result)
{
case TcpClientMessageDto.OperationResult.Success:
if (Interlocked.Increment(ref succ) % 1000 == 0) Console.Write('.');
break;
case TcpClientMessageDto.OperationResult.PrepareTimeout:
Interlocked.Increment(ref prepTimeout);
break;
case TcpClientMessageDto.OperationResult.CommitTimeout:
Interlocked.Increment(ref commitTimeout);
break;
case TcpClientMessageDto.OperationResult.ForwardTimeout:
Interlocked.Increment(ref forwardTimeout);
break;
case TcpClientMessageDto.OperationResult.WrongExpectedVersion:
Interlocked.Increment(ref wrongExpVersion);
break;
case TcpClientMessageDto.OperationResult.StreamDeleted:
Interlocked.Increment(ref streamDeleted);
break;
default:
throw new ArgumentOutOfRangeException();
}
if (dto.Result != TcpClientMessageDto.OperationResult.Success)
if (Interlocked.Increment(ref fail)%1000 == 0)
Console.Write('#');
Interlocked.Increment(ref received);
var localAll = Interlocked.Increment(ref all);
if (localAll % 100000 == 0)
{
var elapsed = sw2.Elapsed;
sw2.Restart();
context.Log.Trace("\nDONE TOTAL {0} WRITES IN {1} ({2:0.0}/s) [S:{3}, F:{4} (WEV:{5}, P:{6}, C:{7}, F:{8}, D:{9})].",
localAll, elapsed, 1000.0*100000/elapsed.TotalMilliseconds,
succ, fail,
wrongExpVersion, prepTimeout, commitTimeout, forwardTimeout, streamDeleted);
}
if (localAll == requestsCnt)
{
context.Success();
doneEvent.Set();
}
},
connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
clients.Add(client);
threads.Add(new Thread(() =>
{
for (int j = 0; j < count; ++j)
{
var write = new TcpClientMessageDto.WriteEvents(
streams[rnd.Next(streamsCnt)],
ExpectedVersion.Any,
new[]
{
new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray(),
"TakeSomeSpaceEvent",
1,0,
Common.Utils.Helper.UTF8NoBom.GetBytes("{ \"DATA\" : \"" + new string('*', size) + "\"}"),
Common.Utils.Helper.UTF8NoBom.GetBytes("{ \"METADATA\" : \"" + new string('$', 100) + "\"}"))
},
false);
var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), write.Serialize());
client.EnqueueSend(package.AsByteArray());
var localSent = Interlocked.Increment(ref sent);
while (localSent - Interlocked.Read(ref received) > context.Client.Options.WriteWindow/clientsCnt)
{
Thread.Sleep(1);
}
}
}) { IsBackground = true });
}
var sw = Stopwatch.StartNew();
sw2.Start();
threads.ForEach(thread => thread.Start());
doneEvent.Wait();
sw.Stop();
clients.ForEach(client => client.Close());
context.Log.Info("Completed. Successes: {0}, failures: {1} (WRONG VERSION: {2}, P: {3}, C: {4}, F: {5}, D: {6})",
succ, fail,
wrongExpVersion, prepTimeout, commitTimeout, forwardTimeout, streamDeleted);
var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;
context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);
PerfUtils.LogData(
Keyword,
PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
PerfUtils.Col("requestsCnt", requestsCnt),
PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));
var failuresRate = (int) (100 * fail / (fail + succ));
PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), failuresRate);
PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-reqPerSec", Keyword, clientsCnt, requestsCnt, streamsCnt, size), (int)reqPerSec);
PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-failureSuccessRate", Keyword, clientsCnt, requestsCnt, streamsCnt, size), failuresRate);
if (Interlocked.Read(ref succ) != requestsCnt)
context.Fail(reason: "There were errors or not all requests completed.");
else
context.Success();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Ical.Net.DataTypes;
using Ical.Net.Evaluation;
using Ical.Net.Proxies;
using Ical.Net.Utility;
namespace Ical.Net.CalendarComponents
{
/// <summary>
/// An iCalendar component that recurs.
/// </summary>
/// <remarks>
/// This component automatically handles
/// RRULEs, RDATE, EXRULEs, and EXDATEs, as well as the DTSTART
/// for the recurring item (all recurring items must have a DTSTART).
/// </remarks>
public class RecurringComponent : UniqueComponent, IRecurringComponent
{
public static IEnumerable<IRecurringComponent> SortByDate(IEnumerable<IRecurringComponent> list) => SortByDate<IRecurringComponent>(list);
public static IEnumerable<TRecurringComponent> SortByDate<TRecurringComponent>(IEnumerable<TRecurringComponent> list) => list.OrderBy(d => d);
protected virtual bool EvaluationIncludesReferenceDate => false;
public virtual IList<Attachment> Attachments
{
get => Properties.GetMany<Attachment>("ATTACH");
set => Properties.Set("ATTACH", value);
}
public virtual IList<string> Categories
{
get => Properties.GetMany<string>("CATEGORIES");
set => Properties.Set("CATEGORIES", value);
}
public virtual string Class
{
get => Properties.Get<string>("CLASS");
set => Properties.Set("CLASS", value);
}
public virtual IList<string> Contacts
{
get => Properties.GetMany<string>("CONTACT");
set => Properties.Set("CONTACT", value);
}
public virtual IDateTime Created
{
get => Properties.Get<IDateTime>("CREATED");
set => Properties.Set("CREATED", value);
}
public virtual string Description
{
get => Properties.Get<string>("DESCRIPTION");
set => Properties.Set("DESCRIPTION", value);
}
/// <summary>
/// The start date/time of the component.
/// </summary>
public virtual IDateTime DtStart
{
get => Properties.Get<IDateTime>("DTSTART");
set => Properties.Set("DTSTART", value);
}
public virtual IList<PeriodList> ExceptionDates
{
get => Properties.GetMany<PeriodList>("EXDATE");
set => Properties.Set("EXDATE", value);
}
public virtual IList<RecurrencePattern> ExceptionRules
{
get => Properties.GetMany<RecurrencePattern>("EXRULE");
set => Properties.Set("EXRULE", value);
}
public virtual IDateTime LastModified
{
get => Properties.Get<IDateTime>("LAST-MODIFIED");
set => Properties.Set("LAST-MODIFIED", value);
}
public virtual int Priority
{
get => Properties.Get<int>("PRIORITY");
set => Properties.Set("PRIORITY", value);
}
public virtual IList<PeriodList> RecurrenceDates
{
get => Properties.GetMany<PeriodList>("RDATE");
set => Properties.Set("RDATE", value);
}
public virtual IList<RecurrencePattern> RecurrenceRules
{
get => Properties.GetMany<RecurrencePattern>("RRULE");
set => Properties.Set("RRULE", value);
}
public virtual IDateTime RecurrenceId
{
get => Properties.Get<IDateTime>("RECURRENCE-ID");
set => Properties.Set("RECURRENCE-ID", value);
}
public virtual IList<string> RelatedComponents
{
get => Properties.GetMany<string>("RELATED-TO");
set => Properties.Set("RELATED-TO", value);
}
public virtual int Sequence
{
get => Properties.Get<int>("SEQUENCE");
set => Properties.Set("SEQUENCE", value);
}
/// <summary>
/// An alias to the DTStart field (i.e. start date/time).
/// </summary>
public virtual IDateTime Start
{
get => DtStart;
set => DtStart = value;
}
public virtual string Summary
{
get => Properties.Get<string>("SUMMARY");
set => Properties.Set("SUMMARY", value);
}
/// <summary>
/// A list of <see cref="Alarm"/>s for this recurring component.
/// </summary>
public virtual ICalendarObjectList<Alarm> Alarms => new CalendarObjectListProxy<Alarm>(Children);
public RecurringComponent()
{
Initialize();
EnsureProperties();
}
public RecurringComponent(string name) : base(name)
{
Initialize();
EnsureProperties();
}
private void Initialize() => SetService(new RecurringEvaluator(this));
private void EnsureProperties()
{
if (!Properties.ContainsKey("SEQUENCE"))
{
Sequence = 0;
}
}
protected override void OnDeserializing(StreamingContext context)
{
base.OnDeserializing(context);
Initialize();
}
public virtual void ClearEvaluation() => RecurrenceUtil.ClearEvaluation(this);
public virtual HashSet<Occurrence> GetOccurrences(IDateTime dt) => RecurrenceUtil.GetOccurrences(this, dt, EvaluationIncludesReferenceDate);
public virtual HashSet<Occurrence> GetOccurrences(DateTime dt)
=> RecurrenceUtil.GetOccurrences(this, new CalDateTime(dt), EvaluationIncludesReferenceDate);
public virtual HashSet<Occurrence> GetOccurrences(IDateTime startTime, IDateTime endTime)
=> RecurrenceUtil.GetOccurrences(this, startTime, endTime, EvaluationIncludesReferenceDate);
public virtual HashSet<Occurrence> GetOccurrences(DateTime startTime, DateTime endTime)
=> RecurrenceUtil.GetOccurrences(this, new CalDateTime(startTime), new CalDateTime(endTime), EvaluationIncludesReferenceDate);
public virtual IList<AlarmOccurrence> PollAlarms() => PollAlarms(null, null);
public virtual IList<AlarmOccurrence> PollAlarms(IDateTime startTime, IDateTime endTime)
=> Alarms?.SelectMany(a => a.Poll(startTime, endTime)).ToList()
?? new List<AlarmOccurrence>();
protected bool Equals(RecurringComponent other)
{
var result = Equals(DtStart, other.DtStart)
&& Equals(Priority, other.Priority)
&& string.Equals(Summary, other.Summary, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Class, other.Class, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Description, other.Description, StringComparison.OrdinalIgnoreCase)
&& Equals(RecurrenceId, other.RecurrenceId)
&& Attachments.SequenceEqual(other.Attachments)
&& CollectionHelpers.Equals(Categories, other.Categories)
&& CollectionHelpers.Equals(Contacts, other.Contacts)
&& CollectionHelpers.Equals(ExceptionDates, other.ExceptionDates)
&& CollectionHelpers.Equals(ExceptionRules, other.ExceptionRules)
&& CollectionHelpers.Equals(RecurrenceDates, other.RecurrenceDates, orderSignificant: true)
&& CollectionHelpers.Equals(RecurrenceRules, other.RecurrenceRules, orderSignificant: true);
return result;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((RecurringComponent)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = DtStart?.GetHashCode() ?? 0;
hashCode = (hashCode * 397) ^ Priority.GetHashCode();
hashCode = (hashCode * 397) ^ (Summary?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (Class?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (Description?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (RecurrenceId?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(Attachments);
hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(Categories);
hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(Contacts);
hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(ExceptionDates);
hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(ExceptionRules);
hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(RecurrenceDates);
hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(RecurrenceRules);
return hashCode;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Https.Internal;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests
{
public class KestrelServerTests
{
private KestrelServerOptions CreateServerOptions()
{
var serverOptions = new KestrelServerOptions();
serverOptions.ApplicationServices = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
return serverOptions;
}
[Fact]
public void StartWithInvalidAddressThrows()
{
var testLogger = new TestApplicationErrorLogger { ThrowOnCriticalErrors = false };
using (var server = CreateServer(CreateServerOptions(), testLogger))
{
server.Features.Get<IServerAddressesFeature>().Addresses.Add("http:/asdf");
var exception = Assert.Throws<FormatException>(() => StartDummyApplication(server));
Assert.Contains("Invalid url", exception.Message);
Assert.Equal(0, testLogger.CriticalErrorsLogged);
}
}
[Fact]
public void StartWithHttpsAddressConfiguresHttpsEndpoints()
{
var options = CreateServerOptions();
options.DefaultCertificate = TestResources.GetTestCertificate();
using (var server = CreateServer(options))
{
server.Features.Get<IServerAddressesFeature>().Addresses.Add("https://127.0.0.1:0");
StartDummyApplication(server);
Assert.True(server.Options.OptionsInUse.Any());
Assert.True(server.Options.OptionsInUse[0].IsTls);
}
}
[Fact]
public void KestrelServerThrowsUsefulExceptionIfDefaultHttpsProviderNotAdded()
{
var options = CreateServerOptions();
options.IsDevCertLoaded = true; // Prevent the system default from being loaded
using (var server = CreateServer(options, throwOnCriticalErrors: false))
{
server.Features.Get<IServerAddressesFeature>().Addresses.Add("https://127.0.0.1:0");
var ex = Assert.Throws<InvalidOperationException>(() => StartDummyApplication(server));
Assert.Equal(CoreStrings.NoCertSpecifiedNoDevelopmentCertificateFound, ex.Message);
}
}
[Fact]
public void KestrelServerDoesNotThrowIfNoDefaultHttpsProviderButNoHttpUrls()
{
using (var server = CreateServer(CreateServerOptions()))
{
server.Features.Get<IServerAddressesFeature>().Addresses.Add("http://127.0.0.1:0");
StartDummyApplication(server);
}
}
[Fact]
public void KestrelServerDoesNotThrowIfNoDefaultHttpsProviderButManualListenOptions()
{
var serverOptions = CreateServerOptions();
serverOptions.Listen(new IPEndPoint(IPAddress.Loopback, 0));
using (var server = CreateServer(serverOptions))
{
server.Features.Get<IServerAddressesFeature>().Addresses.Add("https://127.0.0.1:0");
StartDummyApplication(server);
}
}
[Fact]
public void StartWithPathBaseInAddressThrows()
{
var testLogger = new TestApplicationErrorLogger { ThrowOnCriticalErrors = false };
using (var server = CreateServer(new KestrelServerOptions(), testLogger))
{
server.Features.Get<IServerAddressesFeature>().Addresses.Add("http://127.0.0.1:0/base");
var exception = Assert.Throws<InvalidOperationException>(() => StartDummyApplication(server));
Assert.Equal(
$"A path base can only be configured using {nameof(IApplicationBuilder)}.UsePathBase().",
exception.Message);
Assert.Equal(0, testLogger.CriticalErrorsLogged);
}
}
[Theory]
[InlineData("http://localhost:5000")]
[InlineData("The value of the string shouldn't matter.")]
[InlineData(null)]
public void StartWarnsWhenIgnoringIServerAddressesFeature(string ignoredAddress)
{
var testLogger = new TestApplicationErrorLogger();
var kestrelOptions = new KestrelServerOptions();
// Directly configuring an endpoint using Listen causes the IServerAddressesFeature to be ignored.
kestrelOptions.Listen(IPAddress.Loopback, 0);
using (var server = CreateServer(kestrelOptions, testLogger))
{
server.Features.Get<IServerAddressesFeature>().Addresses.Add(ignoredAddress);
StartDummyApplication(server);
var warning = testLogger.Messages.Single(log => log.LogLevel == LogLevel.Warning);
Assert.Contains("Overriding", warning.Message);
}
}
[Theory]
[InlineData(1, 2)]
[InlineData(int.MaxValue - 1, int.MaxValue)]
public void StartWithMaxRequestBufferSizeLessThanMaxRequestLineSizeThrows(long maxRequestBufferSize, int maxRequestLineSize)
{
var testLogger = new TestApplicationErrorLogger { ThrowOnCriticalErrors = false };
var options = new KestrelServerOptions
{
Limits =
{
MaxRequestBufferSize = maxRequestBufferSize,
MaxRequestLineSize = maxRequestLineSize
}
};
using (var server = CreateServer(options, testLogger))
{
var exception = Assert.Throws<InvalidOperationException>(() => StartDummyApplication(server));
Assert.Equal(
CoreStrings.FormatMaxRequestBufferSmallerThanRequestLineBuffer(maxRequestBufferSize, maxRequestLineSize),
exception.Message);
Assert.Equal(0, testLogger.CriticalErrorsLogged);
}
}
[Theory]
[InlineData(1, 2)]
[InlineData(int.MaxValue - 1, int.MaxValue)]
public void StartWithMaxRequestBufferSizeLessThanMaxRequestHeadersTotalSizeThrows(long maxRequestBufferSize, int maxRequestHeadersTotalSize)
{
var testLogger = new TestApplicationErrorLogger { ThrowOnCriticalErrors = false };
var options = new KestrelServerOptions
{
Limits =
{
MaxRequestBufferSize = maxRequestBufferSize,
MaxRequestLineSize = (int)maxRequestBufferSize,
MaxRequestHeadersTotalSize = maxRequestHeadersTotalSize
}
};
using (var server = CreateServer(options, testLogger))
{
var exception = Assert.Throws<InvalidOperationException>(() => StartDummyApplication(server));
Assert.Equal(
CoreStrings.FormatMaxRequestBufferSmallerThanRequestHeaderBuffer(maxRequestBufferSize, maxRequestHeadersTotalSize),
exception.Message);
Assert.Equal(0, testLogger.CriticalErrorsLogged);
}
}
[Fact]
public void LoggerCategoryNameIsKestrelServerNamespace()
{
var mockLoggerFactory = new Mock<ILoggerFactory>();
var mockLogger = new Mock<ILogger>();
mockLoggerFactory.Setup(m => m.CreateLogger(It.IsAny<string>())).Returns(mockLogger.Object);
new KestrelServer(Options.Create<KestrelServerOptions>(null), new MockTransportFactory(), mockLoggerFactory.Object);
mockLoggerFactory.Verify(factory => factory.CreateLogger("Microsoft.AspNetCore.Server.Kestrel"));
}
[Fact]
public void ConstructorWithNullTransportFactoryThrows()
{
var exception = Assert.Throws<ArgumentNullException>(() =>
new KestrelServer(
Options.Create<KestrelServerOptions>(null),
null,
new LoggerFactory(new[] { new KestrelTestLoggerProvider() })));
Assert.Equal("transportFactory", exception.ParamName);
}
[Fact]
public void ConstructorWithNoTransportFactoriesThrows()
{
var exception = Assert.Throws<InvalidOperationException>(() =>
new KestrelServerImpl(
Options.Create<KestrelServerOptions>(null),
new List<IConnectionListenerFactory>(),
new LoggerFactory(new[] { new KestrelTestLoggerProvider() })));
Assert.Equal(CoreStrings.TransportNotFound, exception.Message);
}
[Fact]
public void StartWithMultipleTransportFactoriesDoesNotThrow()
{
using var server = new KestrelServerImpl(
Options.Create(CreateServerOptions()),
new List<IConnectionListenerFactory>() { new ThrowingTransportFactory(), new MockTransportFactory() },
new LoggerFactory(new[] { new KestrelTestLoggerProvider() }));
StartDummyApplication(server);
}
[Fact]
public async Task ListenIPWithStaticPort_TransportsGetIPv6Any()
{
var options = new KestrelServerOptions();
options.ApplicationServices = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
options.ListenAnyIP(5000, options =>
{
options.UseHttps(TestResources.GetTestCertificate());
options.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
});
var mockTransportFactory = new MockTransportFactory();
var mockMultiplexedTransportFactory = new MockMultiplexedTransportFactory();
using var server = new KestrelServerImpl(
Options.Create(options),
new List<IConnectionListenerFactory>() { mockTransportFactory },
new List<IMultiplexedConnectionListenerFactory>() { mockMultiplexedTransportFactory },
new LoggerFactory(new[] { new KestrelTestLoggerProvider() }));
await server.StartAsync(new DummyApplication(context => Task.CompletedTask), CancellationToken.None);
var transportEndPoint = Assert.Single(mockTransportFactory.BoundEndPoints);
var multiplexedTransportEndPoint = Assert.Single(mockMultiplexedTransportFactory.BoundEndPoints);
// Both transports should get the IPv6Any
Assert.Equal(IPAddress.IPv6Any, ((IPEndPoint)transportEndPoint.OriginalEndPoint).Address);
Assert.Equal(IPAddress.IPv6Any, ((IPEndPoint)multiplexedTransportEndPoint.OriginalEndPoint).Address);
Assert.Equal(5000, ((IPEndPoint)transportEndPoint.OriginalEndPoint).Port);
Assert.Equal(5000, ((IPEndPoint)multiplexedTransportEndPoint.OriginalEndPoint).Port);
}
[Fact]
public async Task ListenIPWithEphemeralPort_TransportsGetIPv6Any()
{
var options = new KestrelServerOptions();
options.ApplicationServices = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
options.ListenAnyIP(0, options =>
{
options.UseHttps(TestResources.GetTestCertificate());
options.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
});
var mockTransportFactory = new MockTransportFactory();
var mockMultiplexedTransportFactory = new MockMultiplexedTransportFactory();
using var server = new KestrelServerImpl(
Options.Create(options),
new List<IConnectionListenerFactory>() { mockTransportFactory },
new List<IMultiplexedConnectionListenerFactory>() { mockMultiplexedTransportFactory },
new LoggerFactory(new[] { new KestrelTestLoggerProvider() }));
await server.StartAsync(new DummyApplication(context => Task.CompletedTask), CancellationToken.None);
var transportEndPoint = Assert.Single(mockTransportFactory.BoundEndPoints);
var multiplexedTransportEndPoint = Assert.Single(mockMultiplexedTransportFactory.BoundEndPoints);
Assert.Equal(IPAddress.IPv6Any, ((IPEndPoint)transportEndPoint.OriginalEndPoint).Address);
Assert.Equal(IPAddress.IPv6Any, ((IPEndPoint)multiplexedTransportEndPoint.OriginalEndPoint).Address);
// Should have been assigned a random value.
Assert.NotEqual(0, ((IPEndPoint)transportEndPoint.BoundEndPoint).Port);
// Same random value should be used for both transports.
Assert.Equal(((IPEndPoint)transportEndPoint.BoundEndPoint).Port, ((IPEndPoint)multiplexedTransportEndPoint.BoundEndPoint).Port);
}
[Fact]
public async Task StopAsyncCallsCompleteWhenFirstCallCompletes()
{
var options = new KestrelServerOptions
{
CodeBackedListenOptions =
{
new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0))
}
};
var unbind = new SemaphoreSlim(0);
var stop = new SemaphoreSlim(0);
var mockTransport = new Mock<IConnectionListener>();
var mockTransportFactory = new Mock<IConnectionListenerFactory>();
mockTransportFactory
.Setup(transportFactory => transportFactory.BindAsync(It.IsAny<EndPoint>(), It.IsAny<CancellationToken>()))
.Returns<EndPoint, CancellationToken>((e, token) =>
{
mockTransport
.Setup(transport => transport.AcceptAsync(It.IsAny<CancellationToken>()))
.Returns(new ValueTask<ConnectionContext>((ConnectionContext)null));
mockTransport
.Setup(transport => transport.UnbindAsync(It.IsAny<CancellationToken>()))
.Returns(() => new ValueTask(unbind.WaitAsync()));
mockTransport
.Setup(transport => transport.DisposeAsync())
.Returns(() => new ValueTask(stop.WaitAsync()));
mockTransport
.Setup(transport => transport.EndPoint).Returns(e);
return new ValueTask<IConnectionListener>(mockTransport.Object);
});
var mockLoggerFactory = new Mock<ILoggerFactory>();
var mockLogger = new Mock<ILogger>();
mockLoggerFactory.Setup(m => m.CreateLogger(It.IsAny<string>())).Returns(mockLogger.Object);
var server = new KestrelServer(Options.Create(options), mockTransportFactory.Object, mockLoggerFactory.Object);
await server.StartAsync(new DummyApplication(), CancellationToken.None);
var stopTask1 = server.StopAsync(default);
var stopTask2 = server.StopAsync(default);
var stopTask3 = server.StopAsync(default);
Assert.False(stopTask1.IsCompleted);
Assert.False(stopTask2.IsCompleted);
Assert.False(stopTask3.IsCompleted);
unbind.Release();
stop.Release();
await Task.WhenAll(new[] { stopTask1, stopTask2, stopTask3 }).DefaultTimeout();
mockTransport.Verify(transport => transport.UnbindAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task StopAsyncCallsCompleteWithThrownException()
{
var options = new KestrelServerOptions
{
CodeBackedListenOptions =
{
new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0))
}
};
var unbind = new SemaphoreSlim(0);
var unbindException = new InvalidOperationException();
var mockTransport = new Mock<IConnectionListener>();
var mockTransportFactory = new Mock<IConnectionListenerFactory>();
mockTransportFactory
.Setup(transportFactory => transportFactory.BindAsync(It.IsAny<EndPoint>(), It.IsAny<CancellationToken>()))
.Returns<EndPoint, CancellationToken>((e, token) =>
{
mockTransport
.Setup(transport => transport.AcceptAsync(It.IsAny<CancellationToken>()))
.Returns(new ValueTask<ConnectionContext>((ConnectionContext)null));
mockTransport
.Setup(transport => transport.UnbindAsync(It.IsAny<CancellationToken>()))
.Returns(async () =>
{
await unbind.WaitAsync();
throw unbindException;
});
mockTransport
.Setup(transport => transport.EndPoint).Returns(e);
return new ValueTask<IConnectionListener>(mockTransport.Object);
});
var mockLoggerFactory = new Mock<ILoggerFactory>();
var mockLogger = new Mock<ILogger>();
mockLoggerFactory.Setup(m => m.CreateLogger(It.IsAny<string>())).Returns(mockLogger.Object);
var server = new KestrelServer(Options.Create(options), mockTransportFactory.Object, mockLoggerFactory.Object);
await server.StartAsync(new DummyApplication(), CancellationToken.None);
var stopTask1 = server.StopAsync(default);
var stopTask2 = server.StopAsync(default);
var stopTask3 = server.StopAsync(default);
Assert.False(stopTask1.IsCompleted);
Assert.False(stopTask2.IsCompleted);
Assert.False(stopTask3.IsCompleted);
unbind.Release();
var timeout = TestConstants.DefaultTimeout;
Assert.Same(unbindException, await Assert.ThrowsAsync<InvalidOperationException>(() => stopTask1.TimeoutAfter(timeout)));
Assert.Same(unbindException, await Assert.ThrowsAsync<InvalidOperationException>(() => stopTask2.TimeoutAfter(timeout)));
Assert.Same(unbindException, await Assert.ThrowsAsync<InvalidOperationException>(() => stopTask3.TimeoutAfter(timeout)));
mockTransport.Verify(transport => transport.UnbindAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task StopAsyncDispatchesSubsequentStopAsyncContinuations()
{
var options = new KestrelServerOptions
{
CodeBackedListenOptions =
{
new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0))
}
};
var unbindTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var mockTransport = new Mock<IConnectionListener>();
var mockTransportFactory = new Mock<IConnectionListenerFactory>();
mockTransportFactory
.Setup(transportFactory => transportFactory.BindAsync(It.IsAny<EndPoint>(), It.IsAny<CancellationToken>()))
.Returns<EndPoint, CancellationToken>((e, token) =>
{
mockTransport
.Setup(transport => transport.AcceptAsync(It.IsAny<CancellationToken>()))
.Returns(new ValueTask<ConnectionContext>((ConnectionContext)null));
mockTransport
.Setup(transport => transport.UnbindAsync(It.IsAny<CancellationToken>()))
.Returns(new ValueTask(unbindTcs.Task));
mockTransport
.Setup(transport => transport.EndPoint).Returns(e);
return new ValueTask<IConnectionListener>(mockTransport.Object);
});
var mockLoggerFactory = new Mock<ILoggerFactory>();
var mockLogger = new Mock<ILogger>();
mockLoggerFactory.Setup(m => m.CreateLogger(It.IsAny<string>())).Returns(mockLogger.Object);
var server = new KestrelServer(Options.Create(options), mockTransportFactory.Object, mockLoggerFactory.Object);
await server.StartAsync(new DummyApplication(), default);
var stopTask1 = server.StopAsync(default);
var stopTask2 = server.StopAsync(default);
Assert.False(stopTask1.IsCompleted);
Assert.False(stopTask2.IsCompleted);
var continuationTask = Task.Run(async () =>
{
await stopTask2;
stopTask1.Wait();
});
unbindTcs.SetResult();
// If stopTask2 is completed inline by the first call to StopAsync, stopTask1 will never complete.
await stopTask1.DefaultTimeout();
await stopTask2.DefaultTimeout();
await continuationTask.DefaultTimeout();
mockTransport.Verify(transport => transport.UnbindAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public void StartingServerInitializesHeartbeat()
{
var testContext = new TestServiceContext
{
ServerOptions =
{
CodeBackedListenOptions =
{
new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0))
}
},
DateHeaderValueManager = new DateHeaderValueManager()
};
testContext.Heartbeat = new Heartbeat(
new IHeartbeatHandler[] { testContext.DateHeaderValueManager },
testContext.MockSystemClock,
DebuggerWrapper.Singleton,
testContext.Log);
using (var server = new KestrelServerImpl(new MockTransportFactory(), testContext))
{
Assert.Null(testContext.DateHeaderValueManager.GetDateHeaderValues());
// Ensure KestrelServer is started at a different time than when it was constructed, since we're
// verifying the heartbeat is initialized during KestrelServer.StartAsync().
testContext.MockSystemClock.UtcNow += TimeSpan.FromDays(1);
StartDummyApplication(server);
Assert.Equal(HeaderUtilities.FormatDate(testContext.MockSystemClock.UtcNow),
testContext.DateHeaderValueManager.GetDateHeaderValues().String);
}
}
[Fact]
public async Task ReloadsOnConfigurationChangeWhenOptedIn()
{
var currentConfig = new ConfigurationBuilder().AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>("Endpoints:A:Url", "http://*:5000"),
new KeyValuePair<string, string>("Endpoints:B:Url", "http://*:5001"),
}).Build();
Func<Task> changeCallback = null;
TaskCompletionSource changeCallbackRegisteredTcs = null;
var mockChangeToken = new Mock<IChangeToken>();
mockChangeToken.Setup(t => t.RegisterChangeCallback(It.IsAny<Action<object>>(), It.IsAny<object>())).Returns<Action<object>, object>((callback, state) =>
{
changeCallbackRegisteredTcs?.SetResult();
changeCallback = () =>
{
changeCallbackRegisteredTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
callback(state);
return changeCallbackRegisteredTcs.Task;
};
return Mock.Of<IDisposable>();
});
var mockConfig = new Mock<IConfiguration>();
mockConfig.Setup(c => c.GetSection(It.IsAny<string>())).Returns<string>(name => currentConfig.GetSection(name));
mockConfig.Setup(c => c.GetChildren()).Returns(() => currentConfig.GetChildren());
mockConfig.Setup(c => c.GetReloadToken()).Returns(() => mockChangeToken.Object);
var mockLoggerFactory = new Mock<ILoggerFactory>();
mockLoggerFactory.Setup(m => m.CreateLogger(It.IsAny<string>())).Returns(Mock.Of<ILogger>());
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(Mock.Of<IHostEnvironment>());
serviceCollection.AddSingleton(Mock.Of<ILogger<KestrelServer>>());
serviceCollection.AddSingleton(Mock.Of<ILogger<HttpsConnectionMiddleware>>());
var options = new KestrelServerOptions
{
ApplicationServices = serviceCollection.BuildServiceProvider(),
};
options.Configure(mockConfig.Object, reloadOnChange: true);
var mockTransports = new List<Mock<IConnectionListener>>();
var mockTransportFactory = new Mock<IConnectionListenerFactory>();
mockTransportFactory
.Setup(transportFactory => transportFactory.BindAsync(It.IsAny<EndPoint>(), It.IsAny<CancellationToken>()))
.Returns<EndPoint, CancellationToken>((e, token) =>
{
var mockTransport = new Mock<IConnectionListener>();
mockTransport
.Setup(transport => transport.AcceptAsync(It.IsAny<CancellationToken>()))
.Returns(new ValueTask<ConnectionContext>(result: null));
mockTransport
.Setup(transport => transport.EndPoint)
.Returns(e);
mockTransports.Add(mockTransport);
return new ValueTask<IConnectionListener>(mockTransport.Object);
});
// Don't use "using". Dispose() could hang if test fails.
var server = new KestrelServer(Options.Create(options), mockTransportFactory.Object, mockLoggerFactory.Object);
await server.StartAsync(new DummyApplication(), CancellationToken.None).DefaultTimeout();
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5000), It.IsAny<CancellationToken>()), Times.Once);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5001), It.IsAny<CancellationToken>()), Times.Once);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5002), It.IsAny<CancellationToken>()), Times.Never);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5003), It.IsAny<CancellationToken>()), Times.Never);
Assert.Equal(2, mockTransports.Count);
foreach (var mockTransport in mockTransports)
{
mockTransport.Verify(t => t.UnbindAsync(It.IsAny<CancellationToken>()), Times.Never);
}
currentConfig = new ConfigurationBuilder().AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>("Endpoints:A:Url", "http://*:5000"),
new KeyValuePair<string, string>("Endpoints:B:Url", "http://*:5002"),
new KeyValuePair<string, string>("Endpoints:C:Url", "http://*:5003"),
}).Build();
await changeCallback().DefaultTimeout();
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5000), It.IsAny<CancellationToken>()), Times.Once);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5001), It.IsAny<CancellationToken>()), Times.Once);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5002), It.IsAny<CancellationToken>()), Times.Once);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5003), It.IsAny<CancellationToken>()), Times.Once);
Assert.Equal(4, mockTransports.Count);
foreach (var mockTransport in mockTransports)
{
if (((IPEndPoint)mockTransport.Object.EndPoint).Port == 5001)
{
mockTransport.Verify(t => t.UnbindAsync(It.IsAny<CancellationToken>()), Times.Once);
}
else
{
mockTransport.Verify(t => t.UnbindAsync(It.IsAny<CancellationToken>()), Times.Never);
}
}
currentConfig = new ConfigurationBuilder().AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>("Endpoints:A:Url", "http://*:5000"),
new KeyValuePair<string, string>("Endpoints:B:Url", "http://*:5002"),
new KeyValuePair<string, string>("Endpoints:C:Url", "http://*:5003"),
new KeyValuePair<string, string>("Endpoints:C:Protocols", "Http1"),
}).Build();
await changeCallback().DefaultTimeout();
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5000), It.IsAny<CancellationToken>()), Times.Once);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5001), It.IsAny<CancellationToken>()), Times.Once);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5002), It.IsAny<CancellationToken>()), Times.Once);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5003), It.IsAny<CancellationToken>()), Times.Exactly(2));
Assert.Equal(5, mockTransports.Count);
var firstPort5003TransportChecked = false;
foreach (var mockTransport in mockTransports)
{
var port = ((IPEndPoint)mockTransport.Object.EndPoint).Port;
if (port == 5001)
{
mockTransport.Verify(t => t.UnbindAsync(It.IsAny<CancellationToken>()), Times.Once);
}
else if (port == 5003 && !firstPort5003TransportChecked)
{
mockTransport.Verify(t => t.UnbindAsync(It.IsAny<CancellationToken>()), Times.Once);
firstPort5003TransportChecked = true;
}
else
{
mockTransport.Verify(t => t.UnbindAsync(It.IsAny<CancellationToken>()), Times.Never);
}
}
await server.StopAsync(CancellationToken.None).DefaultTimeout();
foreach (var mockTransport in mockTransports)
{
mockTransport.Verify(t => t.UnbindAsync(It.IsAny<CancellationToken>()), Times.Once);
}
}
[Fact]
public async Task DoesNotReloadOnConfigurationChangeByDefault()
{
var currentConfig = new ConfigurationBuilder().AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>("Endpoints:A:Url", "http://*:5000"),
new KeyValuePair<string, string>("Endpoints:B:Url", "http://*:5001"),
}).Build();
var mockConfig = new Mock<IConfiguration>();
mockConfig.Setup(c => c.GetSection(It.IsAny<string>())).Returns<string>(name => currentConfig.GetSection(name));
mockConfig.Setup(c => c.GetChildren()).Returns(() => currentConfig.GetChildren());
var mockLoggerFactory = new Mock<ILoggerFactory>();
mockLoggerFactory.Setup(m => m.CreateLogger(It.IsAny<string>())).Returns(Mock.Of<ILogger>());
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(Mock.Of<IHostEnvironment>());
serviceCollection.AddSingleton(Mock.Of<ILogger<KestrelServer>>());
serviceCollection.AddSingleton(Mock.Of<ILogger<HttpsConnectionMiddleware>>());
var options = new KestrelServerOptions
{
ApplicationServices = serviceCollection.BuildServiceProvider(),
};
options.Configure(mockConfig.Object);
var mockTransports = new List<Mock<IConnectionListener>>();
var mockTransportFactory = new Mock<IConnectionListenerFactory>();
mockTransportFactory
.Setup(transportFactory => transportFactory.BindAsync(It.IsAny<EndPoint>(), It.IsAny<CancellationToken>()))
.Returns<EndPoint, CancellationToken>((e, token) =>
{
var mockTransport = new Mock<IConnectionListener>();
mockTransport
.Setup(transport => transport.AcceptAsync(It.IsAny<CancellationToken>()))
.Returns(new ValueTask<ConnectionContext>(result: null));
mockTransport
.Setup(transport => transport.EndPoint)
.Returns(e);
mockTransports.Add(mockTransport);
return new ValueTask<IConnectionListener>(mockTransport.Object);
});
// Don't use "using". Dispose() could hang if test fails.
var server = new KestrelServer(Options.Create(options), mockTransportFactory.Object, mockLoggerFactory.Object);
await server.StartAsync(new DummyApplication(), CancellationToken.None).DefaultTimeout();
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5000), It.IsAny<CancellationToken>()), Times.Once);
mockTransportFactory.Verify(f => f.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 5001), It.IsAny<CancellationToken>()), Times.Once);
mockConfig.Verify(c => c.GetReloadToken(), Times.Never);
await server.StopAsync(CancellationToken.None).DefaultTimeout();
}
private static KestrelServer CreateServer(KestrelServerOptions options, ILogger testLogger)
{
return new KestrelServer(Options.Create(options), new MockTransportFactory(), new LoggerFactory(new[] { new KestrelTestLoggerProvider(testLogger) }));
}
private static KestrelServer CreateServer(KestrelServerOptions options, bool throwOnCriticalErrors = true)
{
return new KestrelServer(Options.Create(options), new MockTransportFactory(), new LoggerFactory(new[] { new KestrelTestLoggerProvider(throwOnCriticalErrors) }));
}
private static void StartDummyApplication(IServer server)
{
server.StartAsync(new DummyApplication(context => Task.CompletedTask), CancellationToken.None).GetAwaiter().GetResult();
}
private class MockTransportFactory : IConnectionListenerFactory
{
public List<BindDetail> BoundEndPoints { get; } = new List<BindDetail>();
public ValueTask<IConnectionListener> BindAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
{
EndPoint resolvedEndPoint = endpoint;
if (resolvedEndPoint is IPEndPoint ipEndPoint)
{
var port = ipEndPoint.Port == 0
? Random.Shared.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort)
: ipEndPoint.Port;
resolvedEndPoint = new IPEndPoint(new IPAddress(ipEndPoint.Address.GetAddressBytes()), port);
}
BoundEndPoints.Add(new BindDetail(endpoint, resolvedEndPoint));
var mock = new Mock<IConnectionListener>();
mock.Setup(m => m.EndPoint).Returns(resolvedEndPoint);
return new ValueTask<IConnectionListener>(mock.Object);
}
}
private class ThrowingTransportFactory : IConnectionListenerFactory
{
public ValueTask<IConnectionListener> BindAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
{
throw new InvalidOperationException();
}
}
private class MockMultiplexedTransportFactory : IMultiplexedConnectionListenerFactory
{
public List<BindDetail> BoundEndPoints { get; } = new List<BindDetail>();
public ValueTask<IMultiplexedConnectionListener> BindAsync(EndPoint endpoint, IFeatureCollection features = null, CancellationToken cancellationToken = default)
{
EndPoint resolvedEndPoint = endpoint;
if (resolvedEndPoint is IPEndPoint ipEndPoint)
{
var port = ipEndPoint.Port == 0
? Random.Shared.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort)
: ipEndPoint.Port;
resolvedEndPoint = new IPEndPoint(new IPAddress(ipEndPoint.Address.GetAddressBytes()), port);
}
BoundEndPoints.Add(new BindDetail(endpoint, resolvedEndPoint));
var mock = new Mock<IMultiplexedConnectionListener>();
mock.Setup(m => m.EndPoint).Returns(resolvedEndPoint);
return new ValueTask<IMultiplexedConnectionListener>(mock.Object);
}
}
private record BindDetail(EndPoint OriginalEndPoint, EndPoint BoundEndPoint);
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Provider;
using Microsoft.Feeds.Interop;
namespace Pscx.Providers
{
[CmdletProvider(PscxProviders.FeedStore, ProviderCapabilities.ShouldProcess)]
public class FeedStoreProvider : NavigationCmdletProvider
{
private string _pathSeparator = Path.DirectorySeparatorChar.ToString();
public static FeedsManager FeedsManager
{
get { return FeedsManagerSingleton.Instance; }
}
private class FeedsManagerSingleton
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static FeedsManagerSingleton()
{
}
internal static readonly FeedsManager Instance = new FeedsManager();
}
#region Private methods
/// <summary>
/// Breaks up the path into individual elements.
/// </summary>
/// <param name="path">The path to split.</param>
/// <returns>An array of path segments.</returns>
private string[] ChunkPath(string path)
{
// Return the path with the drive name and first path
// separator character removed, split by the path separator.
return path.Split(_pathSeparator.ToCharArray());
}
/// <summary>
/// Adapts the path, making sure the correct path separator
/// character is used.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private string NormalizePath(string path)
{
if (String.IsNullOrEmpty(path)) return path;
string result = path.Replace("/", _pathSeparator);
if (result.StartsWith(_pathSeparator))
{
result = result.Substring(_pathSeparator.Length);
}
if (result.EndsWith(_pathSeparator))
{
result = result.Substring(0, result.Length - _pathSeparator.Length);
}
return result;
}
/// <summary>
/// Checks if a given path is actually a drive name.
/// </summary>
/// <param name="path">The path to check.</param>
/// <returns>
/// True if the path given represents a drive, false otherwise.
/// </returns>
private bool PathIsDrive(string path)
{
return String.IsNullOrEmpty(path) || String.IsNullOrEmpty(path.Replace(_pathSeparator, ""));
}
#endregion
#region Protected methods
protected override Collection<PSDriveInfo>InitializeDefaultDrives()
{
Type t = Type.GetTypeFromProgID("Microsoft.FeedsManager", false);
if (t == null) return null;
// we only need to initialize a single default drive
return new Collection<PSDriveInfo>(
new PSDriveInfo[] {
new PSDriveInfo("Feed", this.ProviderInfo, "", "Microsoft Common Feed Store", this.Credential)
});
}
protected override bool IsValidPath(string path)
{
if (String.IsNullOrEmpty(path)) return true;
// Converts all separators in the path to a uniform one.
path = NormalizePath(path);
// Splits the path into individual chunks.
string[] pathChunks = path.Split(_pathSeparator.ToCharArray());
foreach (string pathChunk in pathChunks)
{
if (pathChunk.Length == 0) return false;
}
return true;
}
protected override bool IsItemContainer(string path)
{
path = NormalizePath(path);
if (PathIsDrive(path)) return true;
return FeedsManager.ExistsFolder(path) || FeedsManager.ExistsFeed(path);
}
protected override void NewItem(string path, string itemTypeName, object newItemValue)
{
path = NormalizePath(path);
if (PathIsDrive(path))
{
throw new ArgumentException("Path must be a a folder or feed.");
}
if (itemTypeName.ToLower().StartsWith("f"))
{
if (itemTypeName.Length == 1)
{
WriteError(new ErrorRecord(new ArgumentException("Ambiguous type. Only \"folder\" or \"feed\" can be specified."),
"InvalidArgument", ErrorCategory.InvalidArgument, itemTypeName));
}
// The leaf of the path will contain the name of the item to create
string[] pathChunks = ChunkPath(path);
string parentPath = GetParentPath(path, "");
// create a new folder. Let's check that we're in a folder and not a feed
if (!FeedsManager.ExistsFolder(parentPath))
{
WriteError(new ErrorRecord(new ArgumentException("Items can only be created within folders."),
"InvalidArgument", ErrorCategory.InvalidArgument, path));
return;
}
IFeedFolder folder = FeedsManager.GetFolder(parentPath) as IFeedFolder;
string newItemName = pathChunks[pathChunks.Length - 1];
//if (String.Compare("folder", 0, itemTypeName, 0, itemTypeName.Length, true) == 0)
if (itemTypeName.Equals("folder", StringComparison.OrdinalIgnoreCase) ||
itemTypeName.Equals("directory", StringComparison.OrdinalIgnoreCase))
{
IFeedFolder newFolder = folder.CreateSubfolder(newItemName) as IFeedFolder;
WriteItemObject(newFolder, newFolder.Path, true);
return;
}
if (String.Compare("feed", 0, itemTypeName, 0, itemTypeName.Length, true) == 0)
{
if (newItemValue == null || !Uri.IsWellFormedUriString(newItemValue.ToString(), UriKind.Absolute))
{
WriteError(new ErrorRecord
(new ArgumentException("Value must be a valid feed URI."),
"InvalidArgument", ErrorCategory.InvalidArgument, newItemValue)
);
return;
}
IFeed newFeed = folder.CreateFeed(newItemName, newItemValue.ToString()) as IFeed;
WriteItemObject(newFeed, newFeed.Path, true);
return;
}
}
WriteError(new ErrorRecord(new ArgumentException("The type is not a known type for the feed store. Only \"folder\" or \"feed\" can be specified."),
"InvalidArgument", ErrorCategory.InvalidArgument, itemTypeName));
return;
}
protected override void MoveItem(string path, string destination)
{
path = NormalizePath(path);
destination = NormalizePath(destination);
if (!FeedsManager.ExistsFolder(destination))
{
WriteError(new ErrorRecord
(new ArgumentException("Target feed folder not found."),
"InvalidArgument", ErrorCategory.InvalidArgument, destination)
);
return;
}
if (FeedsManager.ExistsFolder(path))
{
IFeedFolder folder = FeedsManager.GetFolder(path) as IFeedFolder;
if (ShouldProcess(folder.Path, "move"))
{
folder.Move(destination);
WriteItemObject(folder, folder.Path, true);
}
return;
}
if (FeedsManager.ExistsFeed(path))
{
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
if (ShouldProcess(feed.Path, "move"))
{
feed.Move(destination);
WriteItemObject(feed, feed.Path, true);
}
return;
}
WriteError(new ErrorRecord
(new ArgumentException("Item not found."),
"InvalidArgument", ErrorCategory.InvalidArgument, path)
);
return;
}
protected override void RenameItem(string path, string newName)
{
if (newName.Contains(_pathSeparator))
{
WriteError(new ErrorRecord
(new ArgumentException("Cannot rename because the target specified is not a path."),
"InvalidArgument", ErrorCategory.InvalidArgument, newName)
);
return;
}
path = NormalizePath(path);
if (FeedsManager.ExistsFolder(path))
{
IFeedFolder folder = FeedsManager.GetFolder(path) as IFeedFolder;
if (ShouldProcess(folder.Path, "rename"))
{
WriteDebug("Renaming folder " + folder.Path);
folder.Rename(newName);
WriteItemObject(folder, folder.Path, true);
}
return;
}
if (FeedsManager.ExistsFeed(path))
{
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
if (Force && ShouldProcess(feed.Path, "rename"))
{
WriteDebug("Renaming feed " + feed.Path);
feed.Rename(newName);
WriteItemObject(feed, feed.Path, true);
}
return;
}
WriteError(new ErrorRecord
(new NotImplementedException("Cannot rename because item specified."),
"NotImplemented", ErrorCategory.NotImplemented, path)
);
} // RenameItem
protected override void RemoveItem(string path, bool recurse)
{
path = NormalizePath(path);
if (FeedsManager.ExistsFolder(path))
{
IFeedFolder folder = FeedsManager.GetFolder(path) as IFeedFolder;
if (ShouldProcess(path, "delete"))
{
folder.Delete();
}
return;
}
if (FeedsManager.ExistsFeed(path))
{
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
if (ShouldProcess(path, "delete"))
{
feed.Delete();
}
return;
}
WriteError(new ErrorRecord
(new ItemNotFoundException("Item not found."),
"InvalidArgument", ErrorCategory.InvalidArgument, path)
);
}
protected override bool ItemExists(string path)
{
path = NormalizePath(path);
if (PathIsDrive(path)) return true;
if (FeedsManager.ExistsFolder(path) || FeedsManager.ExistsFeed(path)) return true;
string[] chunks = ChunkPath(path);
if (chunks.Length > 0)
{
int id;
if (int.TryParse(chunks[chunks.Length - 1], out id))
{
path = GetParentPath(path, "");
if (FeedsManager.ExistsFeed(path))
{
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
IFeedItem feedItem = feed.GetItem(id) as IFeedItem;
return feedItem != null;
}
}
}
return false;
}
protected override bool HasChildItems(string path)
{
path = NormalizePath(path);
if (PathIsDrive(path))
{
IFeedFolder root = FeedsManager.RootFolder as IFeedFolder;
IFeedsEnum subFolders = root.Subfolders as IFeedsEnum;
if (subFolders.Count > 0) return true;
IFeedsEnum feeds = root.Feeds as IFeedsEnum;
if (feeds.Count > 0) return true;
}
else
{
if (FeedsManager.ExistsFolder(path))
{
IFeedFolder folder = FeedsManager.GetFolder(path) as IFeedFolder;
IFeedsEnum subFolders = folder.Subfolders as IFeedsEnum;
if (subFolders.Count > 0) return true;
IFeedsEnum feeds = folder.Feeds as IFeedsEnum;
if (feeds.Count > 0) return true;
}
if (FeedsManager.ExistsFeed(path))
{
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
return feed.ItemCount > 0;
}
}
return false;
}
protected override object GetChildItemsDynamicParameters(string path, bool recurse)
{
// We provide an "-unread" parameter so that the user can choose to only list
// unread items (and folders and feeds with unread items)
WriteVerbose("GetChildItemsDynamicParameters:path = " + path);
ParameterAttribute unreadAttrib = new ParameterAttribute();
unreadAttrib.Mandatory = false;
unreadAttrib.ValueFromPipeline = false;
RuntimeDefinedParameter unreadParam = new RuntimeDefinedParameter();
unreadParam.IsSet = false;
unreadParam.Name = "Unread";
unreadParam.ParameterType = typeof(SwitchParameter);
unreadParam.Attributes.Add(unreadAttrib);
RuntimeDefinedParameterDictionary dic = new RuntimeDefinedParameterDictionary();
dic.Add("Unread", unreadParam);
return dic;
}
protected override object GetChildNamesDynamicParameters(string path)
{
/* for now we'll just use the same parameters as gci */
return GetChildItemsDynamicParameters(path, false);
}
protected override void GetChildItems(string path, bool recurse)
{
path = NormalizePath(path);
WriteDebug("Listing items in " + path);
bool unreadOnly = false;
RuntimeDefinedParameterDictionary dic = DynamicParameters as RuntimeDefinedParameterDictionary;
if (dic != null && dic.ContainsKey("Unread"))
{
RuntimeDefinedParameter rdp = dic["Unread"];
unreadOnly = rdp.IsSet;
}
WriteDebug(unreadOnly ? "Unread items only" : "All items");
// Checks if the path represented is a drive. This means that the
// children of the path are folders and feeds
if (PathIsDrive(path))
{
WriteDebug("Listing root folder folders");
IFeedFolder folder = FeedsManager.RootFolder as IFeedFolder;
IFeedsEnum subFolders = folder.Subfolders as IFeedsEnum;
foreach (IFeedFolder subFolder in subFolders)
{
if (!unreadOnly || subFolder.TotalUnreadItemCount > 0)
{
WriteItemObject(subFolder, subFolder.Path, true);
if (recurse) GetChildItems(subFolder.Path, true);
}
}
WriteDebug("Listing root folder feeds");
IFeedsEnum feeds = folder.Feeds as IFeedsEnum;
foreach (IFeed feed in feeds)
{
if (!unreadOnly || feed.UnreadItemCount > 0)
{
WriteItemObject(feed, feed.Path, true);
if (recurse) GetChildItems(feed.Path, true);
}
}
return;
}
if (FeedsManager.ExistsFolder(path))
{
WriteDebug("Listing folders in " + path);
IFeedFolder folder = FeedsManager.GetFolder(path) as IFeedFolder;
IFeedsEnum subFolders = folder.Subfolders as IFeedsEnum;
foreach (IFeedFolder subFolder in subFolders)
{
if (!unreadOnly || subFolder.TotalUnreadItemCount > 0)
{
WriteItemObject(subFolder, subFolder.Path, true);
if (recurse) GetChildItems(subFolder.Path, true);
}
}
WriteDebug("Listing feeds in " + path);
IFeedsEnum feeds = folder.Feeds as IFeedsEnum;
foreach (IFeed feed in feeds)
{
if (!unreadOnly || feed.UnreadItemCount > 0)
{
WriteItemObject(feed, feed.Path, true);
if (recurse) GetChildItems(feed.Path, true);
}
}
return;
}
if (FeedsManager.ExistsFeed(path))
{
WriteDebug("Listing items in " + path);
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
IFeedsEnum feedItems = feed.Items as IFeedsEnum;
foreach (IFeedItem feedItem in feedItems)
{
if (!unreadOnly || !feedItem.IsRead)
{
WriteItemObject(feedItem, feed.Path + _pathSeparator + feedItem.LocalId, false);
}
}
return;
}
} // GetChildItems
protected override string GetChildName(string path)
{
path = NormalizePath(path);
WriteDebug("Getting name for " + path);
// Checks if the path represented is a drive
if (PathIsDrive(path))
{
return "";
}// if (PathIsDrive...
if (FeedsManager.ExistsFolder(path))
{
IFeedFolder folder = FeedsManager.GetFolder(path) as IFeedFolder;
return folder.Name;
}
if (FeedsManager.ExistsFeed(path))
{
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
return feed.Name;
}
WriteDebug("Couldn't find drive, folder or feed - checking for item.");
string[] chunks = ChunkPath(path);
if (chunks.Length > 0)
{
WriteDebug("Chunks:");
foreach (string chk in chunks) WriteDebug("chunk: " + chk);
int id;
if (int.TryParse(chunks[chunks.Length - 1], out id))
{
path = GetParentPath(path, "");
WriteDebug("Looking for feed " + path);
if (FeedsManager.ExistsFeed(path))
{
WriteDebug("Found feed - looking for item");
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
IFeedItem feedItem = feed.GetItem(id) as IFeedItem;
if (feedItem != null)
{
WriteDebug("Found item - returning " + feedItem.LocalId);
return feedItem.LocalId.ToString();
}
}
}
}
return base.GetChildName(path);
}
protected override void GetChildNames(string path, ReturnContainers returnContainers)
{
path = NormalizePath(path);
WriteDebug("Listing names in " + path);
bool unreadOnly = false;
RuntimeDefinedParameterDictionary dic = DynamicParameters as RuntimeDefinedParameterDictionary;
if (dic != null && dic.ContainsKey("Unread"))
{
RuntimeDefinedParameter rdp = dic["Unread"];
unreadOnly = rdp.IsSet;
}
WriteDebug(unreadOnly ? "Unread items only" : "All items");
// Checks if the path represented is a drive. This means that the
// children of the path are folders and feeds
if (PathIsDrive(path))
{
WriteDebug("Listing root folder folder names");
IFeedFolder folder = FeedsManager.RootFolder as IFeedFolder;
IFeedsEnum subFolders = folder.Subfolders as IFeedsEnum;
foreach (IFeedFolder subFolder in subFolders)
{
if (!unreadOnly || subFolder.TotalUnreadItemCount > 0)
{
WriteItemObject(subFolder.Name, subFolder.Path, true);
}
}
WriteDebug("Listing root folder feed names");
IFeedsEnum feeds = folder.Feeds as IFeedsEnum;
foreach (IFeed feed in feeds)
{
if (!unreadOnly || feed.UnreadItemCount > 0)
{
WriteItemObject(feed.Name, feed.Path, true);
}
}
return;
}
if (FeedsManager.ExistsFolder(path))
{
WriteDebug("Listing folder names in " + path);
IFeedFolder folder = FeedsManager.GetFolder(path) as IFeedFolder;
IFeedsEnum subFolders = folder.Subfolders as IFeedsEnum;
foreach (IFeedFolder subFolder in subFolders)
{
if (!unreadOnly || subFolder.TotalUnreadItemCount > 0)
{
WriteItemObject(subFolder.Name, subFolder.Path, true);
}
}
WriteDebug("Listing feed names in " + path);
IFeedsEnum feeds = folder.Feeds as IFeedsEnum;
foreach (IFeed feed in feeds)
{
if (!unreadOnly || feed.UnreadItemCount > 0)
{
WriteItemObject(feed.Name, feed.Path, true);
}
}
return;
}
if (FeedsManager.ExistsFeed(path))
{
WriteDebug("Listing names in " + path);
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
IFeedsEnum feedItems = feed.Items as IFeedsEnum;
foreach (IFeedItem feedItem in feedItems)
{
if (!unreadOnly || !feedItem.IsRead)
{
WriteItemObject(feedItem.LocalId.ToString(), feed.Path + _pathSeparator + feedItem.LocalId, false);
}
}
return;
}
} // GetChildNames
protected override void GetItem(string path)
{
path = NormalizePath(path);
// Checks if the path represented is a drive
if (PathIsDrive(path))
{
WriteItemObject(FeedsManager.RootFolder, PSDriveInfo.Name + ':', true);
return;
}// if (PathIsDrive...
if (FeedsManager.ExistsFolder(path))
{
IFeedFolder folder = FeedsManager.GetFolder(path) as IFeedFolder;
WriteItemObject(folder, folder.Path, true);
return;
}
if (FeedsManager.ExistsFeed(path))
{
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
WriteItemObject(feed, feed.Path, true);
return;
}
string[] chunks = ChunkPath(path);
if (chunks.Length > 0)
{
int id;
if (int.TryParse(chunks[chunks.Length - 1], out id))
{
path = GetParentPath(path, "");
if (FeedsManager.ExistsFeed(path))
{
IFeed feed = FeedsManager.GetFeed(path) as IFeed;
IFeedItem feedItem = feed.GetItem(id) as IFeedItem;
if (feedItem != null)
{
WriteItemObject(feedItem, feed.Path + _pathSeparator + feedItem.LocalId, false);
return;
}
}
}
}
base.GetItem(path);
} // GetItem
#endregion
}
}
| |
//
// Copyright (c) 2014-2015 Piotr Fusik <piotr@fusik.info>
//
// 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.
//
// 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.
//
#if DOTNET35
using NUnit.Framework;
using Sooda.UnitTests.BaseObjects;
using System.Linq;
namespace Sooda.UnitTests.TestCases.Linq
{
[TestFixture]
public class PrecommitTest
{
[Test]
public void NewCount()
{
using (new SoodaTransaction())
{
int n = Contact.Linq().Count();
Assert.AreEqual(7, n);
new Contact();
n = Contact.Linq().Count();
Assert.AreEqual(8, n);
}
}
[Test]
public void UpdateCount()
{
using (new SoodaTransaction())
{
int n = Contact.Linq().Count(c => c.Active);
Assert.AreEqual(7, n);
Contact.Mary.Active = false;
n = Contact.Linq().Count(c => c.Active);
Assert.AreEqual(6, n);
n = Contact.Linq().Count(c => !c.Active);
Assert.AreEqual(1, n);
}
}
[Test]
public void DeleteCount()
{
using (new SoodaTransaction())
{
int n = Contact.Linq().Count();
Assert.AreEqual(7, n);
Contact.GetRef(5).MarkForDelete();
n = Contact.Linq().Count();
Assert.AreEqual(6, n);
}
}
[Test]
public void NewToList()
{
using (new SoodaTransaction())
{
int n = Contact.Linq().ToList().Count;
Assert.AreEqual(7, n);
new Contact();
n = Contact.Linq().ToList().Count;
Assert.AreEqual(8, n);
}
}
[Test]
public void UpdateToList()
{
using (new SoodaTransaction())
{
int n = Contact.Linq().Where(c => c.Active).ToList().Count;
Assert.AreEqual(7, n);
Contact.Mary.Active = false;
n = Contact.Linq().Where(c => c.Active).ToList().Count;
Assert.AreEqual(6, n);
n = Contact.Linq().Where(c => !c.Active).ToList().Count;
Assert.AreEqual(1, n);
}
}
[Test]
public void DeleteToList()
{
using (new SoodaTransaction())
{
int n = Contact.Linq().ToList().Count;
Assert.AreEqual(7, n);
Contact.GetRef(5).MarkForDelete();
n = Contact.Linq().ToList().Count;
Assert.AreEqual(6, n);
}
}
[Test]
public void NewSelect()
{
using (new SoodaTransaction())
{
int n = Contact.Linq().Select(c => c.Name).ToList().Count;
Assert.AreEqual(7, n);
new Contact();
n = Contact.Linq().Select(c => c.Name).ToList().Count;
Assert.AreEqual(8, n);
}
}
[Test]
public void UpdateSelect()
{
using (new SoodaTransaction())
{
int n = Contact.Linq().Where(c => c.Active).Select(c => c.Name).ToList().Count;
Assert.AreEqual(7, n);
Contact.Mary.Active = false;
n = Contact.Linq().Where(c => c.Active).Select(c => c.Name).ToList().Count;
Assert.AreEqual(6, n);
n = Contact.Linq().Where(c => !c.Active).Select(c => c.Name).ToList().Count;
Assert.AreEqual(1, n);
}
}
[Test]
public void DeleteSelect()
{
using (new SoodaTransaction())
{
int n = Contact.Linq().Select(c => c.Name).ToList().Count;
Assert.AreEqual(7, n);
Contact.GetRef(5).MarkForDelete();
n = Contact.Linq().Select(c => c.Name).ToList().Count;
Assert.AreEqual(6, n);
}
}
[Test]
public void UpdateNullPrecommit()
{
using (new SoodaTransaction())
{
Contact.Mary.Type = null; // precommit "Customer"
int n = Contact.Linq(SoodaSnapshotOptions.NoCache).Count(c => c.Type == ContactType.Customer);
Assert.AreEqual(5, n);
}
}
[Test]
public void NewPrecommitCommit()
{
using (SoodaTransaction tran = new SoodaTransaction())
{
int n = Contact.Linq().Count();
Assert.AreEqual(7, n);
new Contact();
n = Contact.Linq().Count();
Assert.AreEqual(8, n);
Assert.Throws(typeof(SoodaException), () => tran.Commit());
}
}
[Test]
public void UpdateNullPrecommitCommit()
{
using (SoodaTransaction tran = new SoodaTransaction())
{
Contact.GetRef(50).Type = null; // precommit "Customer"
int n = Contact.Linq(SoodaSnapshotOptions.NoCache).Count(c => c.Type == ContactType.Customer);
Assert.AreEqual(4, n);
Assert.Throws(typeof(SoodaException), () => tran.Commit());
}
}
}
}
#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.
/*============================================================
**
**
**
**
**
** EnumBuilder is a helper class to build Enum ( a special type ).
**
**
===========================================================*/
namespace System.Reflection.Emit
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.InteropServices;
using CultureInfo = System.Globalization.CultureInfo;
sealed public class EnumBuilder : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
// Define literal for enum
public FieldBuilder DefineLiteral(String literalName, Object literalValue)
{
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: EnumBuilder.DefineLiteral( " + literalName + " )");
// Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
FieldBuilder fieldBuilder = m_typeBuilder.DefineField(
literalName,
this,
FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
fieldBuilder.SetConstant(literalValue);
return fieldBuilder;
}
public TypeInfo CreateTypeInfo()
{
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: EnumBuilder.CreateType() ");
return m_typeBuilder.CreateTypeInfo();
}
// CreateType cause EnumBuilder to be baked.
public Type CreateType()
{
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: EnumBuilder.CreateType() ");
return m_typeBuilder.CreateType();
}
// Get the internal metadata token for this class.
public TypeToken TypeToken
{
get { return m_typeBuilder.TypeToken; }
}
// return the underlying field for the enum
public FieldBuilder UnderlyingField
{
get { return m_underlyingField; }
}
public override String Name
{
get { return m_typeBuilder.Name; }
}
/****************************************************
*
* abstract methods defined in the base class
*
*/
public override Guid GUID
{
get
{
return m_typeBuilder.GUID;
}
}
public override Object InvokeMember(
String name,
BindingFlags invokeAttr,
Binder binder,
Object target,
Object[] args,
ParameterModifier[] modifiers,
CultureInfo culture,
String[] namedParameters)
{
return m_typeBuilder.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
}
public override Module Module
{
get { return m_typeBuilder.Module; }
}
public override Assembly Assembly
{
get { return m_typeBuilder.Assembly; }
}
public override RuntimeTypeHandle TypeHandle
{
get { return m_typeBuilder.TypeHandle; }
}
public override String FullName
{
get { return m_typeBuilder.FullName; }
}
public override String AssemblyQualifiedName
{
get
{
return m_typeBuilder.AssemblyQualifiedName;
}
}
public override String Namespace
{
get { return m_typeBuilder.Namespace; }
}
public override Type BaseType
{
get { return m_typeBuilder.BaseType; }
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
return m_typeBuilder.GetConstructor(bindingAttr, binder, callConvention,
types, modifiers);
}
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
return m_typeBuilder.GetConstructors(bindingAttr);
}
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (types == null)
return m_typeBuilder.GetMethod(name, bindingAttr);
else
return m_typeBuilder.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
}
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
return m_typeBuilder.GetMethods(bindingAttr);
}
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
return m_typeBuilder.GetField(name, bindingAttr);
}
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
return m_typeBuilder.GetFields(bindingAttr);
}
public override Type GetInterface(String name, bool ignoreCase)
{
return m_typeBuilder.GetInterface(name, ignoreCase);
}
public override Type[] GetInterfaces()
{
return m_typeBuilder.GetInterfaces();
}
public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
{
return m_typeBuilder.GetEvent(name, bindingAttr);
}
public override EventInfo[] GetEvents()
{
return m_typeBuilder.GetEvents();
}
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
return m_typeBuilder.GetProperties(bindingAttr);
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
return m_typeBuilder.GetNestedTypes(bindingAttr);
}
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
return m_typeBuilder.GetNestedType(name, bindingAttr);
}
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
return m_typeBuilder.GetMember(name, type, bindingAttr);
}
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
return m_typeBuilder.GetMembers(bindingAttr);
}
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
return m_typeBuilder.GetInterfaceMap(interfaceType);
}
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
return m_typeBuilder.GetEvents(bindingAttr);
}
protected override TypeAttributes GetAttributeFlagsImpl()
{
return m_typeBuilder.Attributes;
}
public override bool IsSZArray => false;
protected override bool IsArrayImpl()
{
return false;
}
protected override bool IsPrimitiveImpl()
{
return false;
}
protected override bool IsValueTypeImpl()
{
return true;
}
protected override bool IsByRefImpl()
{
return false;
}
protected override bool IsPointerImpl()
{
return false;
}
protected override bool IsCOMObjectImpl()
{
return false;
}
public override bool IsConstructedGenericType
{
get
{
return false;
}
}
public override Type GetElementType()
{
return m_typeBuilder.GetElementType();
}
protected override bool HasElementTypeImpl()
{
return m_typeBuilder.HasElementType;
}
// About the SuppressMessageAttribute here - CCRewrite wants us to repeat the base type's precondition
// here, but it will always be true. Rather than adding dead code, I'll silence the warning.
[SuppressMessage("Microsoft.Contracts", "CC1055")]
// Legacy: JScript needs it.
public override Type GetEnumUnderlyingType()
{
return m_underlyingField.FieldType;
}
public override Type UnderlyingSystemType
{
get
{
return GetEnumUnderlyingType();
}
}
//ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return m_typeBuilder.GetCustomAttributes(inherit);
}
// Return a custom attribute identified by Type
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return m_typeBuilder.GetCustomAttributes(attributeType, inherit);
}
// Use this function if client decides to form the custom attribute blob themselves
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_typeBuilder.SetCustomAttribute(con, binaryAttribute);
}
// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_typeBuilder.SetCustomAttribute(customBuilder);
}
// Return the class that declared this Field.
public override Type DeclaringType
{
get { return m_typeBuilder.DeclaringType; }
}
// Return the class that was used to obtain this field.
public override Type ReflectedType
{
get { return m_typeBuilder.ReflectedType; }
}
// Returns true if one or more instance of attributeType is defined on this member.
public override bool IsDefined(Type attributeType, bool inherit)
{
return m_typeBuilder.IsDefined(attributeType, inherit);
}
/*****************************************************
*
* private/protected functions
*
*/
//*******************************
// Make a private constructor so these cannot be constructed externally.
//*******************************
private EnumBuilder() { }
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*", this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
string szrank = "";
if (rank == 1)
{
szrank = "*";
}
else
{
for (int i = 1; i < rank; i++)
szrank += ",";
}
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
return SymbolType.FormCompoundType(s, this, 0);
}
// Constructs a EnumBuilder.
// EnumBuilder can only be a top-level (not nested) enum type.
internal EnumBuilder(
String name, // name of type
Type underlyingType, // underlying type for an Enum
TypeAttributes visibility, // any bits on TypeAttributes.VisibilityMask)
ModuleBuilder module) // module containing this type
{
// Client should not set any bits other than the visibility bits.
if ((visibility & ~TypeAttributes.VisibilityMask) != 0)
throw new ArgumentException(SR.Argument_ShouldOnlySetVisibilityFlags, nameof(name));
m_typeBuilder = new TypeBuilder(name, visibility | TypeAttributes.Sealed, typeof(System.Enum), null, module, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize, null);
// Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
m_underlyingField = m_typeBuilder.DefineField("value__", underlyingType, FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
}
/*****************************************************
*
* private data members
*
*/
internal TypeBuilder m_typeBuilder;
private FieldBuilder m_underlyingField;
}
}
| |
/*
* 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 OpenSim 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 Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Avatar.Combat.CombatModule
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CombatModule")]
public class CombatModule : ISharedRegionModule
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Region UUIDS indexed by AgentID
/// </summary>
//private Dictionary<UUID, UUID> m_rootAgents = new Dictionary<UUID, UUID>();
/// <summary>
/// Scenes by Region Handle
/// </summary>
private Dictionary<ulong, Scene> m_scenel = new Dictionary<ulong, Scene>();
/// <summary>
/// Startup
/// </summary>
/// <param name="scene"></param>
/// <param name="config"></param>
public void Initialise(IConfigSource config)
{
}
public void AddRegion(Scene scene)
{
lock (m_scenel)
{
if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle))
{
m_scenel[scene.RegionInfo.RegionHandle] = scene;
}
else
{
m_scenel.Add(scene.RegionInfo.RegionHandle, scene);
}
}
scene.EventManager.OnAvatarKilled += KillAvatar;
scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
}
public void RemoveRegion(Scene scene)
{
if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle))
m_scenel.Remove(scene.RegionInfo.RegionHandle);
scene.EventManager.OnAvatarKilled -= KillAvatar;
scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
}
public void RegionLoaded(Scene scene)
{
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "CombatModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
private void KillAvatar(uint killerObjectLocalID, ScenePresence deadAvatar)
{
string deadAvatarMessage;
ScenePresence killingAvatar = null;
// string killingAvatarMessage;
// check to see if it is an NPC and just remove it
INPCModule NPCmodule = deadAvatar.Scene.RequestModuleInterface<INPCModule>();
if (NPCmodule != null && NPCmodule.DeleteNPC(deadAvatar.UUID, deadAvatar.Scene))
{
return;
}
if (killerObjectLocalID == 0)
deadAvatarMessage = "You committed suicide!";
else
{
// Try to get the avatar responsible for the killing
killingAvatar = deadAvatar.Scene.GetScenePresence(killerObjectLocalID);
if (killingAvatar == null)
{
// Try to get the object which was responsible for the killing
SceneObjectPart part = deadAvatar.Scene.GetSceneObjectPart(killerObjectLocalID);
if (part == null)
{
// Cause of death: Unknown
deadAvatarMessage = "You died!";
}
else
{
// Try to find the avatar wielding the killing object
killingAvatar = deadAvatar.Scene.GetScenePresence(part.OwnerID);
if (killingAvatar == null)
{
IUserManagement userManager = deadAvatar.Scene.RequestModuleInterface<IUserManagement>();
string userName = "Unkown User";
if (userManager != null)
userName = userManager.GetUserName(part.OwnerID);
deadAvatarMessage = String.Format("You impaled yourself on {0} owned by {1}!", part.Name, userName);
}
else
{
// killingAvatarMessage = String.Format("You fragged {0}!", deadAvatar.Name);
deadAvatarMessage = String.Format("You got killed by {0}!", killingAvatar.Name);
}
}
}
else
{
// killingAvatarMessage = String.Format("You fragged {0}!", deadAvatar.Name);
deadAvatarMessage = String.Format("You got killed by {0}!", killingAvatar.Name);
}
}
try
{
deadAvatar.ControllingClient.SendAgentAlertMessage(deadAvatarMessage, true);
if (killingAvatar != null)
killingAvatar.ControllingClient.SendAlertMessage("You fragged " + deadAvatar.Firstname + " " + deadAvatar.Lastname);
}
catch (InvalidOperationException)
{ }
deadAvatar.setHealthWithUpdate(100.0f);
deadAvatar.Scene.TeleportClientHome(deadAvatar.UUID, deadAvatar.ControllingClient);
}
private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
{
try
{
ILandObject obj = avatar.Scene.LandChannel.GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y);
if (obj == null)
return;
if ((obj.LandData.Flags & (uint)ParcelFlags.AllowDamage) != 0
|| avatar.Scene.RegionInfo.RegionSettings.AllowDamage)
{
avatar.Invulnerable = false;
}
else
{
avatar.Invulnerable = true;
if (avatar.Health < 100.0f)
{
avatar.setHealthWithUpdate(100.0f);
}
}
}
catch (Exception)
{
}
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
#if ENABLE_WINRT
using Internal.Runtime.Augments;
#endif
namespace System.Globalization
{
internal partial class CultureData
{
private const uint LOCALE_NOUSEROVERRIDE = 0x80000000;
private const uint LOCALE_RETURN_NUMBER = 0x20000000;
private const uint LOCALE_SISO3166CTRYNAME = 0x0000005A;
private const uint TIME_NOSECONDS = 0x00000002;
/// <summary>
/// Check with the OS to see if this is a valid culture.
/// If so we populate a limited number of fields. If its not valid we return false.
///
/// The fields we populate:
///
/// sWindowsName -- The name that windows thinks this culture is, ie:
/// en-US if you pass in en-US
/// de-DE_phoneb if you pass in de-DE_phoneb
/// fj-FJ if you pass in fj (neutral, on a pre-Windows 7 machine)
/// fj if you pass in fj (neutral, post-Windows 7 machine)
///
/// sRealName -- The name you used to construct the culture, in pretty form
/// en-US if you pass in EN-us
/// en if you pass in en
/// de-DE_phoneb if you pass in de-DE_phoneb
///
/// sSpecificCulture -- The specific culture for this culture
/// en-US for en-US
/// en-US for en
/// de-DE_phoneb for alt sort
/// fj-FJ for fj (neutral)
///
/// sName -- The IETF name of this culture (ie: no sort info, could be neutral)
/// en-US if you pass in en-US
/// en if you pass in en
/// de-DE if you pass in de-DE_phoneb
///
/// bNeutral -- TRUE if it is a neutral locale
///
/// For a neutral we just populate the neutral name, but we leave the windows name pointing to the
/// windows locale that's going to provide data for us.
/// </summary>
private unsafe bool InitCultureData()
{
const int LOCALE_NAME_MAX_LENGTH = 85;
const uint LOCALE_ILANGUAGE = 0x00000001;
const uint LOCALE_INEUTRAL = 0x00000071;
const uint LOCALE_SNAME = 0x0000005c;
int result;
string realNameBuffer = _sRealName;
char* pBuffer = stackalloc char[LOCALE_NAME_MAX_LENGTH];
result = Interop.mincore.GetLocaleInfoEx(realNameBuffer, LOCALE_SNAME, pBuffer, LOCALE_NAME_MAX_LENGTH);
// Did it fail?
if (result == 0)
{
return false;
}
// It worked, note that the name is the locale name, so use that (even for neutrals)
// We need to clean up our "real" name, which should look like the windows name right now
// so overwrite the input with the cleaned up name
_sRealName = new String(pBuffer, 0, result - 1);
realNameBuffer = _sRealName;
// Check for neutrality, don't expect to fail
// (buffer has our name in it, so we don't have to do the gc. stuff)
result = Interop.mincore.GetLocaleInfoEx(realNameBuffer, LOCALE_INEUTRAL | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char));
if (result == 0)
{
return false;
}
// Remember our neutrality
_bNeutral = *((uint*)pBuffer) != 0;
// Note: Parents will be set dynamically
// Start by assuming the windows name'll be the same as the specific name since windows knows
// about specifics on all versions. Only for downlevel Neutral locales does this have to change.
_sWindowsName = realNameBuffer;
// Neutrals and non-neutrals are slightly different
if (_bNeutral)
{
// Neutral Locale
// IETF name looks like neutral name
_sName = realNameBuffer;
// Specific locale name is whatever ResolveLocaleName (win7+) returns.
// (Buffer has our name in it, and we can recycle that because windows resolves it before writing to the buffer)
result = Interop.mincore.ResolveLocaleName(realNameBuffer, pBuffer, LOCALE_NAME_MAX_LENGTH);
// 0 is failure, 1 is invariant (""), which we expect
if (result < 1)
{
return false;
}
// We found a locale name, so use it.
// In vista this should look like a sort name (de-DE_phoneb) or a specific culture (en-US) and be in the "pretty" form
_sSpecificCulture = new String(pBuffer, 0, result - 1);
}
else
{
// Specific Locale
// Specific culture's the same as the locale name since we know its not neutral
// On mac we'll use this as well, even for neutrals. There's no obvious specific
// culture to use and this isn't exposed, but behaviorally this is correct on mac.
// Note that specifics include the sort name (de-DE_phoneb)
_sSpecificCulture = realNameBuffer;
_sName = realNameBuffer;
// We need the IETF name (sname)
// If we aren't an alt sort locale then this is the same as the windows name.
// If we are an alt sort locale then this is the same as the part before the _ in the windows name
// This is for like de-DE_phoneb and es-ES_tradnl that hsouldn't have the _ part
result = Interop.mincore.GetLocaleInfoEx(realNameBuffer, LOCALE_ILANGUAGE | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char));
if (result == 0)
{
return false;
}
_iLanguage = *((int*)pBuffer);
if (!IsCustomCultureId(_iLanguage))
{
// not custom locale
int index = realNameBuffer.IndexOf('_');
if (index > 0 && index < realNameBuffer.Length)
{
_sName = realNameBuffer.Substring(0, index);
}
}
}
// It succeeded.
return true;
}
private string GetLocaleInfo(LocaleStringData type)
{
Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already");
return GetLocaleInfo(_sWindowsName, type);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
private string GetLocaleInfo(string localeName, LocaleStringData type)
{
uint lctype = (uint)type;
return GetLocaleInfoFromLCType(localeName, lctype, UseUserOverride);
}
private int GetLocaleInfo(LocaleNumberData type)
{
uint lctype = (uint)type;
// Fix lctype if we don't want overrides
if (!UseUserOverride)
{
lctype |= LOCALE_NOUSEROVERRIDE;
}
// Ask OS for data, note that we presume it returns success, so we have to know that
// sWindowsName is valid before calling.
Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
int result = Interop.mincore.GetLocaleInfoExInt(_sWindowsName, lctype);
return result;
}
private int[] GetLocaleInfo(LocaleGroupingData type)
{
return ConvertWin32GroupString(GetLocaleInfoFromLCType(_sWindowsName, (uint)type, UseUserOverride));
}
private string GetTimeFormatString()
{
const uint LOCALE_STIMEFORMAT = 0x00001003;
return ReescapeWin32String(GetLocaleInfoFromLCType(_sWindowsName, LOCALE_STIMEFORMAT, UseUserOverride));
}
private int GetFirstDayOfWeek()
{
Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
int result = Interop.mincore.GetLocaleInfoExInt(_sWindowsName, LOCALE_IFIRSTDAYOFWEEK | (!UseUserOverride ? LOCALE_NOUSEROVERRIDE : 0));
// Win32 and .NET disagree on the numbering for days of the week, so we have to convert.
return ConvertFirstDayOfWeekMonToSun(result);
}
private String[] GetTimeFormats()
{
// Note that this gets overrides for us all the time
Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride));
return result;
}
private String[] GetShortTimeFormats()
{
// Note that this gets overrides for us all the time
Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, TIME_NOSECONDS, UseUserOverride));
return result;
}
// Enumerate all system cultures and then try to find out which culture has
// region name match the requested region name
private static CultureData GetCultureDataFromRegionName(String regionName)
{
Debug.Assert(regionName != null);
const uint LOCALE_SUPPLEMENTAL = 0x00000002;
const uint LOCALE_SPECIFICDATA = 0x00000020;
EnumLocaleData context = new EnumLocaleData();
context.cultureName = null;
context.regionName = regionName;
GCHandle contextHandle = GCHandle.Alloc(context);
try
{
IntPtr callback = AddrofIntrinsics.AddrOf<Interop.mincore.EnumLocalesProcEx>(EnumSystemLocalesProc);
Interop.mincore.EnumSystemLocalesEx(callback, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, (IntPtr)contextHandle, IntPtr.Zero);
}
finally
{
contextHandle.Free();
}
if (context.cultureName != null)
{
// we got a matched culture
return GetCultureData(context.cultureName, true);
}
return null;
}
private string GetLanguageDisplayName(string cultureName)
{
#if ENABLE_WINRT
return WinRTInterop.Callbacks.GetLanguageDisplayName(cultureName);
#else
// Usually the UI culture shouldn't be different than what we got from WinRT except
// if DefaultThreadCurrentUICulture was set
CultureInfo ci;
if (CultureInfo.DefaultThreadCurrentUICulture != null &&
((ci = GetUserDefaultCulture()) != null) &&
!CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name))
{
return SNATIVEDISPLAYNAME;
}
else
{
return GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
}
#endif // ENABLE_WINRT
}
private string GetRegionDisplayName(string isoCountryCode)
{
#if ENABLE_WINRT
return WinRTInterop.Callbacks.GetRegionDisplayName(isoCountryCode);
#else
// Usually the UI culture shouldn't be different than what we got from WinRT except
// if DefaultThreadCurrentUICulture was set
CultureInfo ci;
if (CultureInfo.DefaultThreadCurrentUICulture != null &&
((ci = GetUserDefaultCulture()) != null) &&
!CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name))
{
return SNATIVECOUNTRY;
}
else
{
return GetLocaleInfo(LocaleStringData.LocalizedCountryName);
}
#endif // ENABLE_WINRT
}
private static CultureInfo GetUserDefaultCulture()
{
#if ENABLE_WINRT
return (CultureInfo)WinRTInterop.Callbacks.GetUserDefaultCulture();
#else
return CultureInfo.GetUserDefaultCulture();
#endif // ENABLE_WINRT
}
// PAL methods end here.
private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride)
{
Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
// Fix lctype if we don't want overrides
if (!useUserOveride)
{
lctype |= LOCALE_NOUSEROVERRIDE;
}
// Ask OS for data
string result = Interop.mincore.GetLocaleInfoEx(localeName, lctype);
if (result == null)
{
// Failed, just use empty string
result = String.Empty;
}
return result;
}
////////////////////////////////////////////////////////////////////////////
//
// Reescape a Win32 style quote string as a NLS+ style quoted string
//
// This is also the escaping style used by custom culture data files
//
// NLS+ uses \ to escape the next character, whether in a quoted string or
// not, so we always have to change \ to \\.
//
// NLS+ uses \' to escape a quote inside a quoted string so we have to change
// '' to \' (if inside a quoted string)
//
// We don't build the stringbuilder unless we find something to change
////////////////////////////////////////////////////////////////////////////
internal static String ReescapeWin32String(String str)
{
// If we don't have data, then don't try anything
if (str == null)
return null;
StringBuilder result = null;
bool inQuote = false;
for (int i = 0; i < str.Length; i++)
{
// Look for quote
if (str[i] == '\'')
{
// Already in quote?
if (inQuote)
{
// See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote?
if (i + 1 < str.Length && str[i + 1] == '\'')
{
// Found another ', so we have ''. Need to add \' instead.
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append a \' and keep going (so we don't turn off quote mode)
result.Append("\\'");
i++;
continue;
}
// Turning off quote mode, fall through to add it
inQuote = false;
}
else
{
// Found beginning quote, fall through to add it
inQuote = true;
}
}
// Is there a single \ character?
else if (str[i] == '\\')
{
// Found a \, need to change it to \\
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append our \\ to the string & continue
result.Append("\\\\");
continue;
}
// If we have a builder we need to add our character
if (result != null)
result.Append(str[i]);
}
// Unchanged string? , just return input string
if (result == null)
return str;
// String changed, need to use the builder
return result.ToString();
}
internal static String[] ReescapeWin32Strings(String[] array)
{
if (array != null)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = ReescapeWin32String(array[i]);
}
}
return array;
}
// If we get a group from windows, then its in 3;0 format with the 0 backwards
// of how NLS+ uses it (ie: if the string has a 0, then the int[] shouldn't and vice versa)
// EXCEPT in the case where the list only contains 0 in which NLS and NLS+ have the same meaning.
private static int[] ConvertWin32GroupString(String win32Str)
{
// None of these cases make any sense
if (win32Str == null || win32Str.Length == 0)
{
return (new int[] { 3 });
}
if (win32Str[0] == '0')
{
return (new int[] { 0 });
}
// Since its in n;n;n;n;n format, we can always get the length quickly
int[] values;
if (win32Str[win32Str.Length - 1] == '0')
{
// Trailing 0 gets dropped. 1;0 -> 1
values = new int[(win32Str.Length / 2)];
}
else
{
// Need extra space for trailing zero 1 -> 1;0
values = new int[(win32Str.Length / 2) + 2];
values[values.Length - 1] = 0;
}
int i;
int j;
for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++)
{
// Note that this # shouldn't ever be zero, 'cause 0 is only at end
// But we'll test because its registry that could be anything
if (win32Str[i] < '1' || win32Str[i] > '9')
return new int[] { 3 };
values[j] = (int)(win32Str[i] - '0');
}
return (values);
}
private static int ConvertFirstDayOfWeekMonToSun(int iTemp)
{
// Convert Mon-Sun to Sun-Sat format
iTemp++;
if (iTemp > 6)
{
// Wrap Sunday and convert invalid data to Sunday
iTemp = 0;
}
return iTemp;
}
// Context for EnumCalendarInfoExEx callback.
private class EnumLocaleData
{
public string regionName;
public string cultureName;
}
// EnumSystemLocaleEx callback.
[NativeCallable(CallingConvention = CallingConvention.StdCall)]
private static unsafe Interop.BOOL EnumSystemLocalesProc(IntPtr lpLocaleString, uint flags, IntPtr contextHandle)
{
EnumLocaleData context = (EnumLocaleData)((GCHandle)contextHandle).Target;
try
{
string cultureName = new string((char*)lpLocaleString);
string regionName = Interop.mincore.GetLocaleInfoEx(cultureName, LOCALE_SISO3166CTRYNAME);
if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase))
{
context.cultureName = cultureName;
return Interop.BOOL.FALSE; // we found a match, then stop the enumeration
}
return Interop.BOOL.TRUE;
}
catch (Exception)
{
return Interop.BOOL.FALSE;
}
}
// Context for EnumTimeFormatsEx callback.
private class EnumData
{
public LowLevelList<string> strings;
}
// EnumTimeFormatsEx callback itself.
[NativeCallable(CallingConvention = CallingConvention.StdCall)]
private static unsafe Interop.BOOL EnumTimeCallback(IntPtr lpTimeFormatString, IntPtr lParam)
{
EnumData context = (EnumData)((GCHandle)lParam).Target;
try
{
context.strings.Add(new string((char*)lpTimeFormatString));
return Interop.BOOL.TRUE;
}
catch (Exception)
{
return Interop.BOOL.FALSE;
}
}
private static unsafe String[] nativeEnumTimeFormats(String localeName, uint dwFlags, bool useUserOverride)
{
const uint LOCALE_SSHORTTIME = 0x00000079;
const uint LOCALE_STIMEFORMAT = 0x00001003;
EnumData data = new EnumData();
data.strings = new LowLevelList<string>();
GCHandle dataHandle = GCHandle.Alloc(data);
try
{
// Now call the enumeration API. Work is done by our callback function
IntPtr callback = AddrofIntrinsics.AddrOf<Interop.mincore.EnumTimeFormatsProcEx>(EnumTimeCallback);
Interop.mincore.EnumTimeFormatsEx(callback, localeName, (uint)dwFlags, (IntPtr)dataHandle);
}
finally
{
dataHandle.Free();
}
if (data.strings.Count > 0)
{
// Now we need to allocate our stringarray and populate it
string[] results = data.strings.ToArray();
if (!useUserOverride && data.strings.Count > 1)
{
// Since there is no "NoUserOverride" aware EnumTimeFormatsEx, we always get an override
// The override is the first entry if it is overriden.
// We can check if we have overrides by checking the GetLocaleInfo with no override
// If we do have an override, we don't know if it is a user defined override or if the
// user has just selected one of the predefined formats so we can't just remove it
// but we can move it down.
uint lcType = (dwFlags == TIME_NOSECONDS) ? LOCALE_SSHORTTIME : LOCALE_STIMEFORMAT;
string timeFormatNoUserOverride = GetLocaleInfoFromLCType(localeName, lcType, useUserOverride);
if (timeFormatNoUserOverride != "")
{
string firstTimeFormat = results[0];
if (timeFormatNoUserOverride != firstTimeFormat)
{
results[0] = results[1];
results[1] = firstTimeFormat;
}
}
}
return results;
}
return null;
}
private int LocaleNameToLCID(string cultureName)
{
return GetLocaleInfo(LocaleNumberData.LanguageId);
}
private static string LCIDToLocaleName(int culture)
{
throw new NotImplementedException();
}
private int GetAnsiCodePage(string cultureName)
{
return GetLocaleInfo(LocaleNumberData.AnsiCodePage);
}
private int GetOemCodePage(string cultureName)
{
return GetLocaleInfo(LocaleNumberData.OemCodePage);
}
private int GetMacCodePage(string cultureName)
{
return GetLocaleInfo(LocaleNumberData.MacCodePage);
}
private int GetEbcdicCodePage(string cultureName)
{
return GetLocaleInfo(LocaleNumberData.EbcdicCodePage);
}
private int GetGeoId(string cultureName)
{
return GetLocaleInfo(LocaleNumberData.GeoId);
}
private int GetDigitSubstitution(string cultureName)
{
return GetLocaleInfo(LocaleNumberData.DigitSubstitution);
}
private string GetThreeLetterWindowsLanguageName(string cultureName)
{
return GetLocaleInfo(cultureName, LocaleStringData.AbbreviatedWindowsLanguageName);
}
private static CultureInfo[] EnumCultures(CultureTypes types)
{
throw new NotImplementedException();
}
private string GetConsoleFallbackName(string cultureName)
{
return GetLocaleInfo(cultureName, LocaleStringData.ConsoleFallbackName);
}
internal bool IsFramework
{
get { throw new NotImplementedException(); }
}
internal bool IsWin32Installed
{
get { throw new NotImplementedException(); }
}
internal bool IsReplacementCulture
{
get { throw new NotImplementedException(); }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace AIEdit
{
public abstract class TeamTypeOption
{
protected string tag, name;
public string Tag { get { return tag; } }
public string Name { get { return name; } }
public TeamTypeOption(string tag, string name)
{
this.tag = tag;
this.name = name;
}
public abstract IList List { get; }
public abstract TeamTypeEntry DefaultValue { get; }
public abstract int SortOrder { get; }
public abstract TeamTypeEntry Parse(OrderedDictionary section);
public abstract void Write(StreamWriter stream, object value);
}
public class TeamTypeOptionBool : TeamTypeOptionStringList
{
private static List<AITypeListEntry> bools = new List<AITypeListEntry>()
{
new AITypeListEntry(0, "no"),
new AITypeListEntry(1, "yes"),
};
public override int SortOrder { get { return 3; } }
public TeamTypeOptionBool(string tag, string name) : base(tag, name, bools)
{
}
}
public class TeamTypeOptionNumber : TeamTypeOption
{
public TeamTypeOptionNumber(string tag, string name) : base(tag, name)
{
}
public override IList List { get { return null; } }
public override TeamTypeEntry DefaultValue { get { return new TeamTypeEntry(this, (object)0); } }
public override int SortOrder { get { return 2; } }
public override TeamTypeEntry Parse(OrderedDictionary section)
{
if (!section.Contains(tag)) return DefaultValue;
return new TeamTypeEntry(this, section.GetInt(tag));
}
public override void Write(StreamWriter stream, object value)
{
stream.WriteLine(tag + "=" + ((int)value));
}
}
public class TeamTypeOptionList : TeamTypeOption
{
protected IList dataList;
public TeamTypeOptionList(string tag, string name, IList dataList)
: base(tag, name)
{
this.dataList = dataList;
}
public override IList List { get { return dataList; } }
public override TeamTypeEntry DefaultValue { get { return new TeamTypeEntry(this, dataList[0]); } }
public override int SortOrder { get { return 1; } }
public override TeamTypeEntry Parse(OrderedDictionary section)
{
if (!section.Contains(tag)) return DefaultValue;
int val = section.GetInt(tag);
foreach (AITypeListEntry listitem in dataList)
{
if (listitem.Index == val) return new TeamTypeEntry(this, listitem);
}
return new TeamTypeEntry(this, dataList[0]);
}
public override void Write(StreamWriter stream, object value)
{
int v = (value as AITypeListEntry).Index;
stream.WriteLine(tag + "=" + v);
}
}
public class TeamTypeOptionStringList : TeamTypeOptionList
{
public TeamTypeOptionStringList(string tag, string name, IList dataList) : base(tag, name, dataList)
{
}
public override int SortOrder { get { return 1; } }
public override TeamTypeEntry Parse(OrderedDictionary section)
{
if (!section.Contains(tag)) return DefaultValue;
string val = section.GetString(tag);
foreach (AITypeListEntry listitem in dataList)
{
if (listitem.Name == val) return new TeamTypeEntry(this, listitem);
}
return new TeamTypeEntry(this, dataList[0]);
}
public override void Write(StreamWriter stream, object value)
{
string v = (value as AITypeListEntry).Name;
stream.WriteLine(tag + "=" + v);
}
}
public class TeamTypeOptionAIObject : TeamTypeOptionList
{
public TeamTypeOptionAIObject(string tag, string name, IList dataList) : base(tag, name, dataList)
{
}
public override int SortOrder { get { return 0; } }
public override TeamTypeEntry Parse(OrderedDictionary section)
{
if (!section.Contains(tag)) return DefaultValue;
string id = section.GetString(tag);
foreach(IAIObject aiobj in dataList)
{
if (aiobj.ID == id) return new TeamTypeEntry(this, aiobj);
}
return new TeamTypeEntry(this, dataList[0]);
}
public override void Write(StreamWriter stream, object value)
{
string v = (value as IAIObject).ID;
stream.WriteLine(tag + "=" + v);
}
}
public class TeamTypeEntry
{
private TeamTypeOption option;
private object value;
public string Name { get { return option.Name; } }
public TeamTypeOption Option { get { return option; } }
public int SortOrder { get { return option.SortOrder; } }
public object Value
{
get
{
return value;
}
set
{
if (this.value is IAIObject) (this.value as IAIObject).DecUses();
if (value is IAIObject) (value as IAIObject).IncUses();
this.value = value;
}
}
public void Reset()
{
if (this.value is IAIObject) (this.value as IAIObject).DecUses();
this.value = null;
}
public TeamTypeEntry(TeamTypeOption option, object value)
{
this.option = option;
this.Value = value;
}
public TeamTypeEntry(TeamTypeEntry other)
{
this.option = other.option;
this.Value = other.Value;
}
public void Write(StreamWriter stream)
{
option.Write(stream, value);
}
}
public class TeamType : IAIObject, IEnumerable<TeamTypeEntry>, IParamListEntry
{
private string name, id;
private List<TeamTypeEntry> entries;
private int uses;
public string IsBaseDefense { get { return (entries.First(x => x.Option.Tag == "IsBaseDefense").Value as AITypeListEntry).Index == 0 ? "N" : "Y"; } }
public int Max { get { return (int)entries.First(x => x.Option.Tag == "Max").Value; } }
public int Priority { get { return (int)entries.First(x => x.Option.Tag == "Priority").Value; } }
public string House { get { return entries.First(x => x.Option.Tag == "House").Value.ToString(); } }
public uint ParamListIndex { get { return 0; } }
public string Name { get { return name; } set { name = value.Trim(); } }
public string ID { get { return id; } }
public int Uses { get { return uses; } }
public void IncUses() { uses++; }
public void DecUses() { uses--; }
public IEnumerator<TeamTypeEntry> GetEnumerator()
{
return entries.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool HasObject(object obj)
{
return entries.FirstOrDefault(e => e.Value == obj) != null;
}
public TeamType(string id, string name, List<TeamTypeEntry> entries)
{
this.id = id;
this.Name = name;
this.entries = (entries != null) ? entries : new List<TeamTypeEntry>();
}
public IAIObject Copy(string newid, string newname)
{
List<TeamTypeEntry> newentries = new List<TeamTypeEntry>();
foreach (TeamTypeEntry e in this.entries) newentries.Add(new TeamTypeEntry(e));
return new TeamType(newid, newname, newentries);
}
public override string ToString()
{
return name;
}
public void Reset()
{
foreach(TeamTypeEntry e in this.entries) e.Reset();
entries.Clear();
}
public void Write(StreamWriter stream)
{
stream.WriteLine("[" + id + "]");
stream.WriteLine("Name=" + name);
foreach (TeamTypeEntry entry in entries) entry.Write(stream);
stream.WriteLine();
}
public static TeamType Parse(string id, OrderedDictionary section, List<TeamTypeOption> options)
{
List<TeamTypeEntry> entries = new List<TeamTypeEntry>();
string name = section.GetString("Name");
if (name == null) name = id;
try
{
foreach(TeamTypeOption option in options)
{
entries.Add(option.Parse(section));
}
}
catch (Exception )
{
string msg = "Error occured at TeamType: [" + id + "]" + "\nPlease verify its format. Application will now close.";
MessageBox.Show(msg, "Parse Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
Application.Exit();
}
return new TeamType(id, name, entries);
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A sea (for example, the Caspian sea).
/// </summary>
public class SeaBodyOfWater_Core : TypeCore, IBodyOfWater
{
public SeaBodyOfWater_Core()
{
this._TypeId = 236;
this._Id = "SeaBodyOfWater";
this._Schema_Org_Url = "http://schema.org/SeaBodyOfWater";
string label = "";
GetLabel(out label, "SeaBodyOfWater", typeof(SeaBodyOfWater_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,146,40};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{40};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// 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 RoundToNearestIntegerSingle()
{
var test = new SimpleUnaryOpTest__RoundToNearestIntegerSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 SimpleUnaryOpTest__RoundToNearestIntegerSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__RoundToNearestIntegerSingle testClass)
{
var result = Sse41.RoundToNearestInteger(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNearestIntegerSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = Sse41.RoundToNearestInteger(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar1;
private Vector128<Single> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__RoundToNearestIntegerSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleUnaryOpTest__RoundToNearestIntegerSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.RoundToNearestInteger(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.RoundToNearestInteger(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.RoundToNearestInteger(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestInteger), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestInteger), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestInteger), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.RoundToNearestInteger(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
{
var result = Sse41.RoundToNearestInteger(
Sse.LoadVector128((Single*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var result = Sse41.RoundToNearestInteger(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var result = Sse41.RoundToNearestInteger(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var result = Sse41.RoundToNearestInteger(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__RoundToNearestIntegerSingle();
var result = Sse41.RoundToNearestInteger(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__RoundToNearestIntegerSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
{
var result = Sse41.RoundToNearestInteger(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.RoundToNearestInteger(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = Sse41.RoundToNearestInteger(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.RoundToNearestInteger(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.RoundToNearestInteger(
Sse.LoadVector128((Single*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
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(Vector128<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[0], MidpointRounding.AwayFromZero)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[i], MidpointRounding.AwayFromZero)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToNearestInteger)}<Single>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text.RegularExpressions;
using System.Reflection;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Targets
{
/// <summary>
///
/// </summary>
[Target("sharpdev")]
public class SharpDevelopTarget : ITarget
{
#region Fields
private Kernel m_Kernel;
#endregion
#region Private Methods
private static string PrependPath(string path)
{
string tmpPath = Helper.NormalizePath(path, '/');
Regex regex = new Regex(@"(\w):/(\w+)");
Match match = regex.Match(tmpPath);
if(match.Success || tmpPath[0] == '.' || tmpPath[0] == '/')
{
tmpPath = Helper.NormalizePath(tmpPath);
}
else
{
tmpPath = Helper.NormalizePath("./" + tmpPath);
}
return tmpPath;
}
private static string BuildReference(SolutionNode solution, ReferenceNode refr)
{
string ret = "<Reference type=\"";
if(solution.ProjectsTable.ContainsKey(refr.Name))
{
ret += "Project\" refto=\"" + refr.Name;
ret += "\" localcopy=\"" + refr.LocalCopy.ToString() + "\" />";
}
else
{
ProjectNode project = (ProjectNode)refr.Parent;
string fileRef = FindFileReference(refr.Name, project);
if(refr.Path != null || fileRef != null)
{
ret += "Assembly\" refto=\"";
string finalPath = (refr.Path != null) ? Helper.MakeFilePath(refr.Path, refr.Name, "dll") : fileRef;
ret += finalPath;
ret += "\" localcopy=\"" + refr.LocalCopy.ToString() + "\" />";
return ret;
}
ret += "Gac\" refto=\"";
try
{
//Assembly assem = Assembly.Load(refr.Name);
ret += refr.Name;// assem.FullName;
}
catch (System.NullReferenceException e)
{
e.ToString();
ret += refr.Name;
}
ret += "\" localcopy=\"" + refr.LocalCopy.ToString() + "\" />";
}
return ret;
}
private static string FindFileReference(string refName, ProjectNode project)
{
foreach(ReferencePathNode refPath in project.ReferencePaths)
{
string fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll");
if(File.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
/// <summary>
/// Gets the XML doc file.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="conf">The conf.</param>
/// <returns></returns>
public static string GenerateXmlDocFile(ProjectNode project, ConfigurationNode conf)
{
if( conf == null )
{
throw new ArgumentNullException("conf");
}
if( project == null )
{
throw new ArgumentNullException("project");
}
string docFile = (string)conf.Options["XmlDocFile"];
if(docFile != null && docFile.Length == 0)//default to assembly name if not specified
{
return "False";
}
return "True";
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
string csComp = "Csc";
string netRuntime = "MsNet";
if(project.Runtime == ClrRuntime.Mono)
{
csComp = "Mcs";
netRuntime = "Mono";
}
string projFile = Helper.MakeFilePath(project.FullPath, project.Name, "prjx");
StreamWriter ss = new StreamWriter(projFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projFile));
using(ss)
{
ss.WriteLine(
"<Project name=\"{0}\" standardNamespace=\"{1}\" description=\"\" newfilesearch=\"None\" enableviewstate=\"True\" version=\"1.1\" projecttype=\"C#\">",
project.Name,
project.RootNamespace
);
ss.WriteLine(" <Contents>");
foreach(string file in project.Files)
{
string buildAction = "Compile";
switch(project.Files.GetBuildAction(file))
{
case BuildAction.None:
buildAction = "Nothing";
break;
case BuildAction.Content:
buildAction = "Exclude";
break;
case BuildAction.EmbeddedResource:
buildAction = "EmbedAsResource";
break;
default:
buildAction = "Compile";
break;
}
// Sort of a hack, we try and resolve the path and make it relative, if we can.
string filePath = PrependPath(file);
ss.WriteLine(" <File name=\"{0}\" subtype=\"Code\" buildaction=\"{1}\" dependson=\"\" data=\"\" />", filePath, buildAction);
}
ss.WriteLine(" </Contents>");
ss.WriteLine(" <References>");
foreach(ReferenceNode refr in project.References)
{
ss.WriteLine(" {0}", BuildReference(solution, refr));
}
ss.WriteLine(" </References>");
ss.Write(" <DeploymentInformation");
ss.Write(" target=\"\"");
ss.Write(" script=\"\"");
ss.Write(" strategy=\"File\"");
ss.WriteLine(" />");
int count = 0;
ss.WriteLine(" <Configurations active=\"{0}\">", solution.ActiveConfig);
foreach(ConfigurationNode conf in project.Configurations)
{
ss.Write(" <Configuration");
ss.Write(" runwithwarnings=\"True\"");
ss.Write(" name=\"{0}\"", conf.Name);
ss.WriteLine(">");
ss.Write(" <CodeGeneration");
ss.Write(" runtime=\"{0}\"", netRuntime);
ss.Write(" compiler=\"{0}\"", csComp);
ss.Write(" compilerversion=\"\"");
ss.Write(" warninglevel=\"{0}\"", conf.Options["WarningLevel"]);
ss.Write(" nowarn=\"{0}\"", conf.Options["SuppressWarnings"]);
ss.Write(" includedebuginformation=\"{0}\"", conf.Options["DebugInformation"]);
ss.Write(" optimize=\"{0}\"", conf.Options["OptimizeCode"]);
ss.Write(" unsafecodeallowed=\"{0}\"", conf.Options["AllowUnsafe"]);
ss.Write(" generateoverflowchecks=\"{0}\"", conf.Options["CheckUnderflowOverflow"]);
ss.Write(" mainclass=\"{0}\"", project.StartupObject);
ss.Write(" target=\"{0}\"", project.Type);
ss.Write(" definesymbols=\"{0}\"", conf.Options["CompilerDefines"]);
ss.Write(" generatexmldocumentation=\"{0}\"", GenerateXmlDocFile(project, conf));
ss.Write(" win32Icon=\"{0}\"", Helper.NormalizePath(".\\" + project.AppIcon));
ss.Write(" noconfig=\"{0}\"", "False");
ss.Write(" nostdlib=\"{0}\"", conf.Options["NoStdLib"]);
ss.WriteLine(" />");
ss.Write(" <Execution");
ss.Write(" commandlineparameters=\"\"");
ss.Write(" consolepause=\"True\"");
ss.WriteLine(" />");
ss.Write(" <Output");
ss.Write(" directory=\".\\{0}\"", Helper.NormalizePath(conf.Options["OutputPath"].ToString()));
ss.Write(" assembly=\"{0}\"", project.AssemblyName);
ss.Write(" executeScript=\"{0}\"", conf.Options["RunScript"]);
if (conf.Options["PreBuildEvent"] != null && conf.Options["PreBuildEvent"].ToString().Length != 0)
{
ss.Write(" executeBeforeBuild=\"{0}\"", Helper.NormalizePath(conf.Options["PreBuildEvent"].ToString()));
}
else
{
ss.Write(" executeBeforeBuild=\"{0}\"", conf.Options["PreBuildEvent"]);
}
if (conf.Options["PostBuildEvent"] != null && conf.Options["PostBuildEvent"].ToString().Length != 0)
{
ss.Write(" executeAfterBuild=\"{0}\"", Helper.NormalizePath(conf.Options["PostBuildEvent"].ToString()));
}
else
{
ss.Write(" executeAfterBuild=\"{0}\"", conf.Options["PostBuildEvent"]);
}
ss.Write(" executeBeforeBuildArguments=\"{0}\"", conf.Options["PreBuildEventArgs"]);
ss.Write(" executeAfterBuildArguments=\"{0}\"", conf.Options["PreBuildEventArgs"]);
ss.WriteLine(" />");
ss.WriteLine(" </Configuration>");
count++;
}
ss.WriteLine(" </Configurations>");
ss.WriteLine("</Project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void WriteCombine(SolutionNode solution)
{
m_Kernel.Log.Write("Creating SharpDevelop combine and project files");
foreach(ProjectNode project in solution.Projects)
{
if(m_Kernel.AllowProject(project.FilterGroups))
{
m_Kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
}
m_Kernel.Log.Write("");
string combFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "cmbx");
StreamWriter ss = new StreamWriter(combFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(combFile));
using(ss)
{
ss.WriteLine("<Combine fileversion=\"1.0\" name=\"{0}\" description=\"\">", solution.Name);
int count = 0;
foreach(ProjectNode project in solution.Projects)
{
if(count == 0)
ss.WriteLine(" <StartMode startupentry=\"{0}\" single=\"True\">", project.Name);
ss.WriteLine(" <Execute entry=\"{0}\" type=\"None\" />", project.Name);
count++;
}
ss.WriteLine(" </StartMode>");
ss.WriteLine(" <Entries>");
foreach(ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.WriteLine(" <Entry filename=\"{0}\" />",
Helper.MakeFilePath(path, project.Name, "prjx"));
}
ss.WriteLine(" </Entries>");
count = 0;
foreach(ConfigurationNode conf in solution.Configurations)
{
if(count == 0)
{
ss.WriteLine(" <Configurations active=\"{0}\">", conf.Name);
}
ss.WriteLine(" <Configuration name=\"{0}\">", conf.Name);
foreach(ProjectNode project in solution.Projects)
{
ss.WriteLine(" <Entry name=\"{0}\" configurationname=\"{1}\" build=\"True\" />", project.Name, conf.Name);
}
ss.WriteLine(" </Configuration>");
count++;
}
ss.WriteLine(" </Configurations>");
ss.WriteLine("</Combine>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, "prjx");
Helper.DeleteIfExists(projectFile);
}
private void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning SharpDevelop combine and project files for", solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "cmbx");
Helper.DeleteIfExists(slnFile);
foreach(ProjectNode project in solution.Projects)
{
CleanProject(project);
}
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
/// <summary>
/// Writes the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public void Write(Kernel kern)
{
if( kern == null )
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach(SolutionNode solution in kern.Solutions)
{
WriteCombine(solution);
}
m_Kernel = null;
}
/// <summary>
/// Cleans the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Clean(Kernel kern)
{
if( kern == null )
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach(SolutionNode sol in kern.Solutions)
{
CleanSolution(sol);
}
m_Kernel = null;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return "sharpdev";
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
using System;
using System.ComponentModel.Composition;
using System.Net;
using System.Xml;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
/// <summary>
/// Class of extension rule for Metadata.Core.2005
/// </summary>
[Export(typeof(ExtensionRule))]
public class MetadataCore2005 : ExtensionRule
{
/// <summary>
/// Gets Category property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Metadata.Core.2005";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "The presence of HasStream attribute with a value of \"true\" on an <EntityType> element states that the Entity Type is associated with a Media Resource.";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string SpecificationSection
{
get
{
return "2.2.3.7.2";
}
}
/// <summary>
/// Gets the version.
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V1_V2_V3;
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Metadata;
}
}
/// <summary>
/// Gets the flag whether the rule requires metadata document
/// </summary>
public override bool? RequireMetadata
{
get
{
return true;
}
}
/// <summary>
/// Gets the offline context to which the rule applies
/// </summary>
public override bool? IsOfflineContext
{
get
{
return false;
}
}
/// <summary>
/// Gets the payload format to which the rule applies.
/// </summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.Xml;
}
}
/// <summary>
/// Verify Metadata.Core.2005
/// </summary>
/// <param name="context">Service context</param>
/// <param name="info">out parameter to return violation information when rule fail</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
info = null;
// Load MetadataDocument into XMLDOM
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(context.MetadataDocument);
// Find the namespace(s) in order to query for EntitySet name
XmlNodeList namespaceList = xmlDoc.SelectNodes("//*[@*[name()='Namespace']]");
// Find all properties marked m:HasStream = "true" in the document
XmlNodeList hasStreamList = xmlDoc.SelectNodes("//*[@*[name()='m:HasStream'] = 'true']");
if (hasStreamList.Count != 0)
{
// Find the EntitySet node
XmlNode entitySetNode = null;
foreach (XmlNode hsNode in hasStreamList)
{
bool foundEntitySet = false;
foreach (XmlNode nsNode in namespaceList)
{
if (!foundEntitySet)
{
entitySetNode = xmlDoc.SelectSingleNode("//*[@*[name()='EntityType'] = '" + nsNode.Attributes["Namespace"].Value + "." + hsNode.Attributes["Name"].Value + "']");
if (entitySetNode != null)
{
foundEntitySet = true;
}
}
}
// Query to find the first entity in the EntitySet
Uri absoluteUri = new Uri(context.Destination.OriginalString);
Uri relativeUri = new Uri(entitySetNode.Attributes["Name"].Value + "?$top=1", UriKind.Relative);
Uri combinedUri = new Uri(absoluteUri, relativeUri);
Response response = WebHelper.Get(combinedUri, Constants.AcceptHeaderAtom, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
if (response.StatusCode == HttpStatusCode.OK)
{
try
{
// Find the Uri that has media resource and query for it
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.LoadXml(response.ResponsePayload);
XmlNode node = xmlDoc2.SelectSingleNode("//*[local-name()='entry']/*[local-name()='id']");
response = WebHelper.Get(new Uri(node.InnerText + "/$value"), Constants.AcceptHeaderAtom, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
if (response.StatusCode == HttpStatusCode.OK)
{
passed = true;
}
else
{
passed = false;
}
}
catch (Exception)
{
passed = false;
}
}
}
}
info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
return passed;
}
}
}
| |
namespace StockSharp.Algo
{
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using StockSharp.Messages;
using StockSharp.Logging;
using StockSharp.Localization;
/// <summary>
/// Filtered market depth adapter.
/// </summary>
public class FilteredMarketDepthAdapter : MessageAdapterWrapper
{
private class FilteredMarketDepthInfo
{
private readonly Dictionary<ValueTuple<Sides, decimal>, decimal> _totals = new();
private readonly Dictionary<long, RefTriple<Sides, decimal, decimal?>> _ordersInfo = new();
private QuoteChangeMessage _lastSnapshot;
public FilteredMarketDepthInfo(long subscribeId, Subscription bookSubscription, Subscription ordersSubscription)
{
SubscribeId = subscribeId;
BookSubscription = bookSubscription ?? throw new ArgumentNullException(nameof(bookSubscription));
OrdersSubscription = ordersSubscription ?? throw new ArgumentNullException(nameof(ordersSubscription));
}
public long SubscribeId { get; }
public long UnSubscribeId { get; set; }
public Subscription BookSubscription { get; }
public Subscription OrdersSubscription { get; }
public OnlineInfo Online { get; set; }
//public SubscriptionStates State { get; set; } = SubscriptionStates.Stopped;
private QuoteChange[] Filter(Sides side, IEnumerable<QuoteChange> quotes)
{
return quotes
.Select(quote =>
{
if (_totals.TryGetValue((side, quote.Price), out var total))
quote.Volume -= total;
return quote;
})
.Where(q => q.Volume > 0)
.ToArray();
}
private QuoteChangeMessage CreateFilteredBook()
{
var book = new QuoteChangeMessage
{
SecurityId = _lastSnapshot.SecurityId,
ServerTime = _lastSnapshot.ServerTime,
LocalTime = _lastSnapshot.LocalTime,
IsSorted = _lastSnapshot.IsSorted,
BuildFrom = _lastSnapshot.BuildFrom,
Currency = _lastSnapshot.Currency,
IsFiltered = true,
Bids = Filter(Sides.Buy, _lastSnapshot.Bids),
Asks = Filter(Sides.Sell, _lastSnapshot.Asks),
};
if (Online == null)
book.SetSubscriptionIds(subscriptionId: SubscribeId);
else
book.SetSubscriptionIds(Online.Subscribers.Cache);
return book;
}
public QuoteChangeMessage Process(QuoteChangeMessage message)
{
if (message is null)
throw new ArgumentNullException(nameof(message));
_lastSnapshot = message.TypedClone();
return CreateFilteredBook();
}
public void AddOrder(OrderRegisterMessage message)
{
if (message is null)
throw new ArgumentNullException(nameof(message));
_ordersInfo[message.TransactionId] = RefTuple.Create(message.Side, message.Price, (decimal?)message.Volume);
var valKey = (message.Side, message.Price);
_totals.TryGetValue(valKey, out var total);
total += message.Volume;
_totals[valKey] = total;
}
public QuoteChangeMessage Process(ExecutionMessage message)
{
if (message is null)
throw new ArgumentNullException(nameof(message));
if (!message.HasOrderInfo)
return null;
if (message.TransactionId != 0)
{
if (message.OrderState is not OrderStates.Done and not OrderStates.Failed)
{
if (message.OrderPrice == 0)
return null;
var balance = message.Balance;
_ordersInfo[message.TransactionId] = RefTuple.Create(message.Side, message.OrderPrice, balance);
if (balance == null)
return null;
var valKey = (message.Side, message.OrderPrice);
if (_totals.TryGetValue(valKey, out var total))
{
total += balance.Value;
_totals[valKey] = total;
}
else
_totals.Add(valKey, balance.Value);
}
}
else if (_ordersInfo.TryGetValue(message.OriginalTransactionId, out var key))
{
var valKey = (key.First, key.Second);
switch (message.OrderState)
{
case OrderStates.Done:
case OrderStates.Failed:
{
_ordersInfo.Remove(message.OriginalTransactionId);
var balance = key.Third;
if (balance == null)
return null;
if (!_totals.TryGetValue(valKey, out var total))
return null;
total -= balance.Value;
if (total > 0)
_totals[valKey] = total;
else
_totals.Remove(valKey);
break;
}
case OrderStates.Active:
{
var newBalance = message.Balance;
if (newBalance == null)
return null;
var prevBalance = key.Third;
key.Third = newBalance;
if (prevBalance == null)
{
if (_totals.TryGetValue(valKey, out var total))
{
total += newBalance.Value;
_totals[valKey] = total;
}
else
_totals.Add(valKey, newBalance.Value);
}
else
{
if (_totals.TryGetValue(valKey, out var total))
{
var delta = prevBalance.Value - newBalance.Value;
if (delta == 0)
return null;
total -= delta;
if (total > 0)
_totals[valKey] = total;
else
_totals.Remove(valKey);
}
else if (newBalance > 0)
_totals.Add(valKey, newBalance.Value);
}
break;
}
}
}
else
return null;
return _lastSnapshot is null ? null : CreateFilteredBook();
}
}
private class OnlineInfo
{
public readonly CachedSynchronizedSet<long> Subscribers = new();
public readonly CachedSynchronizedSet<long> BookSubscribers = new();
public readonly CachedSynchronizedSet<long> OrdersSubscribers = new();
}
private readonly SyncObject _sync = new();
private readonly Dictionary<long, FilteredMarketDepthInfo> _byId = new();
private readonly Dictionary<long, FilteredMarketDepthInfo> _byBookId = new();
private readonly Dictionary<long, FilteredMarketDepthInfo> _byOrderStatusId = new();
private readonly Dictionary<SecurityId, OnlineInfo> _online = new();
private readonly Dictionary<long, Tuple<FilteredMarketDepthInfo, bool>> _unsubscribeRequests = new();
/// <summary>
/// Initializes a new instance of the <see cref="FilteredMarketDepthAdapter"/>.
/// </summary>
/// <param name="innerAdapter">Inner message adapter.</param>
public FilteredMarketDepthAdapter(IMessageAdapter innerAdapter)
: base(innerAdapter)
{
}
/// <inheritdoc />
protected override bool OnSendInMessage(Message message)
{
void AddInfo(OrderRegisterMessage regMsg)
{
if (regMsg is null)
throw new ArgumentNullException(nameof(regMsg));
if (regMsg.OrderType == OrderTypes.Market || regMsg.Price == 0)
return;
if (regMsg.TimeInForce is TimeInForce.MatchOrCancel or TimeInForce.CancelBalance)
return;
lock (_sync)
{
foreach (var info in _byId.Values)
{
if (info.BookSubscription.SecurityId == regMsg.SecurityId)
info.AddOrder(regMsg);
}
}
}
switch (message.Type)
{
case MessageTypes.Reset:
{
lock (_sync)
{
_byId.Clear();
_byBookId.Clear();
_byOrderStatusId.Clear();
_online.Clear();
_unsubscribeRequests.Clear();
}
break;
}
case MessageTypes.OrderRegister:
case MessageTypes.OrderReplace:
{
AddInfo((OrderRegisterMessage)message);
break;
}
case MessageTypes.OrderPairReplace:
{
var pairMsg = (OrderPairReplaceMessage)message;
AddInfo(pairMsg.Message1);
AddInfo(pairMsg.Message2);
break;
}
case MessageTypes.MarketData:
{
var mdMsg = (MarketDataMessage)message;
if (mdMsg.IsSubscribe)
{
if (mdMsg.SecurityId == default)
break;
if (mdMsg.DataType2 != DataType.FilteredMarketDepth)
break;
var transId = mdMsg.TransactionId;
mdMsg = mdMsg.TypedClone();
mdMsg.TransactionId = TransactionIdGenerator.GetNextId();
mdMsg.DataType2 = DataType.MarketDepth;
var orderStatus = new OrderStatusMessage
{
TransactionId = TransactionIdGenerator.GetNextId(),
IsSubscribe = true,
States = new[] { OrderStates.Active },
SecurityId = mdMsg.SecurityId,
};
var info = new FilteredMarketDepthInfo(transId, new Subscription(mdMsg, mdMsg), new Subscription(orderStatus, orderStatus));
lock (_sync)
{
_byId.Add(transId, info);
_byBookId.Add(mdMsg.TransactionId, info);
_byOrderStatusId.Add(orderStatus.TransactionId, info);
}
this.AddInfoLog("Filtered book {0} started (Book={1} / Orders={2}).", transId, mdMsg.TransactionId, orderStatus.TransactionId);
base.OnSendInMessage(mdMsg);
base.OnSendInMessage(orderStatus);
return true;
}
else
{
MarketDataMessage bookUnsubscribe = null;
OrderStatusMessage ordersUnsubscribe = null;
lock (_sync)
{
if (!_byId.TryGetValue(mdMsg.OriginalTransactionId, out var info))
break;
info.UnSubscribeId = mdMsg.TransactionId;
if (info.BookSubscription.State.IsActive())
{
bookUnsubscribe = new MarketDataMessage
{
TransactionId = TransactionIdGenerator.GetNextId(),
OriginalTransactionId = info.BookSubscription.TransactionId,
IsSubscribe = false,
};
_unsubscribeRequests.Add(bookUnsubscribe.TransactionId, Tuple.Create(info, true));
}
if (info.OrdersSubscription.State.IsActive())
{
ordersUnsubscribe = new OrderStatusMessage
{
TransactionId = TransactionIdGenerator.GetNextId(),
OriginalTransactionId = info.OrdersSubscription.TransactionId,
IsSubscribe = false,
};
_unsubscribeRequests.Add(ordersUnsubscribe.TransactionId, Tuple.Create(info, false));
}
}
if (bookUnsubscribe == null && ordersUnsubscribe == null)
{
RaiseNewOutMessage(new SubscriptionResponseMessage
{
OriginalTransactionId = mdMsg.TransactionId,
Error = new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(mdMsg.OriginalTransactionId)),
});
}
else
{
this.AddInfoLog("Filtered book {0} unsubscribing.", mdMsg.OriginalTransactionId);
if (bookUnsubscribe != null)
base.OnSendInMessage(bookUnsubscribe);
if (ordersUnsubscribe != null)
base.OnSendInMessage(ordersUnsubscribe);
}
return true;
}
}
}
return base.OnSendInMessage(message);
}
/// <inheritdoc />
protected override void OnInnerAdapterNewOutMessage(Message message)
{
Message TryApplyState(IOriginalTransactionIdMessage msg, SubscriptionStates state)
{
void TryCheckOnline(FilteredMarketDepthInfo info)
{
if (state != SubscriptionStates.Online)
return;
var book = info.BookSubscription;
var orders = info.OrdersSubscription;
if (info.BookSubscription.State == SubscriptionStates.Online && orders.State == SubscriptionStates.Online)
{
var online = _online.SafeAdd(book.SecurityId.Value);
online.Subscribers.Add(info.SubscribeId);
online.BookSubscribers.Add(book.TransactionId);
online.OrdersSubscribers.Add(orders.TransactionId);
info.Online = online;
}
}
var id = msg.OriginalTransactionId;
lock (_sync)
{
if (_byBookId.TryGetValue(id, out var info))
{
var book = info.BookSubscription;
book.State = book.State.ChangeSubscriptionState(state, id, this);
var subscribeId = info.SubscribeId;
if (!state.IsActive())
{
if (info.Online != null)
{
info.Online.BookSubscribers.Remove(id);
info.Online.OrdersSubscribers.Remove(info.OrdersSubscription.TransactionId);
info.Online.Subscribers.Remove(subscribeId);
info.Online = null;
}
}
else
TryCheckOnline(info);
switch (book.State)
{
case SubscriptionStates.Stopped:
case SubscriptionStates.Active:
case SubscriptionStates.Error:
return new SubscriptionResponseMessage { OriginalTransactionId = subscribeId, Error = (msg as IErrorMessage)?.Error };
case SubscriptionStates.Finished:
return new SubscriptionFinishedMessage { OriginalTransactionId = subscribeId };
case SubscriptionStates.Online:
return new SubscriptionOnlineMessage { OriginalTransactionId = subscribeId };
default:
throw new ArgumentOutOfRangeException(book.State.ToString());
}
}
else if (_byOrderStatusId.TryGetValue(id, out info))
{
info.OrdersSubscription.State = info.OrdersSubscription.State.ChangeSubscriptionState(state, id, this);
if (!state.IsActive())
info.Online?.OrdersSubscribers.Remove(id);
else
TryCheckOnline(info);
return null;
}
else if (_unsubscribeRequests.TryGetAndRemove(id, out var tuple))
{
info = tuple.Item1;
if (tuple.Item2)
{
var book = info.BookSubscription;
book.State = book.State.ChangeSubscriptionState(SubscriptionStates.Stopped, book.TransactionId, this);
return new SubscriptionResponseMessage
{
OriginalTransactionId = info.UnSubscribeId,
Error = (msg as IErrorMessage)?.Error,
};
}
else
{
var orders = info.OrdersSubscription;
orders.State = orders.State.ChangeSubscriptionState(SubscriptionStates.Stopped, orders.TransactionId, this);
return null;
}
}
else
return (Message)msg;
}
}
List<QuoteChangeMessage> filtered = null;
switch (message.Type)
{
case MessageTypes.SubscriptionResponse:
{
var responseMsg = (SubscriptionResponseMessage)message;
message = TryApplyState(responseMsg, responseMsg.IsOk() ? SubscriptionStates.Active : SubscriptionStates.Error);
break;
}
case MessageTypes.SubscriptionFinished:
{
message = TryApplyState((SubscriptionFinishedMessage)message, SubscriptionStates.Finished);
break;
}
case MessageTypes.SubscriptionOnline:
{
message = TryApplyState((SubscriptionOnlineMessage)message, SubscriptionStates.Online);
break;
}
case MessageTypes.QuoteChange:
{
var quoteMsg = (QuoteChangeMessage)message;
if (quoteMsg.State != null)
break;
HashSet<long> leftIds = null;
lock (_sync)
{
if (_byBookId.Count == 0)
break;
var ids = quoteMsg.GetSubscriptionIds();
HashSet<long> processed = null;
foreach (var id in ids)
{
if (processed != null && processed.Contains(id))
continue;
if (!_byBookId.TryGetValue(id, out var info))
continue;
var book = info.Process(quoteMsg);
if (leftIds is null)
leftIds = new HashSet<long>(ids);
if (info.Online is null)
leftIds.Remove(id);
else
{
if (processed is null)
processed = new HashSet<long>();
processed.AddRange(info.Online.BookSubscribers.Cache);
leftIds.RemoveRange(info.Online.BookSubscribers.Cache);
}
if (filtered == null)
filtered = new List<QuoteChangeMessage>();
filtered.Add(book);
}
}
if (leftIds is null)
break;
else if (leftIds.Count == 0)
message = null;
else
quoteMsg.SetSubscriptionIds(leftIds.ToArray());
break;
}
case MessageTypes.Execution:
{
var execMsg = (ExecutionMessage)message;
if (execMsg.IsMarketData())
break;
HashSet<long> leftIds = null;
lock (_sync)
{
if (_byOrderStatusId.Count == 0)
break;
var ids = execMsg.GetSubscriptionIds();
HashSet<long> processed = null;
foreach (var id in ids)
{
if (processed != null && processed.Contains(id))
continue;
if (!_byOrderStatusId.TryGetValue(id, out var info))
continue;
if (leftIds is null)
leftIds = new HashSet<long>(ids);
if (info.Online is null)
leftIds.Remove(id);
else
{
if (processed is null)
processed = new HashSet<long>();
processed.AddRange(info.Online.OrdersSubscribers.Cache);
leftIds.RemoveRange(info.Online.OrdersSubscribers.Cache);
}
if (filtered is null)
filtered = new List<QuoteChangeMessage>();
var book = info.Process(execMsg);
if (book is object)
filtered.Add(book);
}
}
if (leftIds is null)
break;
else if (leftIds.Count == 0)
message = null;
else
execMsg.SetSubscriptionIds(leftIds.ToArray());
break;
}
}
if (message != null)
base.OnInnerAdapterNewOutMessage(message);
if (filtered != null)
{
foreach (var book in filtered)
base.OnInnerAdapterNewOutMessage(book);
}
}
/// <summary>
/// Create a copy of <see cref="FilteredMarketDepthAdapter"/>.
/// </summary>
/// <returns>Copy.</returns>
public override IMessageChannel Clone() => new FilteredMarketDepthAdapter(InnerAdapter);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
namespace LinqToDB.SqlProvider
{
using SqlQuery;
class JoinOptimizer
{
Dictionary<SqlSearchCondition,SqlSearchCondition> _additionalFilter;
Dictionary<VirtualField,HashSet<Tuple<int,VirtualField>>> _equalityMap;
Dictionary<Tuple<SqlTableSource,SqlTableSource>,List<FoundEquality>> _fieldPairCache;
Dictionary<int,List<List<string>>> _keysCache;
HashSet<int> _removedSources;
Dictionary<VirtualField,VirtualField> _replaceMap;
SelectQuery _selectQuery;
SqlStatement _statement;
static bool IsEqualTables(SqlTable table1, SqlTable table2)
{
var result =
table1 != null
&& table2 != null
&& table1.ObjectType == table2.ObjectType
&& table1.Database == table2.Database
&& table1.Schema == table2.Schema
&& table1.Name == table2.Name
&& table1.PhysicalName == table2.PhysicalName;
return result;
}
void FlattenJoins(SqlTableSource table)
{
for (var i = 0; i < table.Joins.Count; i++)
{
var j = table.Joins[i];
FlattenJoins(j.Table);
if (j.JoinType == JoinType.Inner)
for (var si = 0; si < j.Table.Joins.Count; si++)
{
var sj = j.Table.Joins[si];
if ((sj.JoinType == JoinType.Inner || sj.JoinType == JoinType.Left || sj.JoinType == JoinType.CrossApply || sj.JoinType == JoinType.OuterApply)
&& table != j.Table && !HasDependencyWithParent(j, sj))
{
table.Joins.Insert(i + 1, sj);
j.Table.Joins.RemoveAt(si);
--si;
}
}
}
}
bool IsDependedBetweenJoins(SqlTableSource table,
SqlJoinedTable testedJoin)
{
var testedSources = new HashSet<int>(testedJoin.Table.GetTables().Select(t => t.SourceID));
foreach (var tableJoin in table.Joins)
{
if (testedSources.Contains(tableJoin.Table.SourceID))
continue;
if (IsDependedOnJoin(table, tableJoin, testedSources))
return true;
}
return IsDependedExcludeJoins(testedSources);
}
bool IsDepended(SqlJoinedTable join, SqlJoinedTable toIgnore)
{
var testedSources = new HashSet<int>(join.Table.GetTables().Select(t => t.SourceID));
if (toIgnore != null)
foreach (var sourceId in toIgnore.Table.GetTables().Select(t => t.SourceID))
testedSources.Add(sourceId);
var dependent = false;
new QueryVisitor().VisitParentFirst(_statement, e =>
{
if (dependent)
return false;
// ignore non searchable parts
if ( e.ElementType == QueryElementType.SelectClause
|| e.ElementType == QueryElementType.GroupByClause
|| e.ElementType == QueryElementType.OrderByClause)
return false;
if (e.ElementType == QueryElementType.JoinedTable)
if (testedSources.Contains(((SqlJoinedTable) e).Table.SourceID))
return false;
var expression = e as ISqlExpression;
if (expression != null)
{
var field = GetUnderlayingField(expression);
if (field != null)
{
var newField = GetNewField(field);
var local = testedSources.Contains(newField.SourceID);
if (local)
dependent = !CanWeReplaceField(null, newField, testedSources, -1);
}
}
return !dependent;
});
return dependent;
}
bool IsDependedExcludeJoins(SqlJoinedTable join)
{
var testedSources = new HashSet<int>(join.Table.GetTables().Select(t => t.SourceID));
return IsDependedExcludeJoins(testedSources);
}
bool IsDependedExcludeJoins(HashSet<int> testedSources)
{
var dependent = false;
bool CheckDependency(IQueryElement e)
{
if (dependent)
return false;
if (e.ElementType == QueryElementType.JoinedTable)
return false;
if (e is ISqlExpression expression)
{
var field = GetUnderlayingField(expression);
if (field != null)
{
var newField = GetNewField(field);
var local = testedSources.Contains(newField.SourceID);
if (local)
dependent = !CanWeReplaceField(null, newField, testedSources, -1);
}
}
return !dependent;
}
//TODO: review dependency checking
new QueryVisitor().VisitParentFirst(_selectQuery, CheckDependency);
if (!dependent && _selectQuery.ParentSelect == null)
new QueryVisitor().VisitParentFirst(_statement, CheckDependency);
return dependent;
}
bool HasDependencyWithParent(SqlJoinedTable parent,
SqlJoinedTable child)
{
var sources = new HashSet<int>(child.Table.GetTables().Select(t => t.SourceID));
var dependent = false;
// check that parent has dependency on child
new QueryVisitor().VisitParentFirst(parent, e =>
{
if (dependent)
return false;
if (e == child)
return false;
if (e is ISqlExpression expression)
{
var field = GetUnderlayingField(expression);
if (field != null)
dependent = sources.Contains(field.SourceID);
}
return !dependent;
});
return dependent;
}
bool IsDependedOnJoin(SqlTableSource table, SqlJoinedTable testedJoin, HashSet<int> testedSources)
{
var dependent = false;
var currentSourceId = testedJoin.Table.SourceID;
// check everyting that can be dependent on specific table
new QueryVisitor().VisitParentFirst(testedJoin, e =>
{
if (dependent)
return false;
if (e is ISqlExpression expression)
{
var field = GetUnderlayingField(expression);
if (field != null)
{
var newField = GetNewField(field);
var local = testedSources.Contains(newField.SourceID);
if (local)
dependent = !CanWeReplaceField(table, newField, testedSources, currentSourceId);
}
}
return !dependent;
});
return dependent;
}
bool CanWeReplaceFieldInternal(
SqlTableSource table, VirtualField field, HashSet<int> excludeSourceIds, int testedSourceIndex, HashSet<VirtualField> visited)
{
if (visited.Contains(field))
return false;
if (!excludeSourceIds.Contains(field.SourceID) && !IsSourceRemoved(field.SourceID))
return true;
visited.Add(field);
if (_equalityMap == null)
return false;
if (testedSourceIndex < 0)
return false;
if (_equalityMap.TryGetValue(field, out var sameFields))
foreach (var pair in sameFields)
if ((testedSourceIndex == 0 || GetSourceIndex(table, pair.Item1) > testedSourceIndex)
&& CanWeReplaceFieldInternal(table, pair.Item2, excludeSourceIds, testedSourceIndex, visited))
return true;
return false;
}
bool CanWeReplaceField(SqlTableSource table, VirtualField field, HashSet<int> excludeSourceId, int testedSourceId)
{
var visited = new HashSet<VirtualField>();
return CanWeReplaceFieldInternal(table, field, excludeSourceId, GetSourceIndex(table, testedSourceId), visited);
}
VirtualField GetNewField(VirtualField field)
{
if (_replaceMap == null)
return field;
if (_replaceMap.TryGetValue(field, out var newField))
{
while (_replaceMap.TryGetValue(newField, out var fieldOther))
newField = fieldOther;
}
else
{
newField = field;
}
return newField;
}
VirtualField MapToSourceInternal(SqlTableSource fromTable, VirtualField field, int sourceId, HashSet<VirtualField> visited)
{
if (visited.Contains(field))
return null;
if (field.SourceID == sourceId)
return field;
visited.Add(field);
if (_equalityMap == null)
return null;
var sourceIndex = GetSourceIndex(fromTable, sourceId);
HashSet<Tuple<int, VirtualField>> sameFields;
if (_equalityMap.TryGetValue(field, out sameFields))
foreach (var pair in sameFields)
{
var itemIndex = GetSourceIndex(fromTable, pair.Item1);
if (itemIndex >= 0 && (sourceIndex == 0 || itemIndex < sourceIndex))
{
var newField = MapToSourceInternal(fromTable, pair.Item2, sourceId, visited);
if (newField != null)
return newField;
}
}
return null;
}
VirtualField MapToSource(SqlTableSource table, VirtualField field, int sourceId)
{
var visited = new HashSet<VirtualField>();
return MapToSourceInternal(table, field, sourceId, visited);
}
void RemoveSource(SqlTableSource fromTable, SqlJoinedTable join)
{
if (_removedSources == null)
_removedSources = new HashSet<int>();
_removedSources.Add(join.Table.SourceID);
if (_equalityMap != null)
{
var keys = _equalityMap.Keys.Where(k => k.SourceID == join.Table.SourceID).ToArray();
foreach (var key in keys)
{
var newField = MapToSource(fromTable, key, fromTable.SourceID);
if (newField != null)
ReplaceField(key, newField);
_equalityMap.Remove(key);
}
}
ResetFieldSearchCache(join.Table);
}
bool IsSourceRemoved(int sourceId)
{
return _removedSources != null && _removedSources.Contains(sourceId);
}
void ReplaceField(VirtualField oldField, VirtualField newField)
{
if (_replaceMap == null)
_replaceMap = new Dictionary<VirtualField, VirtualField>();
_replaceMap.Remove(oldField);
_replaceMap.Add (oldField, newField);
}
void AddEqualFields(VirtualField field1, VirtualField field2, int levelSourceId)
{
if (_equalityMap == null)
_equalityMap = new Dictionary<VirtualField, HashSet<Tuple<int, VirtualField>>>();
HashSet<Tuple<int, VirtualField>> set;
if (!_equalityMap.TryGetValue(field1, out set))
{
set = new HashSet<Tuple<int, VirtualField>>();
_equalityMap.Add(field1, set);
}
set.Add(Tuple.Create(levelSourceId, field2));
}
bool CompareExpressions(SqlPredicate.ExprExpr expr1, SqlPredicate.ExprExpr expr2)
{
if (expr1.Operator != expr2.Operator)
return false;
if (expr1.ElementType != expr2.ElementType)
return false;
switch (expr1.ElementType)
{
case QueryElementType.ExprExprPredicate:
{
return CompareExpressions(expr1.Expr1, expr2.Expr1) == true
&& CompareExpressions(expr1.Expr2, expr2.Expr2) == true
|| CompareExpressions(expr1.Expr1, expr2.Expr2) == true
&& CompareExpressions(expr1.Expr2, expr2.Expr1) == true;
}
}
return false;
}
bool? CompareExpressions(ISqlExpression expr1, ISqlExpression expr2)
{
if (expr1.ElementType != expr2.ElementType)
return null;
switch (expr1.ElementType)
{
case QueryElementType.Column:
{
return CompareExpressions(((SqlColumn) expr1).Expression, ((SqlColumn) expr2).Expression);
}
case QueryElementType.SqlField:
{
var field1 = GetNewField(new VirtualField((SqlField) expr1));
var field2 = GetNewField(new VirtualField((SqlField) expr2));
return field1.Equals(field2);
}
}
return null;
}
bool CompareConditions(SqlCondition cond1, SqlCondition cond2)
{
if (cond1.ElementType != cond2.ElementType)
return false;
if (cond1.Predicate.ElementType != cond2.Predicate.ElementType)
return false;
switch (cond1.Predicate.ElementType)
{
case QueryElementType.IsNullPredicate:
{
var isNull1 = (SqlPredicate.IsNull) cond1.Predicate;
var isNull2 = (SqlPredicate.IsNull) cond2.Predicate;
return isNull1.IsNot == isNull2.IsNot && CompareExpressions(isNull1.Expr1, isNull2.Expr1) == true;
}
case QueryElementType.ExprExprPredicate:
{
var expr1 = (SqlPredicate.ExprExpr) cond1.Predicate;
var expr2 = (SqlPredicate.ExprExpr) cond2.Predicate;
return CompareExpressions(expr1, expr2);
}
}
return false;
}
bool? EvaluateLogical(SqlCondition condition)
{
switch (condition.ElementType)
{
case QueryElementType.Condition:
{
if (condition.Predicate is SqlPredicate.ExprExpr expr && expr.Operator == SqlPredicate.Operator.Equal)
return CompareExpressions(expr.Expr1, expr.Expr2);
break;
}
}
return null;
}
void OptimizeSearchCondition(SqlSearchCondition searchCondition)
{
var items = searchCondition.Conditions;
if (items.Any(c => c.IsOr))
return;
for (var i1 = 0; i1 < items.Count; i1++)
{
var c1 = items[i1];
var cmp = EvaluateLogical(c1);
if (cmp != null)
if (cmp.Value)
{
items.RemoveAt(i1);
--i1;
continue;
}
switch (c1.ElementType)
{
case QueryElementType.Condition:
case QueryElementType.SearchCondition:
{
if (c1.Predicate is SqlSearchCondition search)
{
OptimizeSearchCondition(search);
if (search.Conditions.Count == 0)
{
items.RemoveAt(i1);
--i1;
continue;
}
}
break;
}
}
for (var i2 = i1 + 1; i2 < items.Count; i2++)
{
var c2 = items[i2];
if (CompareConditions(c2, c1))
{
searchCondition.Conditions.RemoveAt(i2);
--i2;
}
}
}
}
void AddSearchCondition(SqlSearchCondition search, SqlCondition condition)
{
AddSearchConditions(search, new[] {condition});
}
void AddSearchConditions(SqlSearchCondition search, IEnumerable<SqlCondition> conditions)
{
if (_additionalFilter == null)
_additionalFilter = new Dictionary<SqlSearchCondition, SqlSearchCondition>();
if (!_additionalFilter.TryGetValue(search, out var value))
{
if (search.Conditions.Count > 0 && search.Precedence < Precedence.LogicalConjunction)
{
value = new SqlSearchCondition();
var prev = new SqlSearchCondition();
prev. Conditions.AddRange(search.Conditions);
search.Conditions.Clear();
search.Conditions.Add(new SqlCondition(false, value, false));
search.Conditions.Add(new SqlCondition(false, prev, false));
}
else
{
value = search;
}
_additionalFilter.Add(search, value);
}
value.Conditions.AddRange(conditions);
}
void OptimizeFilters()
{
if (_additionalFilter == null)
return;
foreach (var pair in _additionalFilter)
{
OptimizeSearchCondition(pair.Value);
if (!ReferenceEquals(pair.Key, pair.Value) && pair.Value.Conditions.Count == 1)
{
// conditions can be optimized so we have to remove empty SearchCondition
if (pair.Value.Conditions[0].Predicate is SqlSearchCondition searchCondition &&
searchCondition.Conditions.Count == 0)
pair.Key.Conditions.Remove(pair.Value.Conditions[0]);
}
}
}
Dictionary<string, VirtualField> GetFields(ISqlTableSource source)
{
var res = new Dictionary<string, VirtualField>();
if (source is SqlTable table)
foreach (var pair in table.Fields)
res.Add(pair.Key, new VirtualField(pair.Value));
return res;
}
void ReplaceSource(SqlTableSource fromTable, SqlJoinedTable oldSource, SqlTableSource newSource)
{
var oldFields = GetFields(oldSource.Table.Source);
var newFields = GetFields(newSource.Source);
foreach (var old in oldFields)
{
var newField = newFields[old.Key];
ReplaceField(old.Value, newField);
}
RemoveSource(fromTable, oldSource);
}
void CorrectMappings()
{
if (_replaceMap != null && _replaceMap.Count > 0 || _removedSources != null)
{
((ISqlExpressionWalkable)_statement)
.Walk(new WalkOptions(), element =>
{
if (element is SqlField field)
return GetNewField(new VirtualField(field)).Element;
if (element is SqlColumn column)
return GetNewField(new VirtualField(column)).Element;
return element;
});
}
}
int GetSourceIndex(SqlTableSource table, int sourceId)
{
if (table == null || table.SourceID == sourceId || sourceId == -1)
return 0;
var i = 0;
while (i < table.Joins.Count)
{
if (table.Joins[i].Table.SourceID == sourceId)
return i + 1;
++i;
}
return -1;
}
void CollectEqualFields(SqlJoinedTable join)
{
if (join.JoinType != JoinType.Inner)
return;
if (join.Condition.Conditions.Any(c => c.IsOr))
return;
for (var i1 = 0; i1 < join.Condition.Conditions.Count; i1++)
{
var c = join.Condition.Conditions[i1];
if ( c.ElementType != QueryElementType.Condition
|| c.Predicate.ElementType != QueryElementType.ExprExprPredicate
|| ((SqlPredicate.ExprExpr) c.Predicate).Operator != SqlPredicate.Operator.Equal)
continue;
var predicate = (SqlPredicate.ExprExpr) c.Predicate;
var field1 = GetUnderlayingField(predicate.Expr1);
if (field1 == null)
continue;
var field2 = GetUnderlayingField(predicate.Expr2);
if (field2 == null)
continue;
if (field1.Equals(field2))
continue;
AddEqualFields(field1, field2, join.Table.SourceID);
AddEqualFields(field2, field1, join.Table.SourceID);
}
}
List<List<string>> GetKeysInternal(ISqlTableSource tableSource)
{
//TODO: needed mechanism to define unique indexes. Currently only primary key is used
// only from tables we can get keys
if (!(tableSource is SqlTable))
return null;
var keys = tableSource.GetKeys(false);
if (keys == null || keys.Count == 0)
return null;
var fields = keys.Select(GetUnderlayingField)
.Where(f => f != null)
.Select(f => f.Name).ToList();
if (fields.Count != keys.Count)
return null;
var knownKeys = new List<List<string>> { fields };
return knownKeys;
}
List<List<string>> GetKeys(ISqlTableSource tableSource)
{
if (_keysCache == null || !_keysCache.TryGetValue(tableSource.SourceID, out var keys))
{
keys = GetKeysInternal(tableSource);
if (_keysCache == null)
_keysCache = new Dictionary<int, List<List<string>>>();
_keysCache.Add(tableSource.SourceID, keys);
}
return keys;
}
public void OptimizeJoins(SqlStatement statement, SelectQuery selectQuery)
{
_selectQuery = selectQuery;
_statement = statement;
for (var i = 0; i < selectQuery.From.Tables.Count; i++)
{
var fromTable = selectQuery.From.Tables[i];
FlattenJoins(fromTable);
for (var i1 = 0; i1 < fromTable.Joins.Count; i1++)
{
var j1 = fromTable.Joins[i1];
CollectEqualFields(j1);
// supported only INNER and LEFT joins
if (j1.JoinType != JoinType.Inner && j1.JoinType != JoinType.Left)
continue;
// trying to remove join that is equal to FROM table
if (IsEqualTables(fromTable.Source as SqlTable, j1.Table.Source as SqlTable))
{
var keys = GetKeys(j1.Table.Source);
if (keys != null && TryMergeWithTable(fromTable, j1, keys))
{
fromTable.Joins.RemoveAt(i1);
--i1;
continue;
}
}
for (var i2 = i1 + 1; i2 < fromTable.Joins.Count; i2++)
{
var j2 = fromTable.Joins[i2];
// we can merge LEFT and INNER joins together
if (j2.JoinType != JoinType.Inner && j2.JoinType != JoinType.Left)
continue;
if (!IsEqualTables(j1.Table.Source as SqlTable, j2.Table.Source as SqlTable))
continue;
var keys = GetKeys(j2.Table.Source);
if (keys != null)
{
// try merge if joins are the same
var merged = TryMergeJoins(fromTable, fromTable, j1, j2, keys);
if (!merged)
for (var im = 0; im < i2; im++)
if (fromTable.Joins[im].JoinType == JoinType.Inner || j2.JoinType != JoinType.Left)
{
merged = TryMergeJoins(fromTable, fromTable.Joins[im].Table, j1, j2, keys);
if (merged)
break;
}
if (merged)
{
fromTable.Joins.RemoveAt(i2);
--i2;
}
}
}
}
// trying to remove joins that are not in projection
for (var i1 = 0; i1 < fromTable.Joins.Count; i1++)
{
var j1 = fromTable.Joins[i1];
if (j1.JoinType == JoinType.Left || j1.JoinType == JoinType.Inner)
{
var keys = GetKeys(j1.Table.Source);
if (keys != null && !IsDependedBetweenJoins(fromTable, j1))
{
// try merge if joins are the same
var removed = TryToRemoveIndependent(fromTable, fromTable, j1, keys);
if (!removed)
for (var im = 0; im < i1; im++)
{
var jm = fromTable.Joins[im];
if (jm.JoinType == JoinType.Inner || jm.JoinType != JoinType.Left)
{
removed = TryToRemoveIndependent(fromTable, jm.Table, j1, keys);
if (removed)
break;
}
}
if (removed)
{
fromTable.Joins.RemoveAt(i1);
--i1;
}
}
}
} // independent joins loop
} // table loop
OptimizeFilters();
CorrectMappings();
}
static VirtualField GetUnderlayingField(ISqlExpression expr)
{
switch (expr.ElementType)
{
case QueryElementType.SqlField:
return new VirtualField((SqlField) expr);
case QueryElementType.Column:
return new VirtualField((SqlColumn)expr);
}
return null;
}
void DetectField(SqlTableSource manySource, SqlTableSource oneSource, VirtualField field, FoundEquality equality)
{
field = GetNewField(field);
if (oneSource.Source.SourceID == field.SourceID)
equality.OneField = field;
else if (manySource.Source.SourceID == field.SourceID)
equality.ManyField = field;
else
equality.ManyField = MapToSource(manySource, field, manySource.Source.SourceID);
}
bool MatchFields(SqlTableSource manySource, SqlTableSource oneSource, VirtualField field1, VirtualField field2, FoundEquality equality)
{
if (field1 == null || field2 == null)
return false;
DetectField(manySource, oneSource, field1, equality);
DetectField(manySource, oneSource, field2, equality);
return equality.OneField != null && equality.ManyField != null;
}
void ResetFieldSearchCache(SqlTableSource table)
{
if (_fieldPairCache == null)
return;
var keys = _fieldPairCache.Keys.Where(k => k.Item2 == table || k.Item1 == table).ToArray();
foreach (var key in keys)
_fieldPairCache.Remove(key);
}
List<FoundEquality> SearchForFields(SqlTableSource manySource, SqlJoinedTable join)
{
var key = Tuple.Create(manySource, join.Table);
List<FoundEquality> found = null;
if (_fieldPairCache != null && _fieldPairCache.TryGetValue(key, out found))
return found;
for (var i1 = 0; i1 < join.Condition.Conditions.Count; i1++)
{
var c = join.Condition.Conditions[i1];
if (c.IsOr)
{
found = null;
break;
}
if ( c.ElementType != QueryElementType.Condition
|| c.Predicate.ElementType != QueryElementType.ExprExprPredicate
|| ((SqlPredicate.ExprExpr) c.Predicate).Operator != SqlPredicate.Operator.Equal)
continue;
var predicate = (SqlPredicate.ExprExpr) c.Predicate;
var equality = new FoundEquality();
if (!MatchFields(manySource, join.Table,
GetUnderlayingField(predicate.Expr1),
GetUnderlayingField(predicate.Expr2),
equality))
continue;
equality.OneCondition = c;
if (found == null)
found = new List<FoundEquality>();
found.Add(equality);
}
if (_fieldPairCache == null)
_fieldPairCache = new Dictionary<Tuple<SqlTableSource, SqlTableSource>, List<FoundEquality>>();
_fieldPairCache.Add(key, found);
return found;
}
bool TryMergeWithTable(SqlTableSource fromTable, SqlJoinedTable join, List<List<string>> uniqueKeys)
{
if (join.Table.Joins.Count != 0)
return false;
var hasLeftJoin = join.JoinType == JoinType.Left;
var found = SearchForFields(fromTable, join);
if (found == null)
return false;
// for removing join with same table fields should be equal
found = found.Where(f => f.OneField.Name == f.ManyField.Name).ToList();
if (found.Count == 0)
return false;
if (hasLeftJoin)
{
if (join.Condition.Conditions.Count != found.Count)
return false;
// currently no dependencies in search condition allowed for left join
if (IsDependedExcludeJoins(join))
return false;
}
HashSet<string> foundFields = new HashSet<string>(found.Select(f => f.OneField.Name));
HashSet<string> uniqueFields = null;
for (var i = 0; i < uniqueKeys.Count; i++)
{
var keys = uniqueKeys[i];
if (keys.All(k => foundFields.Contains(k)))
{
if (uniqueFields == null)
uniqueFields = new HashSet<string>();
foreach (var key in keys)
uniqueFields.Add(key);
}
}
if (uniqueFields != null)
{
foreach (var item in found)
if (uniqueFields.Contains(item.OneField.Name))
{
// remove unique key conditions
join.Condition.Conditions.Remove(item.OneCondition);
AddEqualFields(item.ManyField, item.OneField, fromTable.SourceID);
}
// move rest conditions to the Where section
if (join.Condition.Conditions.Count > 0)
{
AddSearchConditions(_selectQuery.Where.SearchCondition, join.Condition.Conditions);
join.Condition.Conditions.Clear();
}
// add check that previously joined fields is not null
foreach (var item in found)
if (item.ManyField.CanBeNull)
{
var newField = MapToSource(fromTable, item.ManyField, fromTable.SourceID);
AddSearchCondition(_selectQuery.Where.SearchCondition,
new SqlCondition(false, new SqlPredicate.IsNull(newField.Element, true)));
}
// add mapping to new source
ReplaceSource(fromTable, join, fromTable);
return true;
}
return false;
}
bool TryMergeJoins(SqlTableSource fromTable,
SqlTableSource manySource,
SqlJoinedTable join1, SqlJoinedTable join2,
List<List<string>> uniqueKeys)
{
var found1 = SearchForFields(manySource, join1);
if (found1 == null)
return false;
var found2 = SearchForFields(manySource, join2);
if (found2 == null)
return false;
var hasLeftJoin = join1.JoinType == JoinType.Left || join2.JoinType == JoinType.Left;
// left join should match exactly
if (hasLeftJoin)
{
if (join1.Condition.Conditions.Count != join2.Condition.Conditions.Count)
return false;
if (found1.Count != found2.Count)
return false;
if (join1.Table.Joins.Count != 0 || join2.Table.Joins.Count != 0)
return false;
}
List<FoundEquality> found = null;
for (var i1 = 0; i1 < found1.Count; i1++)
{
var f1 = found1[i1];
for (var i2 = 0; i2 < found2.Count; i2++)
{
var f2 = found2[i2];
if (f1.ManyField.Name == f2.ManyField.Name && f1.OneField.Name == f2.OneField.Name)
{
if (found == null)
found = new List<FoundEquality>();
found.Add(f2);
}
}
}
if (found == null)
return false;
if (hasLeftJoin)
{
// for left join each expression should be used
if (found.Count != join1.Condition.Conditions.Count)
return false;
// currently no dependencies in search condition allowed for left join
if (IsDepended(join1, join2))
return false;
}
HashSet<string> foundFields = new HashSet<string>(found.Select(f => f.OneField.Name));
HashSet<string> uniqueFields = null;
for (var i = 0; i < uniqueKeys.Count; i++)
{
var keys = uniqueKeys[i];
if (keys.All(k => foundFields.Contains(k)))
{
if (uniqueFields == null)
uniqueFields = new HashSet<string>();
foreach (var key in keys)
uniqueFields.Add(key);
}
}
if (uniqueFields != null)
{
foreach (var item in found)
if (uniqueFields.Contains(item.OneField.Name))
{
// remove from second
join2.Condition.Conditions.Remove(item.OneCondition);
AddEqualFields(item.ManyField, item.OneField, fromTable.SourceID);
}
// move rest conditions to first
if (join2.Condition.Conditions.Count > 0)
{
AddSearchConditions(join1.Condition, join2.Condition.Conditions);
join2.Condition.Conditions.Clear();
}
join1.Table.Joins.AddRange(join2.Table.Joins);
// add mapping to new source
ReplaceSource(fromTable, join2, join1.Table);
return true;
}
return false;
}
// here we can deal with LEFT JOIN and INNER JOIN
bool TryToRemoveIndependent(
SqlTableSource fromTable, SqlTableSource manySource, SqlJoinedTable join, List<List<string>> uniqueKeys)
{
if (join.JoinType == JoinType.Inner)
return false;
var found = SearchForFields(manySource, join);
if (found == null)
return false;
HashSet<string> foundFields = new HashSet<string>(found.Select(f => f.OneField.Name));
HashSet<string> uniqueFields = null;
for (var i = 0; i < uniqueKeys.Count; i++)
{
var keys = uniqueKeys[i];
if (keys.All(k => foundFields.Contains(k)))
{
if (uniqueFields == null)
uniqueFields = new HashSet<string>();
foreach (var key in keys)
uniqueFields.Add(key);
}
}
if (uniqueFields != null)
{
if (join.JoinType == JoinType.Inner)
{
foreach (var item in found)
if (uniqueFields.Contains(item.OneField.Name))
{
// remove from second
join.Condition.Conditions.Remove(item.OneCondition);
AddEqualFields(item.ManyField, item.OneField, fromTable.SourceID);
}
// move rest conditions to Where
if (join.Condition.Conditions.Count > 0)
{
AddSearchConditions(_selectQuery.Where.SearchCondition, join.Condition.Conditions);
join.Condition.Conditions.Clear();
}
// add filer for nullable fileds because after INNER JOIN records with nulls disappear
foreach (var item in found)
if (item.ManyField.CanBeNull)
AddSearchCondition(_selectQuery.Where.SearchCondition,
new SqlCondition(false, new SqlPredicate.IsNull(item.ManyField.Element, true)));
}
RemoveSource(fromTable, join);
return true;
}
return false;
}
[DebuggerDisplay("{ManyField.DisplayString()} -> {OneField.DisplayString()}")]
class FoundEquality
{
public VirtualField ManyField;
public SqlCondition OneCondition;
public VirtualField OneField;
}
[DebuggerDisplay("{DisplayString()}")]
class VirtualField
{
public VirtualField([NotNull] SqlField field)
{
Field = field ?? throw new ArgumentNullException(nameof(field));
}
public VirtualField([NotNull] SqlColumn column)
{
Column = column ?? throw new ArgumentNullException(nameof(column));
}
public SqlField Field { get; }
public SqlColumn Column { get; }
public string Name => Field == null ? Column.Alias : Field.Name;
public int SourceID => Field == null ? Column.Parent.SourceID : Field.Table?.SourceID ?? -1;
public bool CanBeNull => Field?.CanBeNull ?? Column.CanBeNull;
public ISqlExpression Element
{
get
{
if (Field != null)
return Field;
return Column;
}
}
protected bool Equals(VirtualField other)
{
return Equals(Field, other.Field) && Equals(Column, other.Column);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((VirtualField) obj);
}
string GetSourceString(ISqlTableSource source)
{
if (source is SqlTable table)
{
var res = $"({source.SourceID}).{table.Name}";
if (table.Alias != table.Name && !string.IsNullOrEmpty(table.Alias))
res = res + "(" + table.Alias + ")";
return res;
}
return $"({source.SourceID}).{source}";
}
public string DisplayString()
{
if (Field != null)
return $"F: '{GetSourceString(Field.Table)}.{Name}'";
return $"C: '{GetSourceString(Column.Parent)}.{Name}'";
}
public override int GetHashCode()
{
unchecked
{
return ((Field != null ? Field.GetHashCode() : 0) * 397) ^ (Column != null ? Column.GetHashCode() : 0);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using OLEDB.Test.ModuleCore;
/// <summary>
/// This class is used to write out XML tokens. This tool can write
/// well-formed as well as non well-formed file. This writer does not
/// guarantee well-formedness. It does not implement XmlWriter.
/// The class can write tokens by explicit API calls as well as parse
/// a pattern string to generate these tokens.
/// </summary>
namespace XmlCoreTest.Common
{
public class ManagedNodeWriter
{
public static bool DEBUG = false;
private const string XML_DECL = "<?xml version='1.0' ?>\n";
private const string S_ROOT = "<root>";
private const string E_ROOT = "</root>";
private const string E_NAME = "ELEMENT_";
private const string A_NAME = "ATTRIB_";
private const string A_VALUE = "VALUE_";
private const string CDATA = "CDATA_";
private const string TEXT = "TEXT_";
private const string PI = "PI_";
private const string COMMENT = "COMMENT_";
private long _eCount = 0; //element indexer
private long _aCount = 0; //attribute indexer
private long _cCount = 0; //Cdata indexer
private long _tCount = 0; //Text indexer
private long _pCount = 0; //PI Indexer
private long _mCount = 0; //Comment Indexer
private StreamWriter _textWriter = null;
//Obviously performance is not a major requirement so
//making use of out-of-box data structures to keep
//state of the writer.
//Managing the Element Stack.
private Stack<string> _stack = null;
//Managing the Node Queue.
private StringBuilder _q = null;
private const string LT = "<";
private const string GT = ">";
private const string MT = "/>";
private const string ET = "</";
private const string SPACE = " ";
private const string S_QUOTE = "'";
private const string D_QUOTE = "\"";
private const string EQ = "=";
private const string LF = "\n";
private void Init()
{
_q = new StringBuilder();
_stack = new Stack<string>();
}
private void Destroy()
{
_q = null;
_stack = null;
}
/// <summary>
/// Default Constructor.
/// </summary>
public ManagedNodeWriter()
{
Init();
}
///
/// Overloaded Constructor with FileName to Write
///
public ManagedNodeWriter(string filename)
{
Init();
_textWriter = new StreamWriter(FilePathUtil.getStream(filename));
}
public ManagedNodeWriter(Stream myStream, Encoding enc)
{
Init();
_textWriter = new StreamWriter(myStream, enc);
}
/// <summary>
/// Similar to the XmlWriter WriteDocType
/// </summary>
/// <param name="name">Doctype name</param>
/// <param name="sysid">System ID</param>
/// <param name="pubid">Public ID</param>
/// <param name="subset">Content Model</param>
public void WriteDocType(string name, string sysid, string pubid, string subset)
{
StringBuilder dt = new StringBuilder();
dt.Append("<!DOCTYPE ");
dt.Append(name);
if (pubid == null)
{
if (sysid != null)
dt.Append(" SYSTEM " + sysid);
}
else
{
dt.Append(" PUBLIC " + pubid);
if (sysid != null)
{
dt.Append(" " + sysid);
}
}
dt.Append("[");
if (subset != null)
dt.Append(subset);
dt.Append("]>");
if (DEBUG)
CError.WriteLine(dt.ToString());
_q.Append(dt.ToString());
}
/// <summary>
/// GetNodes returns the existing XML string thats been written so far.
/// </summary>
/// <returns>String of XML</returns>
public string GetNodes()
{
return _q.ToString();
}
/// Closing the NodeWriter
public void Close()
{
if (_textWriter != null)
{
_textWriter.Write(_q.ToString());
//textWriter.Close();
_textWriter.Dispose();
_textWriter = null;
}
Destroy();
}
/// Writing XML Decl
public void PutDecl()
{
_q.Append(XML_DECL);
}
/// Writing a Root Element.
public void PutRoot()
{
_q.Append(S_ROOT);
}
/// Writing End Root Element.
public void PutEndRoot()
{
_q.Append(E_ROOT);
}
/// Writing a start of open element.
public void OpenElement()
{
string elem = LT + E_NAME + _eCount + SPACE;
_q.Append(elem);
_stack.Push(E_NAME + _eCount);
++_eCount;
}
/// Writing a start of open element with user supplied name.
public void OpenElement(string myName)
{
string elem = LT + myName + SPACE;
_stack.Push(myName);
_q.Append(elem);
}
/// Closing the open element.
public void CloseElement()
{
_q.Append(GT);
}
// Closing the open element as empty element
public void CloseEmptyElement()
{
_q.Append(MT);
}
/// Writing an attribute.
public void PutAttribute()
{
string attr = A_NAME + _aCount + EQ + S_QUOTE + A_VALUE + _aCount + S_QUOTE + SPACE;
_q.Append(attr);
++_aCount;
}
/// Overloaded PutAttribute which takes user values.
public void PutAttribute(string myAttrName, string myAttrValue)
{
string attr = SPACE + myAttrName + EQ + S_QUOTE + myAttrValue + S_QUOTE;
_q.Append(attr);
}
/// Writing empty element.
public void PutEmptyElement()
{
string elem = LT + E_NAME + _eCount + MT;
_q.Append(elem);
++_eCount;
}
/// Writing an end element from the stack.
public void PutEndElement()
{
string elem = (string)_stack.Pop();
_q.Append(ET + elem + GT);
}
/// Writing an end element for a given name.
public void PutEndElement(string myName)
{
if (DEBUG)
CError.WriteLine("Popping : " + (string)_stack.Pop());
_q.Append(ET + myName + GT);
}
/// <summary>
/// Finish allows user to complete xml file with the end element tags that were so far open.
/// </summary>
public void Finish()
{
while (_stack.Count > 0)
{
string elem = (string)_stack.Pop();
_q.Append(ET + elem + GT);
}
}
/// Writing text.
/// Note : This is basically equivalent to WriteRaw and the string may contain any number of embedded tags.
/// No checking is performed on them either.
public void PutText(string myStr)
{
_q.Append(myStr);
}
/// <summary>
/// AutoGenerated Text
/// </summary>
public void PutText()
{
_q.Append(TEXT + _tCount++);
}
/// <summary>
/// Writing a Byte Array.
/// </summary>
/// <param name="bArr"></param>
public void PutBytes(byte[] bArr)
{
foreach (byte b in bArr)
{
_q.Append(b);
}
}
public void PutByte()
{
_q.Append(Convert.ToByte("a"));
}
/// <summary>
/// Writes out CDATA Node.
/// </summary>
public void PutCData()
{
_q.Append("<![CDATA[" + CDATA + _cCount++ + "]]>");
}
/// <summary>
/// Writes out a PI Node.
/// </summary>
public void PutPI()
{
_q.Append("<?" + PI + _pCount++ + "?>");
}
/// <summary>
/// Writes out a Comment Node.
/// </summary>
public void PutComment()
{
_q.Append("<!--" + COMMENT + _mCount++ + " -->");
}
/// <summary>
/// Writes out a single whitespace
/// </summary>
public void PutWhiteSpace()
{
_q.Append(" ");
}
/// <summary>
/// This method is a conveinience method and a shortcut to create an XML string. Each character in the pattern
/// maps to a particular Put/Open function and calls it for you. For e.g. XEAA/ will call PutDecl, OpenElement,
/// PutAttribute, PutAttribute and CloseElement for you.
/// The following is the list of all allowed characters and their function mappings :
///
///'X' : PutDecl()
///'E' : OpenElement()
///'M' : CloseEmptyElement()
///'/' : CloseElement()
///'e' : PutEndElement()
///'A' : PutAttribute()
///'P' : PutPI()
///'T' : PutText()
///'C' : PutComment()
///'R' : PutRoot()
///'r' : PutEndRoot()
///'B' : PutEndRoot()
///'W' : PutWhiteSpace()
///
/// </summary>
/// <param name="pattern">String containing the pattern which you want to use to create
/// the XML string. Refer to table above for supported chars.</param>
public void PutPattern(string pattern)
{
char[] patternArr = pattern.ToCharArray();
foreach (char ch in patternArr)
{
switch (ch)
{
case 'X':
PutDecl();
break;
case 'E':
OpenElement();
break;
case 'M':
CloseEmptyElement();
break;
case '/':
CloseElement();
break;
case 'e':
PutEndElement();
break;
case 'A':
PutAttribute();
break;
case 'P':
PutPI();
break;
case 'T':
PutText();
break;
case 'C':
PutComment();
break;
case 'R':
PutRoot();
break;
case 'r':
PutEndRoot();
break;
case 'B':
PutEndRoot();
break;
case 'W':
PutWhiteSpace();
break;
default:
CError.WriteLine("Skipping Character : " + ch);
break;
}
}
}
// Entry point.
public static void Main(string[] args)
{
string filename = "temp.xml";
ManagedNodeWriter mw = new ManagedNodeWriter(filename);
ManagedNodeWriter mnw = new ManagedNodeWriter();
mnw.PutPattern("X");
int count = 0;
do
{
mnw.PutPattern("E/");
count++;
} while (count < 65536);
mnw.PutText("<a/>");
mnw.Finish();
StreamWriter sw = new StreamWriter(FilePathUtil.getStream("deep.xml"));
sw.Write(mnw.GetNodes());
sw.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
{
public abstract class FloatingPointTypeModelBinderTest<TFloatingPoint> where TFloatingPoint: struct
{
public static TheoryData<Type> ConvertibleTypeData
{
get
{
return new TheoryData<Type>
{
typeof(TFloatingPoint),
typeof(TFloatingPoint?),
};
}
}
protected abstract TFloatingPoint Twelve { get; }
protected abstract TFloatingPoint TwelvePointFive { get; }
protected abstract TFloatingPoint ThirtyTwoThousand { get; }
protected abstract TFloatingPoint ThirtyTwoThousandPointOne { get; }
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_ReturnsFailure_IfAttemptedValueCannotBeParsed(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", "some-value" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_CreatesError_IfAttemptedValueCannotBeParsed(Type destinationType)
{
// Arrange
var message = "The value 'not a number' is not valid.";
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", "not a number" },
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
Assert.False(bindingContext.ModelState.IsValid);
var error = Assert.Single(bindingContext.ModelState["theModelName"].Errors);
Assert.Equal(message, error.ErrorMessage);
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_CreatesError_IfAttemptedValueCannotBeCompletelyParsed(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("en-GB"))
{
{ "theModelName", "12_5" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
var error = Assert.Single(bindingContext.ModelState["theModelName"].Errors);
Assert.Equal("The value '12_5' is not valid.", error.ErrorMessage, StringComparer.Ordinal);
Assert.Null(error.Exception);
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_CreatesError_IfAttemptedValueContainsDisallowedWhitespace(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("en-GB"))
{
{ "theModelName", " 12" }
};
var binder = GetBinder(NumberStyles.Float & ~NumberStyles.AllowLeadingWhite);
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
var error = Assert.Single(bindingContext.ModelState["theModelName"].Errors);
Assert.Equal("The value ' 12' is not valid.", error.ErrorMessage, StringComparer.Ordinal);
Assert.Null(error.Exception);
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_CreatesError_IfAttemptedValueContainsDisallowedDecimal(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("en-GB"))
{
{ "theModelName", "12.5" }
};
var binder = GetBinder(NumberStyles.Float & ~NumberStyles.AllowDecimalPoint);
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
var error = Assert.Single(bindingContext.ModelState["theModelName"].Errors);
Assert.Equal("The value '12.5' is not valid.", error.ErrorMessage, StringComparer.Ordinal);
Assert.Null(error.Exception);
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_CreatesError_IfAttemptedValueContainsDisallowedThousandsSeparator(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("en-GB"))
{
{ "theModelName", "32,000" }
};
var binder = GetBinder(NumberStyles.Float);
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
var error = Assert.Single(bindingContext.ModelState["theModelName"].Errors);
Assert.Equal("The value '32,000' is not valid.", error.ErrorMessage, StringComparer.Ordinal);
Assert.Null(error.Exception);
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_ReturnsFailed_IfValueProviderEmpty(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.Equal(ModelBindingResult.Failed(), bindingContext.Result);
Assert.Empty(bindingContext.ModelState);
}
[Theory]
[InlineData("")]
[InlineData(" \t \r\n ")]
public async Task BindModel_CreatesError_IfTrimmedAttemptedValueIsEmpty_NonNullableDestination(string value)
{
// Arrange
var message = $"The value '{value}' is invalid.";
var bindingContext = GetBindingContext(typeof(TFloatingPoint));
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", value },
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
var error = Assert.Single(bindingContext.ModelState["theModelName"].Errors);
Assert.Equal(message, error.ErrorMessage, StringComparer.Ordinal);
Assert.Null(error.Exception);
}
[Theory]
[InlineData("")]
[InlineData(" \t \r\n ")]
public async Task BindModel_ReturnsNull_IfTrimmedAttemptedValueIsEmpty_NullableDestination(string value)
{
// Arrange
var bindingContext = GetBindingContext(typeof(TFloatingPoint?));
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", value }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.Null(bindingContext.Result.Model);
var entry = Assert.Single(bindingContext.ModelState);
Assert.Equal("theModelName", entry.Key);
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_ReturnsModel_IfAttemptedValueIsValid_Twelve(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", "12" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.Equal(Twelve, bindingContext.Result.Model);
Assert.True(bindingContext.ModelState.ContainsKey("theModelName"));
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
[ReplaceCulture("en-GB", "en-GB")]
public async Task BindModel_ReturnsModel_IfAttemptedValueIsValid_TwelvePointFive(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", "12.5" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.Equal(TwelvePointFive, bindingContext.Result.Model);
Assert.True(bindingContext.ModelState.ContainsKey("theModelName"));
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_ReturnsModel_IfAttemptedValueIsValid_FrenchTwelvePointFive(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("fr-FR"))
{
{ "theModelName", "12,5" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.Equal(TwelvePointFive, bindingContext.Result.Model);
Assert.True(bindingContext.ModelState.ContainsKey("theModelName"));
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_ReturnsModel_IfAttemptedValueIsValid_ThirtyTwoThousand(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("en-GB"))
{
{ "theModelName", "32,000" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.Equal(ThirtyTwoThousand, bindingContext.Result.Model);
Assert.True(bindingContext.ModelState.ContainsKey("theModelName"));
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_ReturnsModel_IfAttemptedValueIsValid_ThirtyTwoThousandPointOne(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("en-GB"))
{
{ "theModelName", "32,000.1" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.Equal(ThirtyTwoThousandPointOne, bindingContext.Result.Model);
Assert.True(bindingContext.ModelState.ContainsKey("theModelName"));
}
[Theory]
[MemberData(nameof(ConvertibleTypeData))]
public async Task BindModel_ReturnsModel_IfAttemptedValueIsValid_FrenchThirtyTwoThousandPointOne(Type destinationType)
{
// Arrange
var bindingContext = GetBindingContext(destinationType);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("fr-FR"))
{
{ "theModelName", "32000,1" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.Equal(ThirtyTwoThousandPointOne, bindingContext.Result.Model);
Assert.True(bindingContext.ModelState.ContainsKey("theModelName"));
}
protected abstract IModelBinder GetBinder(NumberStyles numberStyles);
private IModelBinder GetBinder()
{
return GetBinder(FloatingPointTypeModelBinderProvider.SupportedStyles);
}
private static DefaultModelBindingContext GetBindingContext(Type modelType)
{
return new DefaultModelBindingContext
{
ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(modelType),
ModelName = "theModelName",
ModelState = new ModelStateDictionary(),
ValueProvider = new SimpleValueProvider() // empty
};
}
private sealed class TestClass
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace MaterialDesignThemes.Wpf
{
/// <summary>
/// Defines how a data context is sourced for a dialog if a <see cref="FrameworkElement"/>
/// is passed as the command parameter when using <see cref="DialogHost.OpenDialogCommand"/>.
/// </summary>
public enum DialogHostOpenDialogCommandDataContextSource
{
/// <summary>
/// The data context from the sender element (typically a <see cref="Button"/>)
/// is applied to the content.
/// </summary>
SenderElement,
/// <summary>
/// The data context from the <see cref="DialogHost"/> is applied to the content.
/// </summary>
DialogHostInstance,
/// <summary>
/// The data context is explicitly set to <c>null</c>.
/// </summary>
None
}
[TemplatePart(Name = PopupPartName, Type = typeof(Popup))]
[TemplatePart(Name = PopupPartName, Type = typeof(ContentControl))]
[TemplatePart(Name = ContentCoverGridName, Type = typeof(Grid))]
[TemplateVisualState(GroupName = "PopupStates", Name = OpenStateName)]
[TemplateVisualState(GroupName = "PopupStates", Name = ClosedStateName)]
public class DialogHost : ContentControl
{
public const string PopupPartName = "PART_Popup";
public const string PopupContentPartName = "PART_PopupContentElement";
public const string ContentCoverGridName = "PART_ContentCoverGrid";
public const string OpenStateName = "Open";
public const string ClosedStateName = "Closed";
/// <summary>
/// Routed command to be used somewhere inside an instance to trigger showing of the dialog. Content can be passed to the dialog via a <see cref="Button.CommandParameter"/>.
/// </summary>
public static readonly RoutedCommand OpenDialogCommand = new();
/// <summary>
/// Routed command to be used inside dialog content to close a dialog. Use a <see cref="Button.CommandParameter"/> to indicate the result of the parameter.
/// </summary>
public static readonly RoutedCommand CloseDialogCommand = new();
private static readonly HashSet<DialogHost> LoadedInstances = new();
private DialogOpenedEventHandler? _asyncShowOpenedEventHandler;
private DialogClosingEventHandler? _asyncShowClosingEventHandler;
private TaskCompletionSource<object?>? _dialogTaskCompletionSource;
private Popup? _popup;
private ContentControl? _popupContentControl;
private Grid? _contentCoverGrid;
private DialogOpenedEventHandler? _attachedDialogOpenedEventHandler;
private DialogClosingEventHandler? _attachedDialogClosingEventHandler;
private IInputElement? _restoreFocusDialogClose;
private Action? _currentSnackbarMessageQueueUnPauseAction;
static DialogHost()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DialogHost), new FrameworkPropertyMetadata(typeof(DialogHost)));
}
#region Show overloads
/// <summary>
/// Shows a modal dialog. To use, a <see cref="DialogHost"/> instance must be in a visual tree (typically this may be specified towards the root of a Window's XAML).
/// </summary>
/// <param name="content">Content to show (can be a control or view model).</param>
/// <returns>Task result is the parameter used to close the dialog, typically what is passed to the <see cref="CloseDialogCommand"/> command.</returns>
public static async Task<object?> Show(object content)
=> await Show(content, null, null);
/// <summary>
/// Shows a modal dialog. To use, a <see cref="DialogHost"/> instance must be in a visual tree (typically this may be specified towards the root of a Window's XAML).
/// </summary>
/// <param name="content">Content to show (can be a control or view model).</param>
/// <param name="openedEventHandler">Allows access to opened event which would otherwise have been subscribed to on a instance.</param>
/// <returns>Task result is the parameter used to close the dialog, typically what is passed to the <see cref="CloseDialogCommand"/> command.</returns>
public static async Task<object?> Show(object content, DialogOpenedEventHandler openedEventHandler)
=> await Show(content, null, openedEventHandler, null);
/// <summary>
/// Shows a modal dialog. To use, a <see cref="DialogHost"/> instance must be in a visual tree (typically this may be specified towards the root of a Window's XAML).
/// </summary>
/// <param name="content">Content to show (can be a control or view model).</param>
/// <param name="closingEventHandler">Allows access to closing event which would otherwise have been subscribed to on a instance.</param>
/// <returns>Task result is the parameter used to close the dialog, typically what is passed to the <see cref="CloseDialogCommand"/> command.</returns>
public static async Task<object?> Show(object content, DialogClosingEventHandler closingEventHandler)
=> await Show(content, null, null, closingEventHandler);
/// <summary>
/// Shows a modal dialog. To use, a <see cref="DialogHost"/> instance must be in a visual tree (typically this may be specified towards the root of a Window's XAML).
/// </summary>
/// <param name="content">Content to show (can be a control or view model).</param>
/// <param name="openedEventHandler">Allows access to opened event which would otherwise have been subscribed to on a instance.</param>
/// <param name="closingEventHandler">Allows access to closing event which would otherwise have been subscribed to on a instance.</param>
/// <returns>Task result is the parameter used to close the dialog, typically what is passed to the <see cref="CloseDialogCommand"/> command.</returns>
public static async Task<object?> Show(object content, DialogOpenedEventHandler? openedEventHandler, DialogClosingEventHandler? closingEventHandler)
=> await Show(content, null, openedEventHandler, closingEventHandler);
/// <summary>
/// Shows a modal dialog. To use, a <see cref="DialogHost"/> instance must be in a visual tree (typically this may be specified towards the root of a Window's XAML).
/// </summary>
/// <param name="content">Content to show (can be a control or view model).</param>
/// <param name="dialogIdentifier"><see cref="Identifier"/> of the instance where the dialog should be shown. Typically this will match an identifer set in XAML. <c>null</c> is allowed.</param>
/// <returns>Task result is the parameter used to close the dialog, typically what is passed to the <see cref="CloseDialogCommand"/> command.</returns>
public static async Task<object?> Show(object content, object dialogIdentifier)
=> await Show(content, dialogIdentifier, null, null);
/// <summary>
/// Shows a modal dialog. To use, a <see cref="DialogHost"/> instance must be in a visual tree (typically this may be specified towards the root of a Window's XAML).
/// </summary>
/// <param name="content">Content to show (can be a control or view model).</param>
/// <param name="dialogIdentifier"><see cref="Identifier"/> of the instance where the dialog should be shown. Typically this will match an identifer set in XAML. <c>null</c> is allowed.</param>
/// <param name="openedEventHandler">Allows access to opened event which would otherwise have been subscribed to on a instance.</param>
/// <returns>Task result is the parameter used to close the dialog, typically what is passed to the <see cref="CloseDialogCommand"/> command.</returns>
public static Task<object?> Show(object content, object dialogIdentifier, DialogOpenedEventHandler openedEventHandler)
=> Show(content, dialogIdentifier, openedEventHandler, null);
/// <summary>
/// Shows a modal dialog. To use, a <see cref="DialogHost"/> instance must be in a visual tree (typically this may be specified towards the root of a Window's XAML).
/// </summary>
/// <param name="content">Content to show (can be a control or view model).</param>
/// <param name="dialogIdentifier"><see cref="Identifier"/> of the instance where the dialog should be shown. Typically this will match an identifer set in XAML. <c>null</c> is allowed.</param>
/// <param name="closingEventHandler">Allows access to closing event which would otherwise have been subscribed to on a instance.</param>
/// <returns>Task result is the parameter used to close the dialog, typically what is passed to the <see cref="CloseDialogCommand"/> command.</returns>
public static Task<object?> Show(object content, object dialogIdentifier, DialogClosingEventHandler closingEventHandler)
=> Show(content, dialogIdentifier, null, closingEventHandler);
/// <summary>
/// Shows a modal dialog. To use, a <see cref="DialogHost"/> instance must be in a visual tree (typically this may be specified towards the root of a Window's XAML).
/// </summary>
/// <param name="content">Content to show (can be a control or view model).</param>
/// <param name="dialogIdentifier"><see cref="Identifier"/> of the instance where the dialog should be shown. Typically this will match an identifer set in XAML. <c>null</c> is allowed.</param>
/// <param name="openedEventHandler">Allows access to opened event which would otherwise have been subscribed to on a instance.</param>
/// <param name="closingEventHandler">Allows access to closing event which would otherwise have been subscribed to on a instance.</param>
/// <returns>Task result is the parameter used to close the dialog, typically what is passed to the <see cref="CloseDialogCommand"/> command.</returns>
public static async Task<object?> Show(object content, object? dialogIdentifier, DialogOpenedEventHandler? openedEventHandler, DialogClosingEventHandler? closingEventHandler)
{
if (content is null) throw new ArgumentNullException(nameof(content));
return await GetInstance(dialogIdentifier).ShowInternal(content, openedEventHandler, closingEventHandler);
}
/// <summary>
/// Close a modal dialog.
/// </summary>
/// <param name="dialogIdentifier"> of the instance where the dialog should be closed. Typically this will match an identifer set in XAML. </param>
public static void Close(object dialogIdentifier)
=> Close(dialogIdentifier, null);
/// <summary>
/// Close a modal dialog.
/// </summary>
/// <param name="dialogIdentifier"> of the instance where the dialog should be closed. Typically this will match an identifer set in XAML. </param>
/// <param name="parameter"> to provide to close handler</param>
public static void Close(object? dialogIdentifier, object? parameter)
{
DialogHost dialogHost = GetInstance(dialogIdentifier);
if (dialogHost.CurrentSession is { } currentSession)
{
currentSession.Close(parameter);
return;
}
throw new InvalidOperationException("DialogHost is not open.");
}
/// <summary>
/// Retrieve the current dialog session for a DialogHost
/// </summary>
/// <param name="dialogIdentifier">The identifier to use to retrieve the DialogHost</param>
/// <returns>The DialogSession if one is in process, or null</returns>
public static DialogSession? GetDialogSession(object dialogIdentifier)
{
DialogHost dialogHost = GetInstance(dialogIdentifier);
return dialogHost.CurrentSession;
}
/// <summary>
/// dialog instance exists
/// </summary>
/// <param name="dialogIdentifier">of the instance where the dialog should be closed. Typically this will match an identifer set in XAML.</param>
/// <returns></returns>
public static bool IsDialogOpen(object dialogIdentifier) => GetDialogSession(dialogIdentifier)?.IsEnded == false;
private static DialogHost GetInstance(object? dialogIdentifier)
{
if (LoadedInstances.Count == 0)
throw new InvalidOperationException("No loaded DialogHost instances.");
LoadedInstances.First().Dispatcher.VerifyAccess();
var targets = LoadedInstances.Where(dh => dialogIdentifier == null || Equals(dh.Identifier, dialogIdentifier)).ToList();
if (targets.Count == 0)
throw new InvalidOperationException($"No loaded DialogHost have an {nameof(Identifier)} property matching {nameof(dialogIdentifier)} ('{dialogIdentifier}') argument.");
if (targets.Count > 1)
throw new InvalidOperationException("Multiple viable DialogHosts. Specify a unique Identifier on each DialogHost, especially where multiple Windows are a concern.");
return targets[0];
}
internal async Task<object?> ShowInternal(object content, DialogOpenedEventHandler? openedEventHandler, DialogClosingEventHandler? closingEventHandler)
{
if (IsOpen)
throw new InvalidOperationException("DialogHost is already open.");
_dialogTaskCompletionSource = new TaskCompletionSource<object?>();
AssertTargetableContent();
if (content != null)
DialogContent = content;
_asyncShowOpenedEventHandler = openedEventHandler;
_asyncShowClosingEventHandler = closingEventHandler;
SetCurrentValue(IsOpenProperty, true);
object? result = await _dialogTaskCompletionSource.Task;
_asyncShowOpenedEventHandler = null;
_asyncShowClosingEventHandler = null;
return result;
}
#endregion
public DialogHost()
{
Loaded += OnLoaded;
Unloaded += OnUnloaded;
CommandBindings.Add(new CommandBinding(CloseDialogCommand, CloseDialogHandler, CloseDialogCanExecute));
CommandBindings.Add(new CommandBinding(OpenDialogCommand, OpenDialogHandler));
}
public static readonly DependencyProperty IdentifierProperty = DependencyProperty.Register(
nameof(Identifier), typeof(object), typeof(DialogHost), new PropertyMetadata(default(object)));
/// <summary>
/// Identifier which is used in conjunction with <see cref="Show(object)"/> to determine where a dialog should be shown.
/// </summary>
public object? Identifier
{
get => GetValue(IdentifierProperty);
set => SetValue(IdentifierProperty, value);
}
public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register(
nameof(IsOpen), typeof(bool), typeof(DialogHost), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsOpenPropertyChangedCallback));
private static void IsOpenPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var dialogHost = (DialogHost)dependencyObject;
if (dialogHost._popupContentControl != null)
ValidationAssist.SetSuppress(dialogHost._popupContentControl, !dialogHost.IsOpen);
VisualStateManager.GoToState(dialogHost, dialogHost.GetStateName(), !TransitionAssist.GetDisableTransitions(dialogHost));
if (dialogHost.IsOpen)
{
dialogHost._currentSnackbarMessageQueueUnPauseAction = dialogHost.SnackbarMessageQueue?.Pause();
}
else
{
dialogHost._attachedDialogClosingEventHandler = null;
if (dialogHost._currentSnackbarMessageQueueUnPauseAction != null)
{
dialogHost._currentSnackbarMessageQueueUnPauseAction();
dialogHost._currentSnackbarMessageQueueUnPauseAction = null;
}
object? closeParameter = null;
if (dialogHost.CurrentSession is { } session)
{
if (!session.IsEnded)
{
session.Close(session.CloseParameter);
}
//DialogSession.Close may attempt to cancel the closing of the dialog.
//When the dialog is closed in this manner it is not valid
if (!session.IsEnded)
{
throw new InvalidOperationException($"Cannot cancel dialog closing after {nameof(IsOpen)} property has been set to {bool.FalseString}");
}
closeParameter = session.CloseParameter;
dialogHost.CurrentSession = null;
}
//NB: _dialogTaskCompletionSource is only set in the case where the dialog is shown with Show
dialogHost._dialogTaskCompletionSource?.TrySetResult(closeParameter);
// Don't attempt to Invoke if _restoreFocusDialogClose hasn't been assigned yet. Can occur
// if the MainWindow has started up minimized. Even when Show() has been called, this doesn't
// seem to have been set.
dialogHost.Dispatcher.InvokeAsync(() => dialogHost._restoreFocusDialogClose?.Focus(), DispatcherPriority.Input);
return;
}
dialogHost.CurrentSession = new DialogSession(dialogHost);
var window = Window.GetWindow(dialogHost);
dialogHost._restoreFocusDialogClose = window != null ? FocusManager.GetFocusedElement(window) : null;
//multiple ways of calling back that the dialog has opened:
// * routed event
// * the attached property (which should be applied to the button which opened the dialog
// * straight forward dependency property
// * handler provided to the async show method
var dialogOpenedEventArgs = new DialogOpenedEventArgs(dialogHost.CurrentSession, DialogOpenedEvent);
dialogHost.OnDialogOpened(dialogOpenedEventArgs);
dialogHost._attachedDialogOpenedEventHandler?.Invoke(dialogHost, dialogOpenedEventArgs);
dialogHost.DialogOpenedCallback?.Invoke(dialogHost, dialogOpenedEventArgs);
dialogHost._asyncShowOpenedEventHandler?.Invoke(dialogHost, dialogOpenedEventArgs);
dialogHost.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
CommandManager.InvalidateRequerySuggested();
UIElement? child = dialogHost.FocusPopup();
if (child != null)
{
//https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit/issues/187
//totally not happy about this, but on immediate validation we can get some weird looking stuff...give WPF a kick to refresh...
Task.Delay(300).ContinueWith(t => child.Dispatcher.BeginInvoke(new Action(() => child.InvalidateVisual())));
}
}));
}
/// <summary>
/// Returns a DialogSession for the currently open dialog for managing it programmatically. If no dialog is open, CurrentSession will return null
/// </summary>
public DialogSession? CurrentSession { get; private set; }
public bool IsOpen
{
get => (bool)GetValue(IsOpenProperty);
set => SetValue(IsOpenProperty, value);
}
public static readonly DependencyProperty DialogContentProperty = DependencyProperty.Register(
nameof(DialogContent), typeof(object), typeof(DialogHost), new PropertyMetadata(default(object)));
public object? DialogContent
{
get => GetValue(DialogContentProperty);
set => SetValue(DialogContentProperty, value);
}
public static readonly DependencyProperty DialogContentTemplateProperty = DependencyProperty.Register(
nameof(DialogContentTemplate), typeof(DataTemplate), typeof(DialogHost), new PropertyMetadata(default(DataTemplate)));
public DataTemplate? DialogContentTemplate
{
get => (DataTemplate?)GetValue(DialogContentTemplateProperty);
set => SetValue(DialogContentTemplateProperty, value);
}
public static readonly DependencyProperty DialogContentTemplateSelectorProperty = DependencyProperty.Register(
nameof(DialogContentTemplateSelector), typeof(DataTemplateSelector), typeof(DialogHost), new PropertyMetadata(default(DataTemplateSelector)));
public DataTemplateSelector? DialogContentTemplateSelector
{
get => (DataTemplateSelector?)GetValue(DialogContentTemplateSelectorProperty);
set => SetValue(DialogContentTemplateSelectorProperty, value);
}
public static readonly DependencyProperty DialogContentStringFormatProperty = DependencyProperty.Register(
nameof(DialogContentStringFormat), typeof(string), typeof(DialogHost), new PropertyMetadata(default(string)));
public string? DialogContentStringFormat
{
get => (string?)GetValue(DialogContentStringFormatProperty);
set => SetValue(DialogContentStringFormatProperty, value);
}
public static readonly DependencyProperty DialogMarginProperty = DependencyProperty.Register(
"DialogMargin", typeof(Thickness), typeof(DialogHost), new PropertyMetadata(default(Thickness)));
public Thickness DialogMargin
{
get => (Thickness)GetValue(DialogMarginProperty);
set => SetValue(DialogMarginProperty, value);
}
public static readonly DependencyProperty OpenDialogCommandDataContextSourceProperty = DependencyProperty.Register(
nameof(OpenDialogCommandDataContextSource), typeof(DialogHostOpenDialogCommandDataContextSource), typeof(DialogHost), new PropertyMetadata(default(DialogHostOpenDialogCommandDataContextSource)));
/// <summary>
/// Defines how a data context is sourced for a dialog if a <see cref="FrameworkElement"/>
/// is passed as the command parameter when using <see cref="DialogHost.OpenDialogCommand"/>.
/// </summary>
public DialogHostOpenDialogCommandDataContextSource OpenDialogCommandDataContextSource
{
get => (DialogHostOpenDialogCommandDataContextSource)GetValue(OpenDialogCommandDataContextSourceProperty);
set => SetValue(OpenDialogCommandDataContextSourceProperty, value);
}
public static readonly DependencyProperty CloseOnClickAwayProperty = DependencyProperty.Register(
"CloseOnClickAway", typeof(bool), typeof(DialogHost), new PropertyMetadata(default(bool)));
/// <summary>
/// Indicates whether the dialog will close if the user clicks off the dialog, on the obscured background.
/// </summary>
public bool CloseOnClickAway
{
get => (bool)GetValue(CloseOnClickAwayProperty);
set => SetValue(CloseOnClickAwayProperty, value);
}
public static readonly DependencyProperty CloseOnClickAwayParameterProperty = DependencyProperty.Register(
"CloseOnClickAwayParameter", typeof(object), typeof(DialogHost), new PropertyMetadata(default(object)));
/// <summary>
/// Parameter to provide to close handlers if an close due to click away is instigated.
/// </summary>
public object? CloseOnClickAwayParameter
{
get => GetValue(CloseOnClickAwayParameterProperty);
set => SetValue(CloseOnClickAwayParameterProperty, value);
}
public static readonly DependencyProperty SnackbarMessageQueueProperty = DependencyProperty.Register(
"SnackbarMessageQueue", typeof(SnackbarMessageQueue), typeof(DialogHost), new PropertyMetadata(default(SnackbarMessageQueue), SnackbarMessageQueuePropertyChangedCallback));
private static void SnackbarMessageQueuePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var dialogHost = (DialogHost)dependencyObject;
if (dialogHost._currentSnackbarMessageQueueUnPauseAction != null)
{
dialogHost._currentSnackbarMessageQueueUnPauseAction();
dialogHost._currentSnackbarMessageQueueUnPauseAction = null;
}
if (!dialogHost.IsOpen) return;
var snackbarMessageQueue = dependencyPropertyChangedEventArgs.NewValue as SnackbarMessageQueue;
dialogHost._currentSnackbarMessageQueueUnPauseAction = snackbarMessageQueue?.Pause();
}
/// <summary>
/// Allows association of a snackbar, so that notifications can be paused whilst a dialog is being displayed.
/// </summary>
public SnackbarMessageQueue? SnackbarMessageQueue
{
get => (SnackbarMessageQueue?)GetValue(SnackbarMessageQueueProperty);
set => SetValue(SnackbarMessageQueueProperty, value);
}
public static readonly DependencyProperty DialogThemeProperty =
DependencyProperty.Register(nameof(DialogTheme), typeof(BaseTheme), typeof(DialogHost), new PropertyMetadata(default(BaseTheme)));
/// <summary>
/// Set the theme (light/dark) for the dialog.
/// </summary>
public BaseTheme DialogTheme
{
get => (BaseTheme)GetValue(DialogThemeProperty);
set => SetValue(DialogThemeProperty, value);
}
public static readonly DependencyProperty PopupStyleProperty = DependencyProperty.Register(
nameof(PopupStyle), typeof(Style), typeof(DialogHost), new PropertyMetadata(default(Style)));
public Style? PopupStyle
{
get => (Style?)GetValue(PopupStyleProperty);
set => SetValue(PopupStyleProperty, value);
}
public static readonly DependencyProperty OverlayBackgroundProperty = DependencyProperty.Register(
nameof(OverlayBackground), typeof(Brush), typeof(DialogHost), new PropertyMetadata(Brushes.Black));
/// <summary>
/// Represents the overlay brush that is used to dim the background behind the dialog
/// </summary>
public Brush? OverlayBackground
{
get => (Brush?)GetValue(OverlayBackgroundProperty);
set => SetValue(OverlayBackgroundProperty, value);
}
public override void OnApplyTemplate()
{
if (_contentCoverGrid != null)
_contentCoverGrid.MouseLeftButtonUp -= ContentCoverGridOnMouseLeftButtonUp;
_popup = GetTemplateChild(PopupPartName) as Popup;
_popupContentControl = GetTemplateChild(PopupContentPartName) as ContentControl;
_contentCoverGrid = GetTemplateChild(ContentCoverGridName) as Grid;
if (_contentCoverGrid != null)
_contentCoverGrid.MouseLeftButtonUp += ContentCoverGridOnMouseLeftButtonUp;
VisualStateManager.GoToState(this, GetStateName(), false);
base.OnApplyTemplate();
}
#region open dialog events/callbacks
public static readonly RoutedEvent DialogOpenedEvent =
EventManager.RegisterRoutedEvent(
"DialogOpened",
RoutingStrategy.Bubble,
typeof(DialogOpenedEventHandler),
typeof(DialogHost));
/// <summary>
/// Raised when a dialog is opened.
/// </summary>
public event DialogOpenedEventHandler DialogOpened
{
add { AddHandler(DialogOpenedEvent, value); }
remove { RemoveHandler(DialogOpenedEvent, value); }
}
/// <summary>
/// Attached property which can be used on the <see cref="Button"/> which instigated the <see cref="OpenDialogCommand"/> to process the event.
/// </summary>
public static readonly DependencyProperty DialogOpenedAttachedProperty = DependencyProperty.RegisterAttached(
"DialogOpenedAttached", typeof(DialogOpenedEventHandler), typeof(DialogHost), new PropertyMetadata(default(DialogOpenedEventHandler)));
public static void SetDialogOpenedAttached(DependencyObject element, DialogOpenedEventHandler value)
=> element.SetValue(DialogOpenedAttachedProperty, value);
public static DialogOpenedEventHandler GetDialogOpenedAttached(DependencyObject element)
=> (DialogOpenedEventHandler)element.GetValue(DialogOpenedAttachedProperty);
public static readonly DependencyProperty DialogOpenedCallbackProperty = DependencyProperty.Register(
nameof(DialogOpenedCallback), typeof(DialogOpenedEventHandler), typeof(DialogHost), new PropertyMetadata(default(DialogOpenedEventHandler)));
/// <summary>
/// Callback fired when the <see cref="DialogOpened"/> event is fired, allowing the event to be processed from a binding/view model.
/// </summary>
public DialogOpenedEventHandler? DialogOpenedCallback
{
get => (DialogOpenedEventHandler?)GetValue(DialogOpenedCallbackProperty);
set => SetValue(DialogOpenedCallbackProperty, value);
}
protected void OnDialogOpened(DialogOpenedEventArgs eventArgs)
=> RaiseEvent(eventArgs);
#endregion
#region close dialog events/callbacks
public static readonly RoutedEvent DialogClosingEvent =
EventManager.RegisterRoutedEvent(
"DialogClosing",
RoutingStrategy.Bubble,
typeof(DialogClosingEventHandler),
typeof(DialogHost));
/// <summary>
/// Raised just before a dialog is closed.
/// </summary>
public event DialogClosingEventHandler DialogClosing
{
add { AddHandler(DialogClosingEvent, value); }
remove { RemoveHandler(DialogClosingEvent, value); }
}
/// <summary>
/// Attached property which can be used on the <see cref="Button"/> which instigated the <see cref="OpenDialogCommand"/> to process the closing event.
/// </summary>
public static readonly DependencyProperty DialogClosingAttachedProperty = DependencyProperty.RegisterAttached(
"DialogClosingAttached", typeof(DialogClosingEventHandler), typeof(DialogHost), new PropertyMetadata(default(DialogClosingEventHandler)));
public static void SetDialogClosingAttached(DependencyObject element, DialogClosingEventHandler value)
=> element.SetValue(DialogClosingAttachedProperty, value);
public static DialogClosingEventHandler GetDialogClosingAttached(DependencyObject element)
=> (DialogClosingEventHandler)element.GetValue(DialogClosingAttachedProperty);
public static readonly DependencyProperty DialogClosingCallbackProperty = DependencyProperty.Register(
nameof(DialogClosingCallback), typeof(DialogClosingEventHandler), typeof(DialogHost), new PropertyMetadata(default(DialogClosingEventHandler)));
/// <summary>
/// Callback fired when the <see cref="DialogClosing"/> event is fired, allowing the event to be processed from a binding/view model.
/// </summary>
public DialogClosingEventHandler? DialogClosingCallback
{
get => (DialogClosingEventHandler?)GetValue(DialogClosingCallbackProperty);
set => SetValue(DialogClosingCallbackProperty, value);
}
protected void OnDialogClosing(DialogClosingEventArgs eventArgs)
=> RaiseEvent(eventArgs);
#endregion
internal void AssertTargetableContent()
{
var existingBinding = BindingOperations.GetBindingExpression(this, DialogContentProperty);
if (existingBinding != null)
throw new InvalidOperationException(
"Content cannot be passed to a dialog via the OpenDialog if DialogContent already has a binding.");
}
internal void InternalClose(object? parameter)
{
var currentSession = CurrentSession ?? throw new InvalidOperationException($"{nameof(DialogHost)} does not have a current session");
currentSession.CloseParameter = parameter;
currentSession.IsEnded = true;
//multiple ways of calling back that the dialog is closing:
// * routed event
// * the attached property (which should be applied to the button which opened the dialog
// * straight forward IsOpen dependency property
// * handler provided to the async show method
var dialogClosingEventArgs = new DialogClosingEventArgs(currentSession, DialogClosingEvent);
OnDialogClosing(dialogClosingEventArgs);
_attachedDialogClosingEventHandler?.Invoke(this, dialogClosingEventArgs);
DialogClosingCallback?.Invoke(this, dialogClosingEventArgs);
_asyncShowClosingEventHandler?.Invoke(this, dialogClosingEventArgs);
if (dialogClosingEventArgs.IsCancelled)
{
currentSession.IsEnded = false;
return;
}
SetCurrentValue(IsOpenProperty, false);
}
/// <summary>
/// Attempts to focus the content of a popup.
/// </summary>
/// <returns>The popup content.</returns>
internal UIElement? FocusPopup()
{
var child = _popup?.Child ?? _popupContentControl;
if (child is null) return null;
CommandManager.InvalidateRequerySuggested();
var focusable = child.VisualDepthFirstTraversal().OfType<UIElement>().FirstOrDefault(ui => ui.Focusable && ui.IsVisible);
focusable?.Dispatcher.InvokeAsync(() =>
{
if (!focusable.Focus()) return;
focusable.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
}, DispatcherPriority.Background);
return child;
}
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
var window = Window.GetWindow(this);
if (window != null && !window.IsActive)
window.Activate();
base.OnPreviewMouseDown(e);
}
private void ContentCoverGridOnMouseLeftButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
if (CloseOnClickAway && CurrentSession != null)
InternalClose(CloseOnClickAwayParameter);
}
private void OpenDialogHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
{
if (executedRoutedEventArgs.Handled) return;
if (executedRoutedEventArgs.OriginalSource is DependencyObject dependencyObject)
{
_attachedDialogOpenedEventHandler = GetDialogOpenedAttached(dependencyObject);
_attachedDialogClosingEventHandler = GetDialogClosingAttached(dependencyObject);
}
if (executedRoutedEventArgs.Parameter != null)
{
AssertTargetableContent();
if (_popupContentControl != null)
{
_popupContentControl.DataContext = OpenDialogCommandDataContextSource switch
{
DialogHostOpenDialogCommandDataContextSource.SenderElement
=> (executedRoutedEventArgs.OriginalSource as FrameworkElement)?.DataContext,
DialogHostOpenDialogCommandDataContextSource.DialogHostInstance => DataContext,
DialogHostOpenDialogCommandDataContextSource.None => null,
_ => throw new ArgumentOutOfRangeException(),
};
}
DialogContent = executedRoutedEventArgs.Parameter;
}
SetCurrentValue(IsOpenProperty, true);
executedRoutedEventArgs.Handled = true;
}
private void CloseDialogCanExecute(object sender, CanExecuteRoutedEventArgs canExecuteRoutedEventArgs)
=> canExecuteRoutedEventArgs.CanExecute = CurrentSession != null;
private void CloseDialogHandler(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
{
if (executedRoutedEventArgs.Handled) return;
InternalClose(executedRoutedEventArgs.Parameter);
executedRoutedEventArgs.Handled = true;
}
private string GetStateName()
=> IsOpen ? OpenStateName : ClosedStateName;
private void OnUnloaded(object sender, RoutedEventArgs routedEventArgs)
=> LoadedInstances.Remove(this);
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
=> LoadedInstances.Add(this);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
public static partial class PublicIPAddressesOperationsExtensions
{
/// <summary>
/// The delete publicIpAddress operation deletes the specified publicIpAddress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
public static void Delete(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName)
{
Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).DeleteAsync(resourceGroupName, publicIpAddressName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete publicIpAddress operation deletes the specified publicIpAddress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync( this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The delete publicIpAddress operation deletes the specified publicIpAddress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
public static void BeginDelete(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName)
{
Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).BeginDeleteAsync(resourceGroupName, publicIpAddressName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete publicIpAddress operation deletes the specified publicIpAddress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync( this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Get publicIpAddress operation retreives information about the
/// specified pubicIpAddress
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
public static PublicIPAddress Get(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, string expand = default(string))
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).GetAsync(resourceGroupName, publicIpAddressName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get publicIpAddress operation retreives information about the
/// specified pubicIpAddress
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublicIPAddress> GetAsync( this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<PublicIPAddress> result = await operations.GetWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, expand, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The Put PublicIPAddress operation creates/updates a stable/dynamic
/// PublicIP address
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the publicIpAddress.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update PublicIPAddress operation
/// </param>
public static PublicIPAddress CreateOrUpdate(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).CreateOrUpdateAsync(resourceGroupName, publicIpAddressName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put PublicIPAddress operation creates/updates a stable/dynamic
/// PublicIP address
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the publicIpAddress.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update PublicIPAddress operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublicIPAddress> CreateOrUpdateAsync( this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<PublicIPAddress> result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The Put PublicIPAddress operation creates/updates a stable/dynamic
/// PublicIP address
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the publicIpAddress.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update PublicIPAddress operation
/// </param>
public static PublicIPAddress BeginCreateOrUpdate(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, publicIpAddressName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put PublicIPAddress operation creates/updates a stable/dynamic
/// PublicIP address
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the publicIpAddress.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update PublicIPAddress operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublicIPAddress> BeginCreateOrUpdateAsync( this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<PublicIPAddress> result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List publicIpAddress opertion retrieves all the publicIpAddresses in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<PublicIPAddress> ListAll(this IPublicIPAddressesOperations operations)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List publicIpAddress opertion retrieves all the publicIpAddresses in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublicIPAddress>> ListAllAsync( this IPublicIPAddressesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<PublicIPAddress>> result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List publicIpAddress opertion retrieves all the publicIpAddresses in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<PublicIPAddress> List(this IPublicIPAddressesOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List publicIpAddress opertion retrieves all the publicIpAddresses in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublicIPAddress>> ListAsync( this IPublicIPAddressesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<PublicIPAddress>> result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List publicIpAddress opertion retrieves all the publicIpAddresses in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<PublicIPAddress> ListAllNext(this IPublicIPAddressesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List publicIpAddress opertion retrieves all the publicIpAddresses in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublicIPAddress>> ListAllNextAsync( this IPublicIPAddressesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<PublicIPAddress>> result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List publicIpAddress opertion retrieves all the publicIpAddresses in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<PublicIPAddress> ListNext(this IPublicIPAddressesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPublicIPAddressesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List publicIpAddress opertion retrieves all the publicIpAddresses in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublicIPAddress>> ListNextAsync( this IPublicIPAddressesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<PublicIPAddress>> result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
}
}
| |
/*
* 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 log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Xml;
namespace OpenSim.Framework
{
public class RegionLightShareData : ICloneable
{
public bool valid = false;
public UUID regionID = UUID.Zero;
public Vector3 waterColor = new Vector3(4.0f,38.0f,64.0f);
public float waterFogDensityExponent = 4.0f;
public float underwaterFogModifier = 0.25f;
public Vector3 reflectionWaveletScale = new Vector3(2.0f,2.0f,2.0f);
public float fresnelScale = 0.40f;
public float fresnelOffset = 0.50f;
public float refractScaleAbove = 0.03f;
public float refractScaleBelow = 0.20f;
public float blurMultiplier = 0.040f;
public Vector2 bigWaveDirection = new Vector2(1.05f,-0.42f);
public Vector2 littleWaveDirection = new Vector2(1.11f,-1.16f);
public UUID normalMapTexture = new UUID("822ded49-9a6c-f61c-cb89-6df54f42cdf4");
public Vector4 horizon = new Vector4(0.25f, 0.25f, 0.32f, 0.32f);
public float hazeHorizon = 0.19f;
public Vector4 blueDensity = new Vector4(0.12f, 0.22f, 0.38f, 0.38f);
public float hazeDensity = 0.70f;
public float densityMultiplier = 0.18f;
public float distanceMultiplier = 0.8f;
public UInt16 maxAltitude = 1605;
public Vector4 sunMoonColor = new Vector4(0.24f, 0.26f, 0.30f, 0.30f);
public float sunMoonPosition = 0.317f;
public Vector4 ambient = new Vector4(0.35f,0.35f,0.35f,0.35f);
public float eastAngle = 0.0f;
public float sunGlowFocus = 0.10f;
public float sunGlowSize = 1.75f;
public float sceneGamma = 1.0f;
public float starBrightness = 0.0f;
public Vector4 cloudColor = new Vector4(0.41f, 0.41f, 0.41f, 0.41f);
public Vector3 cloudXYDensity = new Vector3(1.00f, 0.53f, 1.00f);
public float cloudCoverage = 0.27f;
public float cloudScale = 0.42f;
public Vector3 cloudDetailXYDensity = new Vector3(1.00f, 0.53f, 0.12f);
public float cloudScrollX = 0.20f;
public bool cloudScrollXLock = false;
public float cloudScrollY = 0.01f;
public bool cloudScrollYLock = false;
public bool drawClassicClouds = true;
public delegate void SaveDelegate(RegionLightShareData wl);
public event SaveDelegate OnSave;
public void Save()
{
if (OnSave != null)
OnSave(this);
}
public object Clone()
{
return this.MemberwiseClone(); // call clone method
}
}
public class RegionInfo
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[REGION INFO]";
public bool commFailTF = false;
public string RegionFile = String.Empty;
public bool isSandbox = false;
public bool Persistent = true;
private EstateSettings m_estateSettings;
private RegionSettings m_regionSettings;
// private IConfigSource m_configSource = null;
public UUID originRegionID = UUID.Zero;
public string proxyUrl = "";
public int ProxyOffset = 0;
public string regionSecret = UUID.Random().ToString();
public string osSecret;
public UUID lastMapUUID = UUID.Zero;
public string lastMapRefresh = "0";
private float m_nonphysPrimMin = 0;
private int m_nonphysPrimMax = 0;
private float m_physPrimMin = 0;
private int m_physPrimMax = 0;
private bool m_clampPrimSize = false;
private int m_objectCapacity = 0;
private int m_maxPrimsPerUser = -1;
private int m_linksetCapacity = 0;
private int m_agentCapacity = 0;
private string m_regionType = String.Empty;
private RegionLightShareData m_windlight = new RegionLightShareData();
protected uint m_httpPort;
protected string m_serverURI;
protected string m_regionName = String.Empty;
protected bool Allow_Alternate_Ports;
public bool m_allow_alternate_ports;
private string m_externalHostName;
private string m_lastExternalHostName = string.Empty;
private bool m_IPChanged = false;
private bool m_CheckDynDns = false;
protected DateTime m_lastResolverTime;
protected IPEndPoint m_internalEndPoint;
protected uint m_remotingPort;
public UUID RegionID = UUID.Zero;
public string RemotingAddress;
public UUID ScopeID = UUID.Zero;
private UUID m_maptileStaticUUID = UUID.Zero;
public uint WorldLocX = 0;
public uint WorldLocY = 0;
public uint WorldLocZ = 0;
public uint RegionSizeX = Constants.RegionSize;
public uint RegionSizeY = Constants.RegionSize;
public uint RegionSizeZ = Constants.RegionHeight;
private Dictionary<String, String> m_extraSettings = new Dictionary<string, string>();
// Apparently, we're applying the same estatesettings regardless of whether it's local or remote.
// MT: Yes. Estates can't span trust boundaries. Therefore, it can be
// assumed that all instances belonging to one estate are able to
// access the same database server. Since estate settings are lodaed
// from there, that should be sufficient for full remote administration
// File based loading
//
public RegionInfo(string description, string filename, bool skipConsoleConfig, IConfigSource configSource) : this(description, filename, skipConsoleConfig, configSource, String.Empty)
{
}
public RegionInfo(string description, string filename, bool skipConsoleConfig, IConfigSource configSource, string configName)
{
// m_configSource = configSource;
if (filename.ToLower().EndsWith(".ini"))
{
if (!File.Exists(filename)) // New region config request
{
IniConfigSource newFile = new IniConfigSource();
ReadNiniConfig(newFile, configName);
newFile.Save(filename);
RegionFile = filename;
return;
}
IniConfigSource source = new IniConfigSource(filename);
bool saveFile = false;
if (source.Configs[configName] == null)
saveFile = true;
ReadNiniConfig(source, configName);
if (configName != String.Empty && saveFile)
source.Save(filename);
RegionFile = filename;
return;
}
try
{
// This will throw if it's not legal Nini XML format
//
IConfigSource xmlsource = new XmlConfigSource(filename);
ReadNiniConfig(xmlsource, configName);
RegionFile = filename;
return;
}
catch (Exception)
{
}
}
// The web loader uses this
//
public RegionInfo(string description, XmlNode xmlNode, bool skipConsoleConfig, IConfigSource configSource)
{
XmlElement elem = (XmlElement)xmlNode;
string name = elem.GetAttribute("Name");
string xmlstr = "<Nini>" + xmlNode.OuterXml + "</Nini>";
XmlConfigSource source = new XmlConfigSource(XmlReader.Create(new StringReader(xmlstr)));
ReadNiniConfig(source, name);
m_serverURI = string.Empty;
}
public RegionInfo(uint legacyRegionLocX, uint legacyRegionLocY, IPEndPoint internalEndPoint, string externalUri)
{
RegionLocX = legacyRegionLocX;
RegionLocY = legacyRegionLocY;
RegionSizeX = Constants.RegionSize;
RegionSizeY = Constants.RegionSize;
m_internalEndPoint = internalEndPoint;
m_externalHostName = externalUri;
m_serverURI = string.Empty;
}
public RegionInfo()
{
m_serverURI = string.Empty;
}
public EstateSettings EstateSettings
{
get
{
if (m_estateSettings == null)
{
m_estateSettings = new EstateSettings();
}
return m_estateSettings;
}
set { m_estateSettings = value; }
}
public RegionSettings RegionSettings
{
get
{
if (m_regionSettings == null)
{
m_regionSettings = new RegionSettings();
}
return m_regionSettings;
}
set { m_regionSettings = value; }
}
public RegionLightShareData WindlightSettings
{
get
{
if (m_windlight == null)
{
m_windlight = new RegionLightShareData();
}
return m_windlight;
}
set { m_windlight = value; }
}
public float NonphysPrimMin
{
get { return m_nonphysPrimMin; }
set { m_nonphysPrimMin = value; }
}
public int NonphysPrimMax
{
get { return m_nonphysPrimMax; }
set { m_nonphysPrimMax = value; }
}
public float PhysPrimMin
{
get { return m_physPrimMin; }
set { m_physPrimMin = value; }
}
public int PhysPrimMax
{
get { return m_physPrimMax; }
set { m_physPrimMax = value; }
}
public bool ClampPrimSize
{
get { return m_clampPrimSize; }
set { m_clampPrimSize = value; }
}
public int ObjectCapacity
{
get { return m_objectCapacity; }
set { m_objectCapacity = value; }
}
public int MaxPrimsPerUser
{
get { return m_maxPrimsPerUser; }
set { m_maxPrimsPerUser = value; }
}
public int LinksetCapacity
{
get { return m_linksetCapacity; }
set { m_linksetCapacity = value; }
}
public int AgentCapacity
{
get { return m_agentCapacity; }
set { m_agentCapacity = value; }
}
public byte AccessLevel
{
get { return (byte)Util.ConvertMaturityToAccessLevel((uint)RegionSettings.Maturity); }
}
public string RegionType
{
get { return m_regionType; }
set { m_regionType = value; }
}
public UUID MaptileStaticUUID
{
get { return m_maptileStaticUUID; }
}
public string MaptileStaticFile { get; private set; }
/// <summary>
/// The port by which http communication occurs with the region (most noticeably, CAPS communication)
/// </summary>
public uint HttpPort
{
get { return m_httpPort; }
set { m_httpPort = value; }
}
/// <summary>
/// A well-formed URI for the host region server (namely "http://" + ExternalHostName)
/// </summary>
public string ServerURI
{
get {
if ( m_serverURI != string.Empty ) {
return m_serverURI;
} else {
return "http://" + ExternalHostName + ":" + m_httpPort + "/";
}
}
set {
if ( value.EndsWith("/") ) {
m_serverURI = value;
} else {
m_serverURI = value + '/';
}
}
}
public string RegionName
{
get { return m_regionName; }
set { m_regionName = value; }
}
public uint RemotingPort
{
get { return m_remotingPort; }
set { m_remotingPort = value; }
}
/// <value>
/// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw.
///
/// XXX Isn't this really doing too much to be a simple getter, rather than an explict method?
/// </value>
public IPEndPoint ExternalEndPoint
{
get
{
// Old one defaults to IPv6
//return new IPEndPoint(Dns.GetHostAddresses(m_externalHostName)[0], m_internalEndPoint.Port);
IPAddress ia = null;
// If it is already an IP, don't resolve it - just return directly
if (IPAddress.TryParse(ExternalHostName, out ia))
return new IPEndPoint(ia, m_internalEndPoint.Port);
// Reset for next check
ia = null;
try
{
foreach (IPAddress Adr in Dns.GetHostAddresses(ExternalHostName))
{
if (ia == null)
ia = Adr;
if (Adr.AddressFamily == AddressFamily.InterNetwork)
{
ia = Adr;
break;
}
}
}
catch (SocketException e)
{
throw new Exception(
"Unable to resolve local hostname " + ExternalHostName + " innerException of type '" +
e + "' attached to this exception", e);
}
return new IPEndPoint(ia, m_internalEndPoint.Port);
}
set { ExternalHostName = value.ToString(); }
}
public string CheckExternalHostName()
{
if (!m_CheckDynDns && !String.IsNullOrEmpty(m_lastExternalHostName))
{
/* no recheck */
}
else if (m_externalHostName == "SYSTEMIP")
{
if (DateTime.UtcNow - m_lastResolverTime > TimeSpan.FromMinutes(1))
{
string newIP = Util.GetLocalHost().ToString();
lock (this)
{
if (newIP != m_lastExternalHostName && m_lastExternalHostName != string.Empty)
{
m_IPChanged = true;
}
if(newIP != m_lastExternalHostName || m_lastExternalHostName == string.Empty)
{
m_log.InfoFormat(
"[REGIONINFO]: Resolving SYSTEMIP to {0} for external hostname of region {1}",
m_externalHostName, m_regionName);
}
m_lastExternalHostName = newIP;
m_lastResolverTime = DateTime.UtcNow;
}
}
}
else if (m_CheckDynDns)
{
if (DateTime.UtcNow - m_lastResolverTime > TimeSpan.FromMinutes(1))
{
try
{
string newIP = Util.GetHostFromDNS(m_externalHostName).ToString();
lock (this)
{
if (newIP != m_lastExternalHostName && m_lastExternalHostName != string.Empty)
{
m_IPChanged = true;
m_lastExternalHostName = newIP;
}
m_lastResolverTime = DateTime.UtcNow;
}
}
catch
{
}
}
return m_externalHostName;
}
else
{
m_lastExternalHostName = m_externalHostName;
}
return m_lastExternalHostName;
}
public string ExternalHostName
{
get
{
return CheckExternalHostName();
}
set { m_externalHostName = value; }
}
public bool IsIPChanged
{
get
{
lock(this)
{
bool ipChanged = m_IPChanged;
m_IPChanged = false;
return ipChanged;
}
}
}
public bool MayChangeIP
{
get
{
return m_CheckDynDns;
}
}
public IPEndPoint InternalEndPoint
{
get { return m_internalEndPoint; }
set { m_internalEndPoint = value; }
}
/// <summary>
/// The x co-ordinate of this region in map tiles (e.g. 1000).
/// Coordinate is scaled as world coordinates divided by the legacy region size
/// and is thus is the number of legacy regions.
/// </summary>
public uint RegionLocX
{
get { return WorldLocX / Constants.RegionSize; }
set { WorldLocX = value * Constants.RegionSize; }
}
/// <summary>
/// The y co-ordinate of this region in map tiles (e.g. 1000).
/// Coordinate is scaled as world coordinates divided by the legacy region size
/// and is thus is the number of legacy regions.
/// </summary>
public uint RegionLocY
{
get { return WorldLocY / Constants.RegionSize; }
set { WorldLocY = value * Constants.RegionSize; }
}
public void SetDefaultRegionSize()
{
WorldLocX = 0;
WorldLocY = 0;
WorldLocZ = 0;
RegionSizeX = Constants.RegionSize;
RegionSizeY = Constants.RegionSize;
RegionSizeZ = Constants.RegionHeight;
}
// A unique region handle is created from the region's world coordinates.
// This cannot be changed because some code expects to receive the region handle and then
// compute the region coordinates from it.
public ulong RegionHandle
{
get { return Util.UIntsToLong(WorldLocX, WorldLocY); }
}
public void SetEndPoint(string ipaddr, int port)
{
IPAddress tmpIP = IPAddress.Parse(ipaddr);
IPEndPoint tmpEPE = new IPEndPoint(tmpIP, port);
m_internalEndPoint = tmpEPE;
}
public string GetSetting(string key)
{
string val;
string keylower = key.ToLower();
if (m_extraSettings.TryGetValue(keylower, out val))
return val;
m_log.DebugFormat("[RegionInfo] Could not locate value for parameter {0}", key);
return null;
}
private void SetExtraSetting(string key, string value)
{
string keylower = key.ToLower();
m_extraSettings[keylower] = value;
}
private void ReadNiniConfig(IConfigSource source, string name)
{
// bool creatingNew = false;
if (source.Configs.Count == 0)
{
MainConsole.Instance.Output("=====================================\n");
MainConsole.Instance.Output("We are now going to ask a couple of questions about your region.\n");
MainConsole.Instance.Output("You can press 'enter' without typing anything to use the default\n");
MainConsole.Instance.Output("the default is displayed between [ ] brackets.\n");
MainConsole.Instance.Output("=====================================\n");
if (name == String.Empty)
{
while (name.Trim() == string.Empty)
{
name = MainConsole.Instance.CmdPrompt("New region name", name);
if (name.Trim() == string.Empty)
{
MainConsole.Instance.Output("Cannot interactively create region with no name");
}
}
}
source.AddConfig(name);
// creatingNew = true;
}
if (name == String.Empty)
name = source.Configs[0].Name;
if (source.Configs[name] == null)
{
source.AddConfig(name);
}
RegionName = name;
IConfig config = source.Configs[name];
// Track all of the keys in this config and remove as they are processed
// The remaining keys will be added to generic key-value storage for
// whoever might need it
HashSet<String> allKeys = new HashSet<String>();
foreach (string s in config.GetKeys())
{
allKeys.Add(s);
}
// RegionUUID
//
allKeys.Remove("RegionUUID");
string regionUUID = config.GetString("RegionUUID", string.Empty);
if (!UUID.TryParse(regionUUID.Trim(), out RegionID))
{
UUID newID = UUID.Random();
while (RegionID == UUID.Zero)
{
regionUUID = MainConsole.Instance.CmdPrompt("RegionUUID", newID.ToString());
if (!UUID.TryParse(regionUUID.Trim(), out RegionID))
{
MainConsole.Instance.Output("RegionUUID must be a valid UUID");
}
}
config.Set("RegionUUID", regionUUID);
}
originRegionID = RegionID; // What IS this?! (Needed for RegionCombinerModule?)
// Location
//
allKeys.Remove("Location");
string location = config.GetString("Location", String.Empty);
if (location == String.Empty)
{
location = MainConsole.Instance.CmdPrompt("Region Location", "1000,1000");
config.Set("Location", location);
}
string[] locationElements = location.Split(new char[] {','});
RegionLocX = Convert.ToUInt32(locationElements[0]);
RegionLocY = Convert.ToUInt32(locationElements[1]);
// Region size
// Default to legacy region size if not specified.
allKeys.Remove("SizeX");
string configSizeX = config.GetString("SizeX", Constants.RegionSize.ToString());
config.Set("SizeX", configSizeX);
RegionSizeX = Convert.ToUInt32(configSizeX);
allKeys.Remove("SizeY");
string configSizeY = config.GetString("SizeY", Constants.RegionSize.ToString());
config.Set("SizeY", configSizeX);
RegionSizeY = Convert.ToUInt32(configSizeY);
allKeys.Remove("SizeZ");
string configSizeZ = config.GetString("SizeZ", Constants.RegionHeight.ToString());
config.Set("SizeZ", configSizeX);
RegionSizeZ = Convert.ToUInt32(configSizeZ);
DoRegionSizeSanityChecks();
// InternalAddress
//
IPAddress address;
allKeys.Remove("InternalAddress");
if (config.Contains("InternalAddress"))
{
address = IPAddress.Parse(config.GetString("InternalAddress", String.Empty));
}
else
{
address = IPAddress.Parse(MainConsole.Instance.CmdPrompt("Internal IP address", "0.0.0.0"));
config.Set("InternalAddress", address.ToString());
}
// InternalPort
//
int port;
allKeys.Remove("InternalPort");
if (config.Contains("InternalPort"))
{
port = config.GetInt("InternalPort", 9000);
}
else
{
port = Convert.ToInt32(MainConsole.Instance.CmdPrompt("Internal port", "9000"));
config.Set("InternalPort", port);
}
m_internalEndPoint = new IPEndPoint(address, port);
// AllowAlternatePorts
//
allKeys.Remove("AllowAlternatePorts");
if (config.Contains("AllowAlternatePorts"))
{
m_allow_alternate_ports = config.GetBoolean("AllowAlternatePorts", true);
}
else
{
m_allow_alternate_ports = Convert.ToBoolean(MainConsole.Instance.CmdPrompt("Allow alternate ports", "False"));
config.Set("AllowAlternatePorts", m_allow_alternate_ports.ToString());
}
// ExternalHostName
//
allKeys.Remove("ExternalHostName");
string externalName;
if (config.Contains("ExternalHostName"))
{
externalName = config.GetString("ExternalHostName", "SYSTEMIP");
}
else
{
externalName = MainConsole.Instance.CmdPrompt("External host name", "SYSTEMIP");
config.Set("ExternalHostName", externalName);
}
if (externalName == "MetroIP")
{
string newIP;
string strNewValue;
ServicePointManagerTimeoutSupport.ResetHosts();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://hypergrid.org/my_external_ip.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
strNewValue = "name=Lena";
req.ContentLength = strNewValue.Length;
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(strNewValue);
stOut.Close();
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
newIP = stIn.ReadToEnd();
stIn.Close();
m_externalHostName = newIP;
}
else
{
m_externalHostName = externalName;
m_CheckDynDns = config.GetBoolean("CheckForIPChanges", false);
}
// RegionType
m_regionType = config.GetString("RegionType", String.Empty);
allKeys.Remove("RegionType");
#region Prim and map stuff
m_nonphysPrimMin = config.GetFloat("NonPhysicalPrimMin", 0);
allKeys.Remove("NonPhysicalPrimMin");
m_nonphysPrimMax = config.GetInt("NonPhysicalPrimMax", 0);
allKeys.Remove("NonPhysicalPrimMax");
m_physPrimMin = config.GetFloat("PhysicalPrimMin", 0);
allKeys.Remove("PhysicalPrimMin");
m_physPrimMax = config.GetInt("PhysicalPrimMax", 0);
allKeys.Remove("PhysicalPrimMax");
m_clampPrimSize = config.GetBoolean("ClampPrimSize", false);
allKeys.Remove("ClampPrimSize");
m_objectCapacity = config.GetInt("MaxPrims", 15000);
allKeys.Remove("MaxPrims");
m_maxPrimsPerUser = config.GetInt("MaxPrimsPerUser", -1);
allKeys.Remove("MaxPrimsPerUser");
m_linksetCapacity = config.GetInt("LinksetPrims", 0);
allKeys.Remove("LinksetPrims");
allKeys.Remove("MaptileStaticUUID");
string mapTileStaticUUID = config.GetString("MaptileStaticUUID", UUID.Zero.ToString());
if (UUID.TryParse(mapTileStaticUUID.Trim(), out m_maptileStaticUUID))
{
config.Set("MaptileStaticUUID", m_maptileStaticUUID.ToString());
}
MaptileStaticFile = config.GetString("MaptileStaticFile", String.Empty);
allKeys.Remove("MaptileStaticFile");
#endregion
m_agentCapacity = config.GetInt("MaxAgents", 100);
allKeys.Remove("MaxAgents");
// Multi-tenancy
//
ScopeID = new UUID(config.GetString("ScopeID", UUID.Zero.ToString()));
allKeys.Remove("ScopeID");
foreach (String s in allKeys)
{
SetExtraSetting(s, config.GetString(s));
}
}
// Make sure user specified region sizes are sane.
// Must be multiples of legacy region size (256).
private void DoRegionSizeSanityChecks()
{
if (RegionSizeX != Constants.RegionSize || RegionSizeY != Constants.RegionSize)
{
// Doing non-legacy region sizes.
// Enforce region size to be multiples of the legacy region size (256)
uint partial = RegionSizeX % Constants.RegionSize;
if (partial != 0)
{
RegionSizeX -= partial;
if (RegionSizeX == 0)
RegionSizeX = Constants.RegionSize;
m_log.ErrorFormat("{0} Region size must be multiple of {1}. Enforcing {2}.RegionSizeX={3} instead of specified {4}",
LogHeader, Constants.RegionSize, m_regionName, RegionSizeX, RegionSizeX + partial);
}
partial = RegionSizeY % Constants.RegionSize;
if (partial != 0)
{
RegionSizeY -= partial;
if (RegionSizeY == 0)
RegionSizeY = Constants.RegionSize;
m_log.ErrorFormat("{0} Region size must be multiple of {1}. Enforcing {2}.RegionSizeY={3} instead of specified {4}",
LogHeader, Constants.RegionSize, m_regionName, RegionSizeY, RegionSizeY + partial);
}
// Because of things in the viewer, regions MUST be square.
// Remove this check when viewers have been updated.
if (RegionSizeX != RegionSizeY)
{
uint minSize = Math.Min(RegionSizeX, RegionSizeY);
RegionSizeX = minSize;
RegionSizeY = minSize;
m_log.ErrorFormat("{0} Regions must be square until viewers are updated. Forcing region {1} size to <{2},{3}>",
LogHeader, m_regionName, RegionSizeX, RegionSizeY);
}
// There is a practical limit to region size.
if (RegionSizeX > Constants.MaximumRegionSize || RegionSizeY > Constants.MaximumRegionSize)
{
RegionSizeX = Util.Clamp<uint>(RegionSizeX, Constants.RegionSize, Constants.MaximumRegionSize);
RegionSizeY = Util.Clamp<uint>(RegionSizeY, Constants.RegionSize, Constants.MaximumRegionSize);
m_log.ErrorFormat("{0} Region dimensions must be less than {1}. Clamping {2}'s size to <{3},{4}>",
LogHeader, Constants.MaximumRegionSize, m_regionName, RegionSizeX, RegionSizeY);
}
m_log.InfoFormat("{0} Region {1} size set to <{2},{3}>", LogHeader, m_regionName, RegionSizeX, RegionSizeY);
}
}
private void WriteNiniConfig(IConfigSource source)
{
IConfig config = source.Configs[RegionName];
if (config != null)
source.Configs.Remove(config);
config = source.AddConfig(RegionName);
config.Set("RegionUUID", RegionID.ToString());
string location = String.Format("{0},{1}", RegionLocX, RegionLocY);
config.Set("Location", location);
if (RegionSizeX != Constants.RegionSize || RegionSizeY != Constants.RegionSize)
{
config.Set("SizeX", RegionSizeX);
config.Set("SizeY", RegionSizeY);
config.Set("SizeZ", RegionSizeZ);
}
config.Set("InternalAddress", m_internalEndPoint.Address.ToString());
config.Set("InternalPort", m_internalEndPoint.Port);
config.Set("AllowAlternatePorts", m_allow_alternate_ports.ToString());
config.Set("ExternalHostName", m_externalHostName);
if (m_nonphysPrimMin > 0)
config.Set("NonphysicalPrimMax", m_nonphysPrimMin);
if (m_nonphysPrimMax > 0)
config.Set("NonphysicalPrimMax", m_nonphysPrimMax);
if (m_physPrimMin > 0)
config.Set("PhysicalPrimMax", m_physPrimMin);
if (m_physPrimMax > 0)
config.Set("PhysicalPrimMax", m_physPrimMax);
config.Set("ClampPrimSize", m_clampPrimSize.ToString());
if (m_objectCapacity > 0)
config.Set("MaxPrims", m_objectCapacity);
if (m_maxPrimsPerUser > -1)
config.Set("MaxPrimsPerUser", m_maxPrimsPerUser);
if (m_linksetCapacity > 0)
config.Set("LinksetPrims", m_linksetCapacity);
if (m_agentCapacity > 0)
config.Set("MaxAgents", m_agentCapacity);
if (ScopeID != UUID.Zero)
config.Set("ScopeID", ScopeID.ToString());
if (RegionType != String.Empty)
config.Set("RegionType", RegionType);
if (m_maptileStaticUUID != UUID.Zero)
config.Set("MaptileStaticUUID", m_maptileStaticUUID.ToString());
if (MaptileStaticFile != String.Empty)
config.Set("MaptileStaticFile", MaptileStaticFile);
}
public bool ignoreIncomingConfiguration(string configuration_key, object configuration_result)
{
return true;
}
public void SaveRegionToFile(string description, string filename)
{
if (filename.ToLower().EndsWith(".ini"))
{
IniConfigSource source = new IniConfigSource();
try
{
source = new IniConfigSource(filename); // Load if it exists
}
catch (Exception)
{
}
WriteNiniConfig(source);
source.Save(filename);
return;
}
else
throw new Exception("Invalid file type for region persistence.");
}
public void SaveLastMapUUID(UUID mapUUID)
{
lastMapUUID = mapUUID;
lastMapRefresh = Util.UnixTimeSinceEpoch().ToString();
}
public OSDMap PackRegionInfoData()
{
OSDMap args = new OSDMap();
args["region_id"] = OSD.FromUUID(RegionID);
if ((RegionName != null) && !RegionName.Equals(""))
args["region_name"] = OSD.FromString(RegionName);
args["external_host_name"] = OSD.FromString(ExternalHostName);
args["http_port"] = OSD.FromString(HttpPort.ToString());
args["server_uri"] = OSD.FromString(ServerURI);
args["region_xloc"] = OSD.FromString(RegionLocX.ToString());
args["region_yloc"] = OSD.FromString(RegionLocY.ToString());
args["region_size_x"] = OSD.FromString(RegionSizeX.ToString());
args["region_size_y"] = OSD.FromString(RegionSizeY.ToString());
args["region_size_z"] = OSD.FromString(RegionSizeZ.ToString());
args["internal_ep_address"] = OSD.FromString(InternalEndPoint.Address.ToString());
args["internal_ep_port"] = OSD.FromString(InternalEndPoint.Port.ToString());
if ((RemotingAddress != null) && !RemotingAddress.Equals(""))
args["remoting_address"] = OSD.FromString(RemotingAddress);
args["remoting_port"] = OSD.FromString(RemotingPort.ToString());
args["allow_alt_ports"] = OSD.FromBoolean(m_allow_alternate_ports);
if ((proxyUrl != null) && !proxyUrl.Equals(""))
args["proxy_url"] = OSD.FromString(proxyUrl);
if (RegionType != String.Empty)
args["region_type"] = OSD.FromString(RegionType);
return args;
}
public void UnpackRegionInfoData(OSDMap args)
{
if (args["region_id"] != null)
RegionID = args["region_id"].AsUUID();
if (args["region_name"] != null)
RegionName = args["region_name"].AsString();
if (args["external_host_name"] != null)
ExternalHostName = args["external_host_name"].AsString();
if (args["http_port"] != null)
UInt32.TryParse(args["http_port"].AsString(), out m_httpPort);
if (args["server_uri"] != null)
ServerURI = args["server_uri"].AsString();
if (args["region_xloc"] != null)
{
uint locx;
UInt32.TryParse(args["region_xloc"].AsString(), out locx);
RegionLocX = locx;
}
if (args["region_yloc"] != null)
{
uint locy;
UInt32.TryParse(args["region_yloc"].AsString(), out locy);
RegionLocY = locy;
}
if (args.ContainsKey("region_size_x"))
RegionSizeX = (uint)args["region_size_x"].AsInteger();
if (args.ContainsKey("region_size_y"))
RegionSizeY = (uint)args["region_size_y"].AsInteger();
if (args.ContainsKey("region_size_z"))
RegionSizeZ = (uint)args["region_size_z"].AsInteger();
IPAddress ip_addr = null;
if (args["internal_ep_address"] != null)
{
IPAddress.TryParse(args["internal_ep_address"].AsString(), out ip_addr);
}
int port = 0;
if (args["internal_ep_port"] != null)
{
Int32.TryParse(args["internal_ep_port"].AsString(), out port);
}
InternalEndPoint = new IPEndPoint(ip_addr, port);
if (args["remoting_address"] != null)
RemotingAddress = args["remoting_address"].AsString();
if (args["remoting_port"] != null)
UInt32.TryParse(args["remoting_port"].AsString(), out m_remotingPort);
if (args["allow_alt_ports"] != null)
m_allow_alternate_ports = args["allow_alt_ports"].AsBoolean();
if (args["proxy_url"] != null)
proxyUrl = args["proxy_url"].AsString();
if (args["region_type"] != null)
m_regionType = args["region_type"].AsString();
}
public static RegionInfo Create(UUID regionID, string regionName, uint regX, uint regY, string externalHostName, uint httpPort, uint simPort, uint remotingPort, string serverURI)
{
RegionInfo regionInfo;
IPEndPoint neighbourInternalEndPoint = new IPEndPoint(Util.GetHostFromDNS(externalHostName), (int)simPort);
regionInfo = new RegionInfo(regX, regY, neighbourInternalEndPoint, externalHostName);
regionInfo.RemotingPort = remotingPort;
regionInfo.RemotingAddress = externalHostName;
regionInfo.HttpPort = httpPort;
regionInfo.RegionID = regionID;
regionInfo.RegionName = regionName;
regionInfo.ServerURI = serverURI;
return regionInfo;
}
}
}
| |
/*
* NPlot - A charting library for .NET
*
* ArrowItem.cs
* Copyright (C) 2003-2006 Matt Howlett and others.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
*
* 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.Drawing;
namespace NPlot
{
/// <summary>
/// An Arrow IDrawable, with a text label that is automatically
/// nicely positioned at the non-pointy end of the arrow. Future
/// feature idea: have constructor that takes a dataset, and have
/// the arrow know how to automatically set it's angle to avoid
/// the data.
/// </summary>
public class ArrowItem : IDrawable
{
private readonly Pen pen_ = new Pen(Color.Black);
private double angle_ = -45.0;
private Brush arrowBrush_ = new SolidBrush(Color.Black);
private Font font_;
private float headAngle_ = 40.0f;
private int headOffset_ = 2;
private float headSize_ = 10.0f;
private float physicalLength_ = 40.0f;
private Brush textBrush_ = new SolidBrush(Color.Black);
private string text_ = "";
private PointD to_;
/// <summary>
/// Default constructor :
/// text = ""
/// angle = 45 degrees anticlockwise from horizontal.
/// </summary>
/// <param name="position">The position the arrow points to.</param>
public ArrowItem(PointD position)
{
to_ = position;
Init();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="position">The position the arrow points to.</param>
/// <param name="angle">angle of arrow with respect to x axis.</param>
public ArrowItem(PointD position, double angle)
{
to_ = position;
angle_ = -angle;
Init();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="position">The position the arrow points to.</param>
/// <param name="angle">angle of arrow with respect to x axis.</param>
/// <param name="text">The text associated with the arrow.</param>
public ArrowItem(PointD position, double angle, string text)
{
to_ = position;
angle_ = -angle;
text_ = text;
Init();
}
/// <summary>
/// Text associated with the arrow.
/// </summary>
public string Text
{
get { return text_; }
set { text_ = value; }
}
/// <summary>
/// Angle of arrow anti-clockwise to right horizontal in degrees.
/// </summary>
/// <remarks>
/// The code relating to this property in the Draw method is
/// a bit weird. Internally, all rotations are clockwise [this is by
/// accient, I wasn't concentrating when I was doing it and was half
/// done before I realised]. The simplest way to make angle represent
/// anti-clockwise rotation (as it is normal to do) is to make the
/// get and set methods negate the provided value.
/// </remarks>
public double Angle
{
get { return -angle_; }
set { angle_ = -value; }
}
/// <summary>
/// Physical length of the arrow.
/// </summary>
public float PhysicalLength
{
get { return physicalLength_; }
set { physicalLength_ = value; }
}
/// <summary>
/// The point the arrow points to.
/// </summary>
public PointD To
{
get { return to_; }
set { to_ = value; }
}
/// <summary>
/// Size of the arrow head sides in pixels.
/// </summary>
public float HeadSize
{
get { return headSize_; }
set { headSize_ = value; }
}
/// <summary>
/// angle between sides of arrow head in degrees
/// </summary>
public float HeadAngle
{
get { return headAngle_; }
set { headAngle_ = value; }
}
/// <summary>
/// The brush used to draw the text associated with the arrow.
/// </summary>
public Brush TextBrush
{
get { return textBrush_; }
set { textBrush_ = value; }
}
/// <summary>
/// Set the text to be drawn with a solid brush of this color.
/// </summary>
public Color TextColor
{
set { textBrush_ = new SolidBrush(value); }
}
/// <summary>
/// The color of the pen used to draw the arrow.
/// </summary>
public Color ArrowColor
{
get { return pen_.Color; }
set
{
pen_.Color = value;
arrowBrush_ = new SolidBrush(value);
}
}
/// <summary>
/// The font used to draw the text associated with the arrow.
/// </summary>
public Font TextFont
{
get { return font_; }
set { font_ = value; }
}
/// <summary>
/// Offset the whole arrow back in the arrow direction this many pixels from the point it's pointing to.
/// </summary>
public int HeadOffset
{
get { return headOffset_; }
set { headOffset_ = value; }
}
/// <summary>
/// Draws the arrow on a plot surface.
/// </summary>
/// <param name="g">graphics surface on which to draw</param>
/// <param name="xAxis">The X-Axis to draw against.</param>
/// <param name="yAxis">The Y-Axis to draw against.</param>
public void Draw(Graphics g, PhysicalAxis xAxis, PhysicalAxis yAxis)
{
if (To.X > xAxis.Axis.WorldMax || To.X < xAxis.Axis.WorldMin)
return;
if (To.Y > yAxis.Axis.WorldMax || To.Y < yAxis.Axis.WorldMin)
return;
double angle = angle_;
if (angle_ < 0.0)
{
int mul = -(int) (angle_/360.0) + 2;
angle = angle_ + 360.0*mul;
}
double normAngle = angle%360.0; // angle in range 0 -> 360.
Point toPoint = new Point(
(int) xAxis.WorldToPhysical(to_.X, true).X,
(int) yAxis.WorldToPhysical(to_.Y, true).Y);
float xDir = (float) Math.Cos(normAngle*2.0*Math.PI/360.0);
float yDir = (float) Math.Sin(normAngle*2.0*Math.PI/360.0);
toPoint.X += (int) (xDir*headOffset_);
toPoint.Y += (int) (yDir*headOffset_);
float xOff = physicalLength_*xDir;
float yOff = physicalLength_*yDir;
Point fromPoint = new Point(
(int) (toPoint.X + xOff),
(int) (toPoint.Y + yOff));
g.DrawLine(pen_, toPoint, fromPoint);
Point[] head = new Point[3];
head[0] = toPoint;
xOff = headSize_*(float) Math.Cos((normAngle - headAngle_/2.0f)*2.0*Math.PI/360.0);
yOff = headSize_*(float) Math.Sin((normAngle - headAngle_/2.0f)*2.0*Math.PI/360.0);
head[1] = new Point(
(int) (toPoint.X + xOff),
(int) (toPoint.Y + yOff));
float xOff2 = headSize_*(float) Math.Cos((normAngle + headAngle_/2.0f)*2.0*Math.PI/360.0);
float yOff2 = headSize_*(float) Math.Sin((normAngle + headAngle_/2.0f)*2.0*Math.PI/360.0);
head[2] = new Point(
(int) (toPoint.X + xOff2),
(int) (toPoint.Y + yOff2));
g.FillPolygon(arrowBrush_, head);
SizeF textSize = g.MeasureString(text_, font_);
SizeF halfSize = new SizeF(textSize.Width/2.0f, textSize.Height/2.0f);
float quadrantSlideLength = halfSize.Width + halfSize.Height;
float quadrantF = (float) normAngle/90.0f; // integer part gives quadrant.
int quadrant = (int) quadrantF; // quadrant in.
float prop = quadrantF - quadrant; // proportion of way through this qadrant.
float dist = prop*quadrantSlideLength; // distance along quarter of bounds rectangle.
// now find the offset from the middle of the text box that the
// rear end of the arrow should end at (reverse this to get position
// of text box with respect to rear end of arrow).
//
// There is almost certainly an elgant way of doing this involving
// trig functions to get all the signs right, but I'm about ready to
// drop off to sleep at the moment, so this blatent method will have
// to do.
PointF offsetFromMiddle = new PointF(0.0f, 0.0f);
switch (quadrant)
{
case 0:
if (dist > halfSize.Height)
{
dist -= halfSize.Height;
offsetFromMiddle = new PointF(-halfSize.Width + dist, halfSize.Height);
}
else
{
offsetFromMiddle = new PointF(-halfSize.Width, - dist);
}
break;
case 1:
if (dist > halfSize.Width)
{
dist -= halfSize.Width;
offsetFromMiddle = new PointF(halfSize.Width, halfSize.Height - dist);
}
else
{
offsetFromMiddle = new PointF(dist, halfSize.Height);
}
break;
case 2:
if (dist > halfSize.Height)
{
dist -= halfSize.Height;
offsetFromMiddle = new PointF(halfSize.Width - dist, -halfSize.Height);
}
else
{
offsetFromMiddle = new PointF(halfSize.Width, -dist);
}
break;
case 3:
if (dist > halfSize.Width)
{
dist -= halfSize.Width;
offsetFromMiddle = new PointF(-halfSize.Width, -halfSize.Height + dist);
}
else
{
offsetFromMiddle = new PointF(-dist, -halfSize.Height);
}
break;
default:
throw new NPlotException("Programmer error.");
}
g.DrawString(
text_, font_, textBrush_,
(int) (fromPoint.X - halfSize.Width - offsetFromMiddle.X),
(int) (fromPoint.Y - halfSize.Height + offsetFromMiddle.Y));
}
private void Init()
{
FontFamily fontFamily = new FontFamily("Arial");
font_ = new Font(fontFamily, 10, FontStyle.Regular, GraphicsUnit.Pixel);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MachineKeySection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace FormsAuthOnly.Configuration
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using FormsAuthOnly.Security.Cryptography;
using FormsAuthOnly.Util;
/******************************************************************
* !! NOTICE !! *
* The cryptographic code in this class is a legacy code base. *
* New code should not call into these crypto APIs; use the APIs *
* provided by AspNetCryptoServiceProvider instead. *
******************************************************************/
/******************************************************************
* !! WARNING !! *
* This class contains cryptographic code. If you make changes to *
* this class, please have it reviewed by the appropriate people. *
******************************************************************/
/*
<!-- validation="[SHA1|MD5|3DES|AES|HMACSHA256|HMACSHA384|HMACSHA512|alg:algorithm_name]" decryption="[AES|EDES" -->
<machineKey validationKey="AutoGenerate,IsolateApps" decryptionKey="AutoGenerate,IsolateApps" decryption="[AES|3DES]" validation="HMACSHA256" compatibilityMode="[Framework20SP1|Framework20SP2]" />
*/
public sealed class MachineKeySection
{
private const string OBSOLETE_CRYPTO_API_MESSAGE = "This API exists only for backward compatibility; new framework features that require cryptographic services MUST NOT call it. New features should use the AspNetCryptoServiceProvider class instead.";
// If the default validation algorithm changes, be sure to update the _HashSize and _AutoGenValidationKeySize fields also.
internal const string DefaultValidationAlgorithm = "HMACSHA256";
internal const MachineKeyValidation DefaultValidation = MachineKeyValidation.SHA1;
internal const string DefaultDataProtectorType = "";
internal const string DefaultApplicationName = "";
private static object s_initLock = new object();
private static bool s_initComplete = false;
private static MachineKeySection s_config;
private static RNGCryptoServiceProvider s_randomNumberGenerator;
private static SymmetricAlgorithm s_oSymAlgoDecryption;
private static SymmetricAlgorithm s_oSymAlgoValidation;
private static byte[] s_validationKey;
private static byte[] s_inner = null;
private static byte[] s_outer = null;
internal static bool IsDecryptionKeyAutogenerated { get { EnsureConfig(); return s_config.AutogenKey; } }
private bool _AutogenKey;
internal bool AutogenKey { get { RuntimeDataInitialize(); return _AutogenKey; } }
private byte[] _ValidationKey;
private byte[] _DecryptionKey;
private bool DataInitialized = false;
private static bool _CustomValidationTypeIsKeyed;
private static string _CustomValidationName;
private static int _IVLengthDecryption = 64;
private static int _IVLengthValidation = 64;
private static int _HashSize = HMACSHA256_HASH_SIZE;
private static int _AutoGenValidationKeySize = HMACSHA256_KEY_SIZE;
private static int _AutoGenDecryptionKeySize = 24;
private static bool _UseHMACSHA = true;
private static bool _UsingCustomEncryption = false;
private static SymmetricAlgorithm s_oSymAlgoLegacy;
private const int MD5_KEY_SIZE = 64;
private const int MD5_HASH_SIZE = 16;
private const int SHA1_KEY_SIZE = 64;
private const int HMACSHA256_KEY_SIZE = 64;
private const int HMACSHA384_KEY_SIZE = 128;
private const int HMACSHA512_KEY_SIZE = 128;
private const int SHA1_HASH_SIZE = 20;
private const int HMACSHA256_HASH_SIZE = 32;
private const int HMACSHA384_HASH_SIZE = 48;
private const int HMACSHA512_HASH_SIZE = 64;
private const string ALGO_PREFIX = "alg:";
internal byte[] ValidationKeyInternal { get { RuntimeDataInitialize(); return (byte[])_ValidationKey.Clone(); } }
internal byte[] DecryptionKeyInternal { get { RuntimeDataInitialize(); return (byte[])_DecryptionKey.Clone(); } }
internal static int HashSize { get { s_config.RuntimeDataInitialize(); return _HashSize; } }
internal static int ValidationKeySize { get { s_config.RuntimeDataInitialize(); return _AutoGenValidationKeySize; } }
public MachineKeySection()
{
DecryptionKey = "AutoGenerate, IsolateApps";
DecryptionKey = "AutoGenerate, IsolateApps";
Decryption = "Auto";
Validation = DefaultValidation;
DataProtectorType = DefaultDataProtectorType;
ApplicationName = DefaultApplicationName;
CompatibilityMode = MachineKeyCompatibilityMode.Framework20SP1;
}
internal static MachineKeyCompatibilityMode CompatMode
{
get
{
return GetApplicationConfig().CompatibilityMode;
}
}
public string ValidationKey { get; set; }
public string DecryptionKey { get; set; }
private string decryption;
public string Decryption
{
get
{
string s = decryption ?? "Auto";
if (s != "Auto" && s != "AES" && s != "3DES" && s != "DES" && !s.StartsWith(ALGO_PREFIX, StringComparison.Ordinal))
throw new InvalidOperationException(SR.GetString(SR.Wrong_decryption_enum));
return s;
}
set
{
if (value != "AES" && value != "3DES" && value != "Auto" && value != "DES" && !value.StartsWith(ALGO_PREFIX, StringComparison.Ordinal))
throw new InvalidOperationException(SR.GetString(SR.Wrong_decryption_enum));
decryption = value;
}
}
private bool _validationIsCached;
private string _cachedValidation;
private MachineKeyValidation _cachedValidationEnum;
private string validationAlgorithm;
public string ValidationAlgorithm
{
get
{
if (!_validationIsCached)
CacheValidation();
return _cachedValidation;
}
set
{
if (_validationIsCached && value == _cachedValidation)
return;
if (value == null)
value = DefaultValidationAlgorithm;
_cachedValidationEnum = MachineKeyValidationConverter.ConvertToEnum(value);
_cachedValidation = value;
validationAlgorithm = value;
_validationIsCached = true;
}
}
// returns the value in the 'validation' attribute (or the default value if null) without throwing an exception if the value is malformed
internal string GetValidationAttributeSkipValidation()
{
return validationAlgorithm ?? DefaultValidationAlgorithm;
}
private void CacheValidation()
{
_cachedValidation = GetValidationAttributeSkipValidation();
_cachedValidationEnum = MachineKeyValidationConverter.ConvertToEnum(_cachedValidation);
_validationIsCached = true;
}
private string validation;
public MachineKeyValidation Validation
{
get
{
if (_validationIsCached == false)
CacheValidation();
return _cachedValidationEnum;
}
set
{
if (_validationIsCached && value == _cachedValidationEnum)
return;
_cachedValidation = MachineKeyValidationConverter.ConvertFromEnum(value);
_cachedValidationEnum = value;
validation = _cachedValidation;
_validationIsCached = true;
}
}
public string DataProtectorType { get; set; }
public string ApplicationName { get; set; }
public MachineKeyCompatibilityMode CompatibilityMode { get; set; }
private void RuntimeDataInitialize()
{
if (DataInitialized == false) {
byte[] bKeysRandom = null;
bool fNonHttpApp = false;
string strKey = ValidationKey;
string appName = null; // HttpRuntime.AppDomainAppVirtualPath;
string appId = null; // HttpRuntime.AppDomainAppId;
InitValidationAndEncyptionSizes();
if (appName == null) {
#if !FEATURE_PAL // FEATURE_PAL does not enable cryptography
// FEATURE_PAL
appName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
if (ValidationKey.Contains("AutoGenerate") ||
DecryptionKey.Contains("AutoGenerate")) {
fNonHttpApp = true;
bKeysRandom = new byte[_AutoGenValidationKeySize + _AutoGenDecryptionKeySize];
// Gernerate random keys
RandomNumberGenerator.GetBytes(bKeysRandom);
}
#endif // !FEATURE_PAL
}
bool fAppIdSpecific = StringUtil.StringEndsWith(strKey, ",IsolateByAppId");
if (fAppIdSpecific) {
strKey = strKey.Substring(0, strKey.Length - ",IsolateByAppId".Length);
}
bool fAppSpecific = StringUtil.StringEndsWith(strKey, ",IsolateApps");
if (fAppSpecific) {
strKey = strKey.Substring(0, strKey.Length - ",IsolateApps".Length);
}
if (strKey == "AutoGenerate") { // case sensitive
_ValidationKey = new byte[_AutoGenValidationKeySize];
if (fNonHttpApp) {
Buffer.BlockCopy(bKeysRandom, 0, _ValidationKey, 0, _AutoGenValidationKeySize);
} else {
//Buffer.BlockCopy(HttpRuntime.s_autogenKeys, 0, _ValidationKey, 0, _AutoGenValidationKeySize);
}
} else {
if (strKey.Length < 40 || (strKey.Length & 0x1) == 1)
throw new InvalidOperationException(SR.GetString(SR.Unable_to_get_cookie_authentication_validation_key, strKey.Length.ToString(CultureInfo.InvariantCulture)));
#pragma warning disable 618 // obsolete
_ValidationKey = HexStringToByteArray(strKey);
#pragma warning restore 618
if (_ValidationKey == null)
throw new InvalidOperationException(SR.GetString(SR.Invalid_validation_key));
}
if (fAppSpecific) {
int dwCode = StringComparer.InvariantCultureIgnoreCase.GetHashCode(appName);
_ValidationKey[0] = (byte)(dwCode & 0xff);
_ValidationKey[1] = (byte)((dwCode & 0xff00) >> 8);
_ValidationKey[2] = (byte)((dwCode & 0xff0000) >> 16);
_ValidationKey[3] = (byte)((dwCode & 0xff000000) >> 24);
}
if (fAppIdSpecific) {
int dwCode = StringComparer.InvariantCultureIgnoreCase.GetHashCode(appId);
_ValidationKey[4] = (byte)(dwCode & 0xff);
_ValidationKey[5] = (byte)((dwCode & 0xff00) >> 8);
_ValidationKey[6] = (byte)((dwCode & 0xff0000) >> 16);
_ValidationKey[7] = (byte)((dwCode & 0xff000000) >> 24);
}
strKey = DecryptionKey;
fAppIdSpecific = StringUtil.StringEndsWith(strKey, ",IsolateByAppId");
if (fAppIdSpecific) {
strKey = strKey.Substring(0, strKey.Length - ",IsolateByAppId".Length);
}
fAppSpecific = StringUtil.StringEndsWith(strKey, ",IsolateApps");
if (fAppSpecific) {
strKey = strKey.Substring(0, strKey.Length - ",IsolateApps".Length);
}
if (strKey == "AutoGenerate") { // case sensitive
_DecryptionKey = new byte[_AutoGenDecryptionKeySize];
if (fNonHttpApp) {
Buffer.BlockCopy(bKeysRandom, _AutoGenValidationKeySize, _DecryptionKey, 0, _AutoGenDecryptionKeySize);
} else {
//Buffer.BlockCopy(HttpRuntime.s_autogenKeys, _AutoGenValidationKeySize, _DecryptionKey, 0, _AutoGenDecryptionKeySize);
}
_AutogenKey = true;
} else {
_AutogenKey = false;
if ((strKey.Length & 1) != 0)
throw new InvalidOperationException(SR.GetString(SR.Invalid_decryption_key));
#pragma warning disable 618 // obsolete
_DecryptionKey = HexStringToByteArray(strKey);
#pragma warning restore 618
if (_DecryptionKey == null)
throw new InvalidOperationException(SR.GetString(SR.Invalid_decryption_key));
}
if (fAppSpecific) {
int dwCode = StringComparer.InvariantCultureIgnoreCase.GetHashCode(appName);
_DecryptionKey[0] = (byte)(dwCode & 0xff);
_DecryptionKey[1] = (byte)((dwCode & 0xff00) >> 8);
_DecryptionKey[2] = (byte)((dwCode & 0xff0000) >> 16);
_DecryptionKey[3] = (byte)((dwCode & 0xff000000) >> 24);
}
if (fAppIdSpecific) {
int dwCode = StringComparer.InvariantCultureIgnoreCase.GetHashCode(appId);
_DecryptionKey[4] = (byte)(dwCode & 0xff);
_DecryptionKey[5] = (byte)((dwCode & 0xff00) >> 8);
_DecryptionKey[6] = (byte)((dwCode & 0xff0000) >> 16);
_DecryptionKey[7] = (byte)((dwCode & 0xff000000) >> 24);
}
DataInitialized = true;
}
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length)
{
// MSRC 10405: IVType.Hash has been removed; new default behavior is to use IVType.Random.
return EncryptOrDecryptData(fEncrypt, buf, modifier, start, length, false, false, IVType.Random);
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length, bool useValidationSymAlgo)
{
// MSRC 10405: IVType.Hash has been removed; new default behavior is to use IVType.Random.
return EncryptOrDecryptData(fEncrypt, buf, modifier, start, length, useValidationSymAlgo, false, IVType.Random);
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length,
bool useValidationSymAlgo, bool useLegacyMode, IVType ivType)
{
// MSRC 10405: Encryption is not sufficient to prevent a malicious user from tampering with the data, and the result of decryption can
// be used to discover information about the plaintext (such as via a padding or decryption oracle). We must sign anything that we
// encrypt to ensure that end users can't abuse our encryption routines.
// the new encrypt-then-sign behavior for everything EXCEPT Membership / MachineKey. We need to make it very clear that setting this
// to 'false' is a Very Bad Thing(tm).
return EncryptOrDecryptData(fEncrypt, buf, modifier, start, length, useValidationSymAlgo, useLegacyMode, ivType, !AppSettings.UseLegacyEncryption);
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length,
bool useValidationSymAlgo, bool useLegacyMode, IVType ivType, bool signData)
{
/* This algorithm is used to perform encryption or decryption of a buffer, along with optional signing (for encryption)
* or signature verification (for decryption). Possible operation modes are:
*
* ENCRYPT + SIGN DATA (fEncrypt = true, signData = true)
* Input: buf represents plaintext to encrypt, modifier represents data to be appended to buf (but isn't part of the plaintext itself)
* Output: E(iv + buf + modifier) + HMAC(E(iv + buf + modifier))
*
* ONLY ENCRYPT DATA (fEncrypt = true, signData = false)
* Input: buf represents plaintext to encrypt, modifier represents data to be appended to buf (but isn't part of the plaintext itself)
* Output: E(iv + buf + modifier)
*
* VERIFY + DECRYPT DATA (fEncrypt = false, signData = true)
* Input: buf represents ciphertext to decrypt, modifier represents data to be removed from the end of the plaintext (since it's not really plaintext data)
* Input (buf): E(iv + m + modifier) + HMAC(E(iv + m + modifier))
* Output: m
*
* ONLY DECRYPT DATA (fEncrypt = false, signData = false)
* Input: buf represents ciphertext to decrypt, modifier represents data to be removed from the end of the plaintext (since it's not really plaintext data)
* Input (buf): E(iv + plaintext + modifier)
* Output: m
*
* The 'iv' in the above descriptions isn't an actual IV. Rather, if ivType = IVType.Random, we'll prepend random bytes ('iv')
* to the plaintext before feeding it to the crypto algorithms. Introducing randomness early in the algorithm prevents users
* from inspecting two ciphertexts to see if the plaintexts are related. If ivType = IVType.None, then 'iv' is simply
* an empty string. If ivType = IVType.Hash, we use a non-keyed hash of the plaintext.
*
* The 'modifier' in the above descriptions is a piece of metadata that should be encrypted along with the plaintext but
* which isn't actually part of the plaintext itself. It can be used for storing things like the user name for whom this
* plaintext was generated, the page that generated the plaintext, etc. On decryption, the modifier parameter is compared
* against the modifier stored in the crypto stream, and it is stripped from the message before the plaintext is returned.
*
* In all cases, if something goes wrong (e.g. invalid padding, invalid signature, invalid modifier, etc.), a generic exception is thrown.
*/
try {
EnsureConfig();
if (!fEncrypt && signData) {
if (start != 0 || length != buf.Length) {
// These transformations assume that we're operating on buf in its entirety and
// not on any subset of buf, so we'll just replace buf with the particular subset
// we're interested in.
byte[] bTemp = new byte[length];
Buffer.BlockCopy(buf, start, bTemp, 0, length);
buf = bTemp;
start = 0;
}
// buf actually contains E(iv + m + modifier) + HMAC(E(iv + m + modifier)), so we need to verify and strip off the signature
buf = GetUnHashedData(buf);
// At this point, buf contains only E(iv + m + modifier) if the signature check succeeded.
if (buf == null) {
// signature verification failed
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
// need to fix up again since GetUnhashedData() returned a different array
length = buf.Length;
}
if (useLegacyMode)
useLegacyMode = _UsingCustomEncryption; // only use legacy mode for custom algorithms
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ICryptoTransform cryptoTransform = GetCryptoTransform(fEncrypt, useValidationSymAlgo, useLegacyMode);
CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write);
// DevDiv Bugs 137864: Add IV to beginning of data to be encrypted.
// IVType.None is used by MembershipProvider which requires compatibility even in SP2 mode (and will set signData = false).
// MSRC 10405: If signData is set to true, we must generate an IV.
bool createIV = signData || ((ivType != IVType.None) && (CompatMode > MachineKeyCompatibilityMode.Framework20SP1));
if (fEncrypt && createIV) {
int ivLength = (useValidationSymAlgo ? _IVLengthValidation : _IVLengthDecryption);
byte[] iv = null;
switch (ivType) {
case IVType.Hash:
// iv := H(buf)
iv = GetIVHash(buf, ivLength);
break;
case IVType.Random:
// iv := [random]
iv = new byte[ivLength];
RandomNumberGenerator.GetBytes(iv);
break;
}
cs.Write(iv, 0, iv.Length);
}
cs.Write(buf, start, length);
if (fEncrypt && modifier != null) {
cs.Write(modifier, 0, modifier.Length);
}
cs.FlushFinalBlock();
byte[] paddedData = ms.ToArray();
// At this point:
// If fEncrypt = true (encrypting), paddedData := Enc(iv + buf + modifier)
// If fEncrypt = false (decrypting), paddedData := iv + plaintext + modifier
byte[] bData;
cs.Close();
// In ASP.NET 2.0, we pool ICryptoTransform objects, and this returns that ICryptoTransform
// to the pool. In ASP.NET 4.0, this just disposes of the ICryptoTransform object.
ReturnCryptoTransform(fEncrypt, cryptoTransform, useValidationSymAlgo, useLegacyMode);
// DevDiv Bugs 137864: Strip IV from beginning of unencrypted data
if (!fEncrypt && createIV) {
// strip off the first bytes that were random bits
int ivLength = (useValidationSymAlgo ? _IVLengthValidation : _IVLengthDecryption);
int bDataLength = paddedData.Length - ivLength;
if (bDataLength < 0) {
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
bData = new byte[bDataLength];
Buffer.BlockCopy(paddedData, ivLength, bData, 0, bDataLength);
} else {
bData = paddedData;
}
// At this point:
// If fEncrypt = true (encrypting), bData := Enc(iv + buf + modifier)
// If fEncrypt = false (decrypting), bData := plaintext + modifier
if (!fEncrypt && modifier != null && modifier.Length > 0) {
// MSRC 10405: Crypto board suggests blinding where signature failed
// to prevent timing attacks.
bool modifierCheckFailed = false;
for (int iter = 0; iter < modifier.Length; iter++)
if (bData[bData.Length - modifier.Length + iter] != modifier[iter])
modifierCheckFailed = true;
if (modifierCheckFailed) {
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
byte[] bData2 = new byte[bData.Length - modifier.Length];
Buffer.BlockCopy(bData, 0, bData2, 0, bData2.Length);
bData = bData2;
}
// At this point:
// If fEncrypt = true (encrypting), bData := Enc(iv + buf + modifier)
// If fEncrypt = false (decrypting), bData := plaintext
if (fEncrypt && signData) {
byte[] hmac = HashData(bData, null, 0, bData.Length);
byte[] bData2 = new byte[bData.Length + hmac.Length];
Buffer.BlockCopy(bData, 0, bData2, 0, bData.Length);
Buffer.BlockCopy(hmac, 0, bData2, bData.Length, hmac.Length);
bData = bData2;
}
// At this point:
// If fEncrypt = true (encrypting), bData := Enc(iv + buf + modifier) + HMAC(Enc(iv + buf + modifier))
// If fEncrypt = false (decrypting), bData := plaintext
// And we're done
return bData;
}
catch {
// It's important that we don't propagate the original exception here as we don't want a production
// server which has unintentionally left YSODs enabled to leak cryptographic information.
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
}
private static byte[] GetIVHash(byte[] buf, int ivLength)
{
// return an IV that is computed as a hash of the buffer
int bytesToWrite = ivLength;
int bytesWritten = 0;
byte[] iv = new byte[ivLength];
// get SHA1 hash of the buffer and copy to the IV.
// if hash length is less than IV length, re-hash the hash and
// append until IV is full.
byte[] hash = buf;
while (bytesWritten < ivLength) {
byte[] newHash = new byte[_HashSize];
int hr = UnsafeNativeMethods.GetSHA1Hash(hash, hash.Length, newHash, newHash.Length);
Marshal.ThrowExceptionForHR(hr);
hash = newHash;
int bytesToCopy = Math.Min(_HashSize, bytesToWrite);
Buffer.BlockCopy(hash, 0, iv, bytesWritten, bytesToCopy);
bytesWritten += bytesToCopy;
bytesToWrite -= bytesToCopy;
}
return iv;
}
private static RNGCryptoServiceProvider RandomNumberGenerator
{
get
{
if (s_randomNumberGenerator == null) {
s_randomNumberGenerator = new RNGCryptoServiceProvider();
}
return s_randomNumberGenerator;
}
}
private static void SetInnerOuterKeys(byte[] validationKey, ref byte[] inner, ref byte[] outer)
{
byte[] key = null;
if (validationKey.Length > _AutoGenValidationKeySize) {
key = new byte[_HashSize];
int hr = UnsafeNativeMethods.GetSHA1Hash(validationKey, validationKey.Length, key, key.Length);
Marshal.ThrowExceptionForHR(hr);
}
if (inner == null)
inner = new byte[_AutoGenValidationKeySize];
if (outer == null)
outer = new byte[_AutoGenValidationKeySize];
int i;
for (i = 0; i < _AutoGenValidationKeySize; i++) {
inner[i] = 0x36;
outer[i] = 0x5C;
}
for (i = 0; i < validationKey.Length; i++) {
inner[i] ^= validationKey[i];
outer[i] ^= validationKey[i];
}
}
private static byte[] GetHMACSHA1Hash(byte[] buf, byte[] modifier, int start, int length)
{
if (start < 0 || start > buf.Length)
throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "start"));
if (length < 0 || buf == null || (start + length) > buf.Length)
throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "length"));
byte[] hash = new byte[_HashSize];
int hr = UnsafeNativeMethods.GetHMACSHA1Hash(buf, start, length,
modifier, (modifier == null) ? 0 : modifier.Length,
s_inner, s_inner.Length, s_outer, s_outer.Length,
hash, hash.Length);
if (hr == 0)
return hash;
_UseHMACSHA = false;
return null;
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static string HashAndBase64EncodeString(string s)
{
byte[] ab;
byte[] hash;
string result;
ab = Encoding.Unicode.GetBytes(s);
hash = HashData(ab, null, 0, ab.Length);
result = Convert.ToBase64String(hash);
return result;
}
static internal void DestroyByteArray(byte[] buf)
{
if (buf == null || buf.Length < 1)
return;
for (int iter = 0; iter < buf.Length; iter++)
buf[iter] = (byte)0;
}
internal void DestroyKeys()
{
MachineKeySection.DestroyByteArray(_ValidationKey);
MachineKeySection.DestroyByteArray(_DecryptionKey);
}
static void EnsureConfig()
{
if (!s_initComplete) {
lock (s_initLock) {
if (!s_initComplete) {
GetApplicationConfig(); // sets s_config field
s_config.ConfigureEncryptionObject();
s_initComplete = true;
}
}
}
}
private static MachineKeySection machineKeySection = new MachineKeySection();
// gets the application-level MachineKeySection
internal static MachineKeySection GetApplicationConfig()
{
return s_config = machineKeySection;
}
// NOTE: When encoding the data, this method *may* return the same reference to the input "buf" parameter
// with the hash appended in the end if there's enough space. The "length" parameter would also be
// appropriately adjusted in those cases. This is an optimization to prevent unnecessary copying of
// buffers.
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] GetEncodedData(byte[] buf, byte[] modifier, int start, ref int length)
{
EnsureConfig();
byte[] bHash = HashData(buf, modifier, start, length);
byte[] returnBuffer;
if (buf.Length - start - length >= bHash.Length) {
// Append hash to end of buffer if there's space
Buffer.BlockCopy(bHash, 0, buf, start + length, bHash.Length);
returnBuffer = buf;
} else {
returnBuffer = new byte[length + bHash.Length];
Buffer.BlockCopy(buf, start, returnBuffer, 0, length);
Buffer.BlockCopy(bHash, 0, returnBuffer, length, bHash.Length);
start = 0;
}
length += bHash.Length;
if (s_config.Validation == MachineKeyValidation.TripleDES || s_config.Validation == MachineKeyValidation.AES) {
returnBuffer = EncryptOrDecryptData(true, returnBuffer, modifier, start, length, true);
length = returnBuffer.Length;
}
return returnBuffer;
}
// NOTE: When decoding the data, this method *may* return the same reference to the input "buf" parameter
// with the "dataLength" parameter containing the actual length of the data in the "buf" (i.e. length of actual
// data is (total length of data - hash length)). This is an optimization to prevent unnecessary copying of buffers.
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] GetDecodedData(byte[] buf, byte[] modifier, int start, int length, ref int dataLength)
{
EnsureConfig();
if (s_config.Validation == MachineKeyValidation.TripleDES || s_config.Validation == MachineKeyValidation.AES) {
buf = EncryptOrDecryptData(false, buf, modifier, start, length, true);
if (buf == null || buf.Length < _HashSize)
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
length = buf.Length;
start = 0;
}
if (length < _HashSize || start < 0 || start >= length)
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
byte[] bHash = HashData(buf, modifier, start, length - _HashSize);
for (int iter = 0; iter < bHash.Length; iter++)
if (bHash[iter] != buf[start + length - _HashSize + iter])
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
dataLength = length - _HashSize;
return buf;
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] HashData(byte[] buf, byte[] modifier, int start, int length)
{
EnsureConfig();
if (s_config.Validation == MachineKeyValidation.MD5)
return HashDataUsingNonKeyedAlgorithm(null, buf, modifier, start, length, s_validationKey);
if (_UseHMACSHA) {
byte[] hash = GetHMACSHA1Hash(buf, modifier, start, length);
if (hash != null)
return hash;
}
if (_CustomValidationTypeIsKeyed) {
return HashDataUsingKeyedAlgorithm(KeyedHashAlgorithm.Create(_CustomValidationName),
buf, modifier, start, length, s_validationKey);
} else {
return HashDataUsingNonKeyedAlgorithm(HashAlgorithm.Create(_CustomValidationName),
buf, modifier, start, length, s_validationKey);
}
}
private void ConfigureEncryptionObject()
{
// We suppress CS0618 since some of the algorithms we support are marked with [Obsolete].
// These deprecated algorithms are *not* enabled by default. Developers must opt-in to
// them, so we're secure by default.
#pragma warning disable 618
//using (new ApplicationImpersonationContext()) {
s_validationKey = ValidationKeyInternal;
byte[] dKey = DecryptionKeyInternal;
if (_UseHMACSHA)
SetInnerOuterKeys(s_validationKey, ref s_inner, ref s_outer);
DestroyKeys();
switch (Decryption) {
case "3DES":
s_oSymAlgoDecryption = CryptoAlgorithms.CreateTripleDES();
break;
case "DES":
s_oSymAlgoDecryption = CryptoAlgorithms.CreateDES();
break;
case "AES":
s_oSymAlgoDecryption = CryptoAlgorithms.CreateAes();
break;
case "Auto":
if (dKey.Length == 8) {
s_oSymAlgoDecryption = CryptoAlgorithms.CreateDES();
} else {
s_oSymAlgoDecryption = CryptoAlgorithms.CreateAes();
}
break;
}
if (s_oSymAlgoDecryption == null) // Shouldn't happen!
InitValidationAndEncyptionSizes();
switch (Validation) {
case MachineKeyValidation.TripleDES:
if (dKey.Length == 8) {
s_oSymAlgoValidation = CryptoAlgorithms.CreateDES();
} else {
s_oSymAlgoValidation = CryptoAlgorithms.CreateTripleDES();
}
break;
case MachineKeyValidation.AES:
s_oSymAlgoValidation = CryptoAlgorithms.CreateAes();
break;
}
// The IV lengths should actually be equal to the block sizes rather than the key
// sizes, but we shipped with this code and unfortunately cannot change it without
// breaking back-compat.
if (s_oSymAlgoValidation != null) {
SetKeyOnSymAlgorithm(s_oSymAlgoValidation, dKey);
_IVLengthValidation = RoundupNumBitsToNumBytes(s_oSymAlgoValidation.KeySize);
}
SetKeyOnSymAlgorithm(s_oSymAlgoDecryption, dKey);
_IVLengthDecryption = RoundupNumBitsToNumBytes(s_oSymAlgoDecryption.KeySize);
InitLegacyEncAlgorithm(dKey);
DestroyByteArray(dKey);
//}
#pragma warning restore 618
}
private void SetKeyOnSymAlgorithm(SymmetricAlgorithm symAlgo, byte[] dKey)
{
try {
if (dKey.Length > 8 && symAlgo is DESCryptoServiceProvider) {
byte[] bTemp = new byte[8];
Buffer.BlockCopy(dKey, 0, bTemp, 0, 8);
symAlgo.Key = bTemp;
DestroyByteArray(bTemp);
} else {
symAlgo.Key = dKey;
}
symAlgo.GenerateIV();
symAlgo.IV = new byte[symAlgo.IV.Length];
}
catch (Exception e) {
throw new InvalidOperationException(SR.GetString(SR.Bad_machine_key, e.Message));
}
}
private static ICryptoTransform GetCryptoTransform(bool fEncrypt, bool useValidationSymAlgo, bool legacyMode)
{
SymmetricAlgorithm algo = (legacyMode ? s_oSymAlgoLegacy : (useValidationSymAlgo ? s_oSymAlgoValidation : s_oSymAlgoDecryption));
lock (algo)
return (fEncrypt ? algo.CreateEncryptor() : algo.CreateDecryptor());
}
private static void ReturnCryptoTransform(bool fEncrypt, ICryptoTransform ct, bool useValidationSymAlgo, bool legacyMode)
{
ct.Dispose();
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
static byte[] s_ahexval;
// This API is obsolete because it is insecure: invalid hex chars are silently replaced with '0',
// which can reduce the overall security of the system. But unfortunately, some code is dependent
// on this broken behavior.
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
static internal byte[] HexStringToByteArray(String str)
{
if (((uint)str.Length & 0x1) == 0x1) // must be 2 nibbles per byte
{
return null;
}
byte[] ahexval = s_ahexval; // initialize a table for faster lookups
if (ahexval == null) {
ahexval = new byte['f' + 1];
for (int i = ahexval.Length; --i >= 0;) {
if ('0' <= i && i <= '9') {
ahexval[i] = (byte)(i - '0');
} else if ('a' <= i && i <= 'f') {
ahexval[i] = (byte)(i - 'a' + 10);
} else if ('A' <= i && i <= 'F') {
ahexval[i] = (byte)(i - 'A' + 10);
}
}
s_ahexval = ahexval;
}
byte[] result = new byte[str.Length / 2];
int istr = 0, ir = 0;
int n = result.Length;
while (--n >= 0) {
int c1, c2;
try {
c1 = ahexval[str[istr++]];
}
catch (ArgumentNullException) {
c1 = 0;
return null;// Inavlid char
}
catch (ArgumentException) {
c1 = 0;
return null;// Inavlid char
}
catch (IndexOutOfRangeException) {
c1 = 0;
return null;// Inavlid char
}
try {
c2 = ahexval[str[istr++]];
}
catch (ArgumentNullException) {
c2 = 0;
return null;// Inavlid char
}
catch (ArgumentException) {
c2 = 0;
return null;// Inavlid char
}
catch (IndexOutOfRangeException) {
c2 = 0;
return null;// Inavlid char
}
result[ir++] = (byte)((c1 << 4) + c2);
}
return result;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private void InitValidationAndEncyptionSizes()
{
_CustomValidationName = ValidationAlgorithm;
_CustomValidationTypeIsKeyed = true;
switch (ValidationAlgorithm) {
case "AES":
case "3DES":
_UseHMACSHA = true;
_HashSize = SHA1_HASH_SIZE;
_AutoGenValidationKeySize = SHA1_KEY_SIZE;
break;
case "SHA1":
_UseHMACSHA = true;
_HashSize = SHA1_HASH_SIZE;
_AutoGenValidationKeySize = SHA1_KEY_SIZE;
break;
case "MD5":
_CustomValidationTypeIsKeyed = false;
_UseHMACSHA = false;
_HashSize = MD5_HASH_SIZE;
_AutoGenValidationKeySize = MD5_KEY_SIZE;
break;
case "HMACSHA256":
_UseHMACSHA = true;
_HashSize = HMACSHA256_HASH_SIZE;
_AutoGenValidationKeySize = HMACSHA256_KEY_SIZE;
break;
case "HMACSHA384":
_UseHMACSHA = true;
_HashSize = HMACSHA384_HASH_SIZE;
_AutoGenValidationKeySize = HMACSHA384_KEY_SIZE;
break;
case "HMACSHA512":
_UseHMACSHA = true;
_HashSize = HMACSHA512_HASH_SIZE;
_AutoGenValidationKeySize = HMACSHA512_KEY_SIZE;
break;
default:
_UseHMACSHA = false;
if (!_CustomValidationName.StartsWith(ALGO_PREFIX, StringComparison.Ordinal)) {
throw new InvalidOperationException(SR.GetString(SR.Wrong_validation_enum));
}
_CustomValidationName = _CustomValidationName.Substring(ALGO_PREFIX.Length);
HashAlgorithm alg = null;
try {
_CustomValidationTypeIsKeyed = false;
alg = HashAlgorithm.Create(_CustomValidationName);
}
catch (Exception e) {
throw new InvalidOperationException(SR.GetString(SR.Wrong_validation_enum), e);
}
if (alg == null)
throw new InvalidOperationException(SR.GetString(SR.Wrong_validation_enum));
_AutoGenValidationKeySize = 0;
_HashSize = 0;
_CustomValidationTypeIsKeyed = (alg is KeyedHashAlgorithm);
if (!_CustomValidationTypeIsKeyed) {
throw new InvalidOperationException(SR.GetString(SR.Wrong_validation_enum));
}
try {
_HashSize = RoundupNumBitsToNumBytes(alg.HashSize);
if (_CustomValidationTypeIsKeyed)
_AutoGenValidationKeySize = ((KeyedHashAlgorithm)alg).Key.Length;
if (_AutoGenValidationKeySize < 1)
_AutoGenValidationKeySize = RoundupNumBitsToNumBytes(alg.InputBlockSize);
if (_AutoGenValidationKeySize < 1)
_AutoGenValidationKeySize = RoundupNumBitsToNumBytes(alg.OutputBlockSize);
}
catch { }
if (_HashSize < 1 || _AutoGenValidationKeySize < 1) {
// If we didn't get the hash-size or key-size, perform a hash and get the sizes
byte[] buf = new byte[10];
byte[] buf2 = new byte[512];
RandomNumberGenerator.GetBytes(buf);
RandomNumberGenerator.GetBytes(buf2);
byte[] bHash = alg.ComputeHash(buf);
_HashSize = bHash.Length;
if (_AutoGenValidationKeySize < 1) {
if (_CustomValidationTypeIsKeyed)
_AutoGenValidationKeySize = ((KeyedHashAlgorithm)alg).Key.Length;
else
_AutoGenValidationKeySize = RoundupNumBitsToNumBytes(alg.InputBlockSize);
}
alg.Clear();
}
if (_HashSize < 1)
_HashSize = HMACSHA512_HASH_SIZE;
if (_AutoGenValidationKeySize < 1)
_AutoGenValidationKeySize = HMACSHA512_KEY_SIZE;
break;
}
_AutoGenDecryptionKeySize = 0;
switch (Decryption) {
case "AES":
_AutoGenDecryptionKeySize = 24;
break;
case "3DES":
_AutoGenDecryptionKeySize = 24;
break;
case "Auto":
_AutoGenDecryptionKeySize = 24;
break;
case "DES":
if (ValidationAlgorithm == "AES" || ValidationAlgorithm == "3DES")
_AutoGenDecryptionKeySize = 24;
else
_AutoGenDecryptionKeySize = 8;
break;
default:
_UsingCustomEncryption = true;
if (!Decryption.StartsWith(ALGO_PREFIX, StringComparison.Ordinal)) {
throw new InvalidOperationException(SR.GetString(SR.Wrong_decryption_enum));
}
try {
s_oSymAlgoDecryption = SymmetricAlgorithm.Create(Decryption.Substring(ALGO_PREFIX.Length));
}
catch (Exception e) {
throw new InvalidOperationException(SR.GetString(SR.Wrong_decryption_enum), e);
}
if (s_oSymAlgoDecryption == null)
throw new InvalidOperationException(SR.GetString(SR.Wrong_decryption_enum));
_AutoGenDecryptionKeySize = RoundupNumBitsToNumBytes(s_oSymAlgoDecryption.KeySize);
break;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
internal static int RoundupNumBitsToNumBytes(int numBits)
{
if (numBits < 0)
return 0;
return (numBits / 8) + (((numBits & 7) != 0) ? 1 : 0);
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private static byte[] HashDataUsingNonKeyedAlgorithm(HashAlgorithm hashAlgo, byte[] buf, byte[] modifier,
int start, int length, byte[] validationKey)
{
int totalLength = length + validationKey.Length + ((modifier != null) ? modifier.Length : 0);
byte[] bAll = new byte[totalLength];
Buffer.BlockCopy(buf, start, bAll, 0, length);
if (modifier != null) {
Buffer.BlockCopy(modifier, 0, bAll, length, modifier.Length);
}
Buffer.BlockCopy(validationKey, 0, bAll, length, validationKey.Length);
if (hashAlgo != null) {
return hashAlgo.ComputeHash(bAll);
} else {
byte[] newHash = new byte[MD5_HASH_SIZE];
int hr = UnsafeNativeMethods.GetSHA1Hash(bAll, bAll.Length, newHash, newHash.Length);
Marshal.ThrowExceptionForHR(hr);
return newHash;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private static byte[] HashDataUsingKeyedAlgorithm(KeyedHashAlgorithm hashAlgo, byte[] buf, byte[] modifier,
int start, int length, byte[] validationKey)
{
int totalLength = length + ((modifier != null) ? modifier.Length : 0);
byte[] bAll = new byte[totalLength];
Buffer.BlockCopy(buf, start, bAll, 0, length);
if (modifier != null) {
Buffer.BlockCopy(modifier, 0, bAll, length, modifier.Length);
}
hashAlgo.Key = validationKey;
return hashAlgo.ComputeHash(bAll);
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] GetUnHashedData(byte[] bufHashed)
{
if (!VerifyHashedData(bufHashed))
return null;
byte[] buf2 = new byte[bufHashed.Length - _HashSize];
Buffer.BlockCopy(bufHashed, 0, buf2, 0, buf2.Length);
return buf2;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static bool VerifyHashedData(byte[] bufHashed)
{
EnsureConfig();
//////////////////////////////////////////////////////////////////////
// Step 1: Get the MAC: Last [HashSize] bytes
if (bufHashed.Length <= _HashSize)
return false;
byte[] bMac = HashData(bufHashed, null, 0, bufHashed.Length - _HashSize);
//////////////////////////////////////////////////////////////////////
// Step 2: Make sure the MAC has expected length
if (bMac == null || bMac.Length != _HashSize)
return false;
int lastPos = bufHashed.Length - _HashSize;
// From Tolga: To prevent a timing attack, we should verify the entire hash instead of failing
// early the first time we see a mismatched byte.
bool hashCheckFailed = false;
for (int iter = 0; iter < _HashSize; iter++)
if (bMac[iter] != bufHashed[lastPos + iter])
hashCheckFailed = true;
return !hashCheckFailed;
}
internal static bool UsingCustomEncryption
{
get
{
EnsureConfig();
return _UsingCustomEncryption;
}
}
private static void InitLegacyEncAlgorithm(byte[] dKey)
{
if (!_UsingCustomEncryption)
return;
s_oSymAlgoLegacy = CryptoAlgorithms.CreateAes();
try {
s_oSymAlgoLegacy.Key = dKey;
}
catch {
if (dKey.Length <= 24)
throw;
byte[] buf = new byte[24];
Buffer.BlockCopy(dKey, 0, buf, 0, buf.Length);
dKey = buf;
s_oSymAlgoLegacy.Key = dKey;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.