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.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Execution;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.MSBuild
{
internal abstract class ProjectFile : IProjectFile
{
private readonly ProjectFileLoader _loader;
private readonly MSB.Evaluation.Project _loadedProject;
public ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project loadedProject)
{
_loader = loader;
_loadedProject = loadedProject;
}
~ProjectFile()
{
try
{
// unload project so collection will release global strings
_loadedProject.ProjectCollection.UnloadAllProjects();
}
catch
{
}
}
public virtual string FilePath
{
get { return _loadedProject.FullPath; }
}
public string GetPropertyValue(string name)
{
return _loadedProject.GetPropertyValue(name);
}
public abstract SourceCodeKind GetSourceCodeKind(string documentFileName);
public abstract string GetDocumentExtension(SourceCodeKind kind);
public abstract Task<ProjectFileInfo> GetProjectFileInfoAsync(CancellationToken cancellationToken);
protected class BuildResult
{
public readonly MSB.Execution.BuildResult Result;
public readonly MSB.Execution.ProjectInstance Instance;
internal BuildResult(MSB.Execution.BuildResult result, MSB.Execution.ProjectInstance instance)
{
this.Result = result;
this.Instance = instance;
}
}
protected async Task<BuildResult> BuildAsync(string taskName, MSB.Framework.ITaskHost taskHost, CancellationToken cancellationToken)
{
// prepare for building
var buildTargets = new BuildTargets(_loadedProject, "Compile");
// Don't execute this one. It will build referenced projects.
// Even when DesignTimeBuild is defined, it will still add the referenced project's output to the references list
// which we don't want.
buildTargets.Remove("ResolveProjectReferences");
// don't execute anything after CoreCompile target, since we've
// already done everything we need to compute compiler inputs by then.
buildTargets.RemoveAfter("CoreCompile", includeTargetInRemoval: false);
// create a project instance to be executed by build engine.
// The executed project will hold the final model of the project after execution via msbuild.
var executedProject = _loadedProject.CreateProjectInstance();
var hostServices = new Microsoft.Build.Execution.HostServices();
// connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
hostServices.RegisterHostObject(_loadedProject.FullPath, "CoreCompile", taskName, taskHost);
var buildParameters = new MSB.Execution.BuildParameters(_loadedProject.ProjectCollection);
var buildRequestData = new MSB.Execution.BuildRequestData(executedProject, buildTargets.Targets, hostServices);
var result = await this.BuildAsync(buildParameters, buildRequestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (result.Exception != null)
{
throw result.Exception;
}
return new BuildResult(result, executedProject);
}
// this lock is static because we are using the default build manager, and there is only one per process
private static readonly AsyncSemaphore s_buildManagerLock = new AsyncSemaphore(1);
private async Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
// only allow one build to use the default build manager at a time
using (await s_buildManagerLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
{
return await BuildAsync(MSB.Execution.BuildManager.DefaultBuildManager, parameters, requestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
}
}
private static Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildManager buildManager, MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
var taskSource = new TaskCompletionSource<MSB.Execution.BuildResult>();
buildManager.BeginBuild(parameters);
// enable cancellation of build
CancellationTokenRegistration registration = default(CancellationTokenRegistration);
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(() =>
{
try
{
buildManager.CancelAllSubmissions();
buildManager.EndBuild();
registration.Dispose();
}
finally
{
taskSource.TrySetCanceled();
}
});
}
// execute build async
try
{
buildManager.PendBuildRequest(requestData).ExecuteAsync(sub =>
{
// when finished
try
{
var result = sub.BuildResult;
buildManager.EndBuild();
registration.Dispose();
taskSource.TrySetResult(result);
}
catch (Exception e)
{
taskSource.TrySetException(e);
}
}, null);
}
catch (Exception e)
{
taskSource.SetException(e);
}
return taskSource.Task;
}
protected virtual string GetOutputDirectory()
{
var targetPath = _loadedProject.GetPropertyValue("TargetPath");
if (string.IsNullOrEmpty(targetPath))
{
targetPath = _loadedProject.DirectoryPath;
}
return Path.GetDirectoryName(this.GetAbsolutePath(targetPath));
}
protected virtual string GetAssemblyName()
{
var assemblyName = _loadedProject.GetPropertyValue("AssemblyName");
if (string.IsNullOrEmpty(assemblyName))
{
assemblyName = Path.GetFileNameWithoutExtension(_loadedProject.FullPath);
}
return PathUtilities.GetFileName(assemblyName);
}
protected virtual IEnumerable<ProjectFileReference> GetProjectReferences(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("ProjectReference")
.Select(reference => new ProjectFileReference(
path: reference.EvaluatedInclude,
aliases: ImmutableArray<string>.Empty));
}
protected IEnumerable<ProjectItemInstance> GetProjectReferenceItems(ProjectInstance executedProject)
{
return executedProject
.GetItems("ProjectReference")
.Where(i => !string.Equals(
i.GetMetadataValue("ReferenceOutputAssembly"),
bool.FalseString,
StringComparison.OrdinalIgnoreCase));
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetDocumentsFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Compile");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetMetadataReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("ReferencePath");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAnalyzerReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Analyzer");
}
public MSB.Evaluation.ProjectProperty GetProperty(string name)
{
return _loadedProject.GetProperty(name);
}
protected IEnumerable<MSB.Framework.ITaskItem> GetTaskItems(MSB.Execution.ProjectInstance executedProject, string itemType)
{
return executedProject.GetItems(itemType);
}
protected string GetItemString(MSB.Execution.ProjectInstance executedProject, string itemType)
{
string text = "";
foreach (var item in executedProject.GetItems(itemType))
{
if (text.Length > 0)
{
text = text + " ";
}
text = text + item.EvaluatedInclude;
}
return text;
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return this.ReadPropertyString(executedProject, propertyName, propertyName);
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
var executedProperty = executedProject.GetProperty(executedPropertyName);
if (executedProperty != null)
{
return executedProperty.EvaluatedValue;
}
var evaluatedProperty = _loadedProject.GetProperty(evaluatedPropertyName);
if (evaluatedProperty != null)
{
return evaluatedProperty.EvaluatedValue;
}
return null;
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, propertyName));
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static bool ConvertToBool(string value)
{
return value != null && (string.Equals("true", value, StringComparison.OrdinalIgnoreCase) ||
string.Equals("On", value, StringComparison.OrdinalIgnoreCase));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, propertyName));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static int ConvertToInt(string value)
{
if (value == null)
{
return 0;
}
else
{
int result;
int.TryParse(value, out result);
return result;
}
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToULong(ReadPropertyString(executedProject, propertyName));
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToULong(this.ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static ulong ConvertToULong(string value)
{
if (value == null)
{
return 0;
}
else
{
ulong result;
ulong.TryParse(value, out result);
return result;
}
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string propertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, propertyName));
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static TEnum? ConvertToEnum<TEnum>(string value)
where TEnum : struct
{
if (value == null)
{
return null;
}
else
{
TEnum result;
if (Enum.TryParse<TEnum>(value, out result))
{
return result;
}
else
{
return null;
}
}
}
/// <summary>
/// Resolves the given path that is possibly relative to the project directory.
/// </summary>
/// <remarks>
/// The resulting path is absolute but might not be normalized.
/// </remarks>
protected string GetAbsolutePath(string path)
{
// TODO (tomat): should we report an error when drive-relative path (e.g. "C:foo.cs") is encountered?
return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, _loadedProject.DirectoryPath) ?? path);
}
protected string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem)
{
return GetAbsolutePath(documentItem.ItemSpec);
}
protected static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem)
{
return !string.IsNullOrEmpty(documentItem.GetMetadata("Link"));
}
private IDictionary<string, MSB.Evaluation.ProjectItem> _documents = null;
protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem)
{
if (_documents == null)
{
_documents = new Dictionary<string, MSB.Evaluation.ProjectItem>();
foreach (var item in _loadedProject.GetItems("compile"))
{
_documents[GetAbsolutePath(item.EvaluatedInclude)] = item;
}
}
return !_documents.ContainsKey(GetAbsolutePath(documentItem.ItemSpec));
}
protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory)
{
var link = documentItem.GetMetadata("Link");
if (!string.IsNullOrEmpty(link))
{
// if a specific link is specified in the project file then use it to form the logical path.
return link;
}
else
{
var result = documentItem.ItemSpec;
if (Path.IsPathRooted(result))
{
// If we have an absolute path, there are two possibilities:
result = Path.GetFullPath(result);
// If the document is within the current project directory (or subdirectory), then the logical path is the relative path
// from the project's directory.
if (result.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase))
{
result = result.Substring(projectDirectory.Length);
}
else
{
// if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project.
// if more than one document ends up with the same logical name then so be it (the workspace will survive.)
return Path.GetFileName(result);
}
}
return result;
}
}
protected string GetReferenceFilePath(ProjectItemInstance projectItem)
{
return GetAbsolutePath(projectItem.EvaluatedInclude);
}
public void AddDocument(string filePath, string logicalPath = null)
{
var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
Dictionary<string, string> metadata = null;
if (logicalPath != null && relativePath != logicalPath)
{
metadata = new Dictionary<string, string>();
metadata.Add("link", logicalPath);
relativePath = filePath; // link to full path
}
_loadedProject.AddItem("Compile", relativePath, metadata);
}
public void RemoveDocument(string filePath)
{
var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
var items = _loadedProject.GetItems("Compile");
var item = items.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var metadata = new Dictionary<string, string>();
if (!peRef.Properties.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", peRef.Properties.Aliases));
}
if (IsInGAC(peRef.FilePath) && identity != null)
{
_loadedProject.AddItem("Reference", identity.GetDisplayName(), metadata);
}
else
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath);
_loadedProject.AddItem("Reference", relativePath, metadata);
}
}
}
private bool IsInGAC(string filePath)
{
return filePath.Contains(@"\GAC_MSIL\");
}
public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var item = FindReferenceItem(identity, peRef.FilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath)
{
var references = _loadedProject.GetItems("Reference");
MSB.Evaluation.ProjectItem item = null;
if (identity != null)
{
var shortAssemblyName = identity.Name;
var fullAssemblyName = identity.ToAssemblyName().FullName;
// check for short name match
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
// check for full name match
if (item == null)
{
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
}
}
// check for file path match
if (item == null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
item = references.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath));
}
// check for partial name match
if (item == null && identity != null)
{
var partialName = identity.Name + ",";
var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList();
if (items.Count == 1)
{
item = items[0];
}
}
return item;
}
public void AddProjectReference(string projectName, ProjectFileReference reference)
{
var metadata = new Dictionary<string, string>();
metadata.Add("Name", projectName);
if (!reference.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", reference.Aliases));
}
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path);
_loadedProject.AddItem("ProjectReference", relativePath, metadata);
}
public void RemoveProjectReference(string projectName, string projectFilePath)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
var item = FindProjectReferenceItem(projectName, projectFilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
private MSB.Evaluation.ProjectItem FindProjectReferenceItem(string projectName, string projectFilePath)
{
var references = _loadedProject.GetItems("ProjectReference");
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
MSB.Evaluation.ProjectItem item = null;
// find by project file path
item = references.First(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath));
// try to find by project name
if (item == null)
{
item = references.First(it => string.Compare(projectName, it.GetMetadataValue("Name"), StringComparison.OrdinalIgnoreCase) == 0);
}
return item;
}
public void AddAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
_loadedProject.AddItem("Analyzer", relativePath);
}
}
public void RemoveAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
var analyzers = _loadedProject.GetItems("Analyzer");
var item = analyzers.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
public void Save()
{
_loadedProject.Save();
}
internal static bool TryGetOutputKind(string outputKind, out OutputKind kind)
{
if (string.Equals(outputKind, "Library", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.DynamicallyLinkedLibrary;
return true;
}
else if (string.Equals(outputKind, "Exe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.ConsoleApplication;
return true;
}
else if (string.Equals(outputKind, "WinExe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsApplication;
return true;
}
else if (string.Equals(outputKind, "Module", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.NetModule;
return true;
}
else if (string.Equals(outputKind, "WinMDObj", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsRuntimeMetadata;
return true;
}
else
{
kind = OutputKind.DynamicallyLinkedLibrary;
return false;
}
}
}
}
| |
// Amplify Motion - Full-scene Motion Blur for Unity Pro
// Copyright (c) Amplify Creations, Lda <[email protected]>
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9
#define UNITY_4
#endif
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6 || UNITY_5_7 || UNITY_5_8 || UNITY_5_9
#define UNITY_5
#endif
#if UNITY_4 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2
#define UNITY_PRE_5_3
#endif
using System;
using System.Collections.Generic;
using UnityEngine;
#if !UNITY_4
using UnityEngine.Rendering;
#endif
namespace AmplifyMotion
{
public enum ObjectType
{
None,
Solid,
Skinned,
Cloth,
#if !UNITY_PRE_5_3
Particle
#endif
}
[Serializable]
internal abstract class MotionState
{
protected struct MaterialDesc
{
public Material material;
#if !UNITY_4
public MaterialPropertyBlock propertyBlock;
#endif
public bool coverage;
public bool cutoff;
}
protected struct Matrix3x4
{
public float m00, m01, m02, m03;
public float m10, m11, m12, m13;
public float m20, m21, m22, m23;
public Vector4 GetRow( int i )
{
if ( i == 0 )
return new Vector4( m00, m01, m02, m03 );
else if ( i == 1 )
return new Vector4( m10, m11, m12, m13 );
else if ( i == 2 )
return new Vector4( m20, m21, m22, m23 );
else
return new Vector4( 0, 0, 0, 1 );
}
public static implicit operator Matrix3x4( Matrix4x4 from )
{
Matrix3x4 to = new Matrix3x4();
to.m00 = from.m00; to.m01 = from.m01; to.m02 = from.m02; to.m03 = from.m03;
to.m10 = from.m10; to.m11 = from.m11; to.m12 = from.m12; to.m13 = from.m13;
to.m20 = from.m20; to.m21 = from.m21; to.m22 = from.m22; to.m23 = from.m23;
return to;
}
public static implicit operator Matrix4x4( Matrix3x4 from )
{
Matrix4x4 to = new Matrix4x4();
to.m00 = from.m00; to.m01 = from.m01; to.m02 = from.m02; to.m03 = from.m03;
to.m10 = from.m10; to.m11 = from.m11; to.m12 = from.m12; to.m13 = from.m13;
to.m20 = from.m20; to.m21 = from.m21; to.m22 = from.m22; to.m23 = from.m23;
to.m30 = to.m31 = to.m32 = 0;
to.m33 = 1;
return to;
}
public static Matrix3x4 operator * ( Matrix3x4 a, Matrix3x4 b )
{
Matrix3x4 to = new Matrix3x4();
to.m00 = a.m00 * b.m00 + a.m01 * b.m10 + a.m02 * b.m20;
to.m01 = a.m00 * b.m01 + a.m01 * b.m11 + a.m02 * b.m21;
to.m02 = a.m00 * b.m02 + a.m01 * b.m12 + a.m02 * b.m22;
to.m03 = a.m00 * b.m03 + a.m01 * b.m13 + a.m02 * b.m23 + a.m03;
to.m10 = a.m10 * b.m00 + a.m11 * b.m10 + a.m12 * b.m20;
to.m11 = a.m10 * b.m01 + a.m11 * b.m11 + a.m12 * b.m21;
to.m12 = a.m10 * b.m02 + a.m11 * b.m12 + a.m12 * b.m22;
to.m13 = a.m10 * b.m03 + a.m11 * b.m13 + a.m12 * b.m23 + a.m13;
to.m20 = a.m20 * b.m00 + a.m21 * b.m10 + a.m22 * b.m20;
to.m21 = a.m20 * b.m01 + a.m21 * b.m11 + a.m22 * b.m21;
to.m22 = a.m20 * b.m02 + a.m21 * b.m12 + a.m22 * b.m22;
to.m23 = a.m20 * b.m03 + a.m21 * b.m13 + a.m22 * b.m23 + a.m23;
return to;
}
}
public const int AsyncUpdateTimeout = 100;
protected bool m_error;
protected bool m_initialized;
protected Transform m_transform;
protected AmplifyMotionCamera m_owner;
protected AmplifyMotionObjectBase m_obj;
public AmplifyMotionCamera Owner { get { return m_owner; } }
public bool Initialized { get { return m_initialized; } }
public bool Error { get { return m_error; } }
public MotionState( AmplifyMotionCamera owner, AmplifyMotionObjectBase obj )
{
m_error = false;
m_initialized = false;
m_owner = owner;
m_obj = obj;
m_transform = obj.transform;
}
internal virtual void Initialize() { m_initialized = true; }
internal virtual void Shutdown() {}
internal virtual void AsyncUpdate() {}
#if UNITY_4
internal abstract void UpdateTransform( bool starting );
internal virtual void RenderVectors( Camera camera, float scale, AmplifyMotion.Quality quality ) {}
#else
internal abstract void UpdateTransform( CommandBuffer updateCB, bool starting );
internal virtual void RenderVectors( Camera camera, CommandBuffer renderCB, float scale, AmplifyMotion.Quality quality ) {}
#endif
internal virtual void RenderDebugHUD() {}
private static HashSet<Material> m_materialWarnings = new HashSet<Material>();
protected MaterialDesc[] ProcessSharedMaterials( Material[] mats )
{
MaterialDesc[] matsDesc = new MaterialDesc [ mats.Length ];
for ( int i = 0; i < mats.Length; i++ )
{
matsDesc[ i ].material = mats[ i ];
bool legacyCoverage = ( mats[ i ].GetTag( "RenderType", false ) == "TransparentCutout" );
#if UNITY_4
bool isCoverage = legacyCoverage;
matsDesc[ i ].coverage = mats[ i ].HasProperty( "_MainTex" ) && isCoverage;
#else
bool isCoverage = legacyCoverage || mats[ i ].IsKeywordEnabled( "_ALPHATEST_ON" );
matsDesc[ i ].propertyBlock = new MaterialPropertyBlock();
matsDesc[ i ].coverage = mats[ i ].HasProperty( "_MainTex" ) && isCoverage;
#endif
matsDesc[ i ].cutoff = mats[ i ].HasProperty( "_Cutoff" );
if ( isCoverage && !matsDesc[ i ].coverage && !m_materialWarnings.Contains( matsDesc[ i ].material ) )
{
Debug.LogWarning( "[AmplifyMotion] TransparentCutout material \"" + matsDesc[ i ].material.name + "\" {" + matsDesc[ i ].material.shader.name + "} not using _MainTex standard property." );
m_materialWarnings.Add( matsDesc[ i ].material );
}
}
return matsDesc;
}
protected static bool MatrixChanged( Matrix3x4 a, Matrix3x4 b )
{
if ( Vector4.SqrMagnitude( new Vector4( a.m00 - b.m00, a.m01 - b.m01, a.m02 - b.m02, a.m03 - b.m03 ) ) > 0.0f )
return true;
if ( Vector4.SqrMagnitude( new Vector4( a.m10 - b.m10, a.m11 - b.m11, a.m12 - b.m12, a.m13 - b.m13 ) ) > 0.0f )
return true;
if ( Vector4.SqrMagnitude( new Vector4( a.m20 - b.m20, a.m21 - b.m21, a.m22 - b.m22, a.m23 - b.m23 ) ) > 0.0f )
return true;
return false;
}
protected static void MulPoint3x4_XYZ( ref Vector3 result, ref Matrix3x4 mat, Vector4 vec )
{
result.x = mat.m00 * vec.x + mat.m01 * vec.y + mat.m02 * vec.z + mat.m03;
result.y = mat.m10 * vec.x + mat.m11 * vec.y + mat.m12 * vec.z + mat.m13;
result.z = mat.m20 * vec.x + mat.m21 * vec.y + mat.m22 * vec.z + mat.m23;
}
protected static void MulPoint3x4_XYZW( ref Vector3 result, ref Matrix3x4 mat, Vector4 vec )
{
result.x = mat.m00 * vec.x + mat.m01 * vec.y + mat.m02 * vec.z + mat.m03 * vec.w;
result.y = mat.m10 * vec.x + mat.m11 * vec.y + mat.m12 * vec.z + mat.m13 * vec.w;
result.z = mat.m20 * vec.x + mat.m21 * vec.y + mat.m22 * vec.z + mat.m23 * vec.w;
}
protected static void MulAddPoint3x4_XYZW( ref Vector3 result, ref Matrix3x4 mat, Vector4 vec )
{
result.x += mat.m00 * vec.x + mat.m01 * vec.y + mat.m02 * vec.z + mat.m03 * vec.w;
result.y += mat.m10 * vec.x + mat.m11 * vec.y + mat.m12 * vec.z + mat.m13 * vec.w;
result.z += mat.m20 * vec.x + mat.m21 * vec.y + mat.m22 * vec.z + mat.m23 * vec.w;
}
}
}
[AddComponentMenu( "" )]
public class AmplifyMotionObjectBase : MonoBehaviour
{
public enum MinMaxCurveState
{
Scalar = 0,
Curve = 1,
TwoCurves = 2,
TwoScalars = 3
}
internal static bool ApplyToChildren = true;
[SerializeField] private bool m_applyToChildren = ApplyToChildren;
private AmplifyMotion.ObjectType m_type = AmplifyMotion.ObjectType.None;
private Dictionary<Camera, AmplifyMotion.MotionState> m_states = new Dictionary<Camera, AmplifyMotion.MotionState>();
private bool m_fixedStep = false;
private int m_objectId = 0;
private Vector3 m_lastPosition = Vector3.zero;
internal bool FixedStep { get { return m_fixedStep; } }
internal int ObjectId { get { return m_objectId; } }
private int m_resetAtFrame = -1;
public AmplifyMotion.ObjectType Type { get { return m_type; } }
internal void RegisterCamera( AmplifyMotionCamera camera )
{
Camera actual = camera.GetComponent<Camera>();
if ( ( actual.cullingMask & ( 1 << gameObject.layer ) ) != 0 && !m_states.ContainsKey( actual ) )
{
AmplifyMotion.MotionState state = null;
switch ( m_type )
{
case AmplifyMotion.ObjectType.Solid:
state = new AmplifyMotion.SolidState( camera, this ); break;
case AmplifyMotion.ObjectType.Skinned:
state = new AmplifyMotion.SkinnedState( camera, this ); break;
case AmplifyMotion.ObjectType.Cloth:
state = new AmplifyMotion.ClothState( camera, this ); break;
#if !UNITY_PRE_5_3
case AmplifyMotion.ObjectType.Particle:
state = new AmplifyMotion.ParticleState( camera, this ); break;
#endif
default:
throw new Exception( "[AmplifyMotion] Invalid object type." );
}
camera.RegisterObject( this );
m_states.Add( actual, state );
}
}
internal void UnregisterCamera( AmplifyMotionCamera camera )
{
AmplifyMotion.MotionState state;
Camera actual = camera.GetComponent<Camera>();
if ( m_states.TryGetValue( actual, out state ) )
{
camera.UnregisterObject( this );
if ( m_states.TryGetValue( actual, out state ) )
state.Shutdown();
m_states.Remove( actual );
}
}
bool InitializeType()
{
Renderer renderer = GetComponent<Renderer>();
if ( AmplifyMotionEffectBase.CanRegister( gameObject, false ) )
{
#if !UNITY_PRE_5_3
ParticleSystem particleRenderer = GetComponent<ParticleSystem>();
if ( particleRenderer != null )
{
m_type = AmplifyMotion.ObjectType.Particle;
AmplifyMotionEffectBase.RegisterObject( this );
}
else
#endif
if ( renderer != null )
{
// At this point, Renderer is guaranteed to be one of the following
if ( renderer.GetType() == typeof( MeshRenderer ) )
m_type = AmplifyMotion.ObjectType.Solid;
#if UNITY_4
else if ( renderer.GetType() == typeof( ClothRenderer ) )
m_type = AmplifyMotion.ObjectType.Cloth;
#endif
else if ( renderer.GetType() == typeof( SkinnedMeshRenderer ) )
{
#if !UNITY_4
if ( GetComponent<Cloth>() != null )
m_type = AmplifyMotion.ObjectType.Cloth;
else
#endif
m_type = AmplifyMotion.ObjectType.Skinned;
}
AmplifyMotionEffectBase.RegisterObject( this );
}
}
// No renderer? disable it, it is here just for adding children
return ( renderer != null );
}
void OnEnable()
{
bool valid = InitializeType();
if ( valid )
{
if ( m_type == AmplifyMotion.ObjectType.Cloth )
{
#if UNITY_4
m_fixedStep = true;
#else
m_fixedStep = false;
#endif
}
else if ( m_type == AmplifyMotion.ObjectType.Solid )
{
Rigidbody rigidbody = GetComponent<Rigidbody>();
if ( rigidbody != null && rigidbody.interpolation == RigidbodyInterpolation.None && !rigidbody.isKinematic )
m_fixedStep = true;
}
}
if ( m_applyToChildren )
{
foreach ( Transform child in gameObject.transform )
AmplifyMotionEffectBase.RegisterRecursivelyS( child.gameObject );
}
if ( !valid )
enabled = false;
}
void OnDisable()
{
AmplifyMotionEffectBase.UnregisterObject( this );
}
void TryInitializeStates()
{
var enumerator = m_states.GetEnumerator();
while ( enumerator.MoveNext() )
{
AmplifyMotion.MotionState state = enumerator.Current.Value;
if ( state.Owner.Initialized && !state.Error && !state.Initialized )
state.Initialize();
}
}
void Start()
{
if ( AmplifyMotionEffectBase.Instance != null )
TryInitializeStates();
m_lastPosition = transform.position;
}
void Update()
{
if ( AmplifyMotionEffectBase.Instance != null )
TryInitializeStates();
}
static void RecursiveResetMotionAtFrame( Transform transform, AmplifyMotionObjectBase obj, int frame )
{
if ( obj != null )
obj.m_resetAtFrame = frame;
foreach ( Transform child in transform )
RecursiveResetMotionAtFrame( child, child.GetComponent<AmplifyMotionObjectBase>(), frame );
}
public void ResetMotionNow()
{
RecursiveResetMotionAtFrame( transform, this, Time.frameCount );
}
public void ResetMotionAtFrame( int frame )
{
RecursiveResetMotionAtFrame( transform, this, frame );
}
private void CheckTeleportReset( AmplifyMotionEffectBase inst )
{
if ( Vector3.SqrMagnitude( transform.position - m_lastPosition ) > inst.MinResetDeltaDistSqr )
RecursiveResetMotionAtFrame( transform, this, Time.frameCount + inst.ResetFrameDelay );
}
#if UNITY_4
internal void OnUpdateTransform( AmplifyMotionEffectBase inst, Camera camera, bool starting )
#else
internal void OnUpdateTransform( AmplifyMotionEffectBase inst, Camera camera, CommandBuffer updateCB, bool starting )
#endif
{
AmplifyMotion.MotionState state;
if ( m_states.TryGetValue( camera, out state ) )
{
if ( !state.Error )
{
CheckTeleportReset( inst );
bool reset = ( m_resetAtFrame > 0 && Time.frameCount >= m_resetAtFrame );
#if UNITY_4
state.UpdateTransform( starting || reset );
#else
state.UpdateTransform( updateCB, starting || reset );
#endif
}
}
m_lastPosition = transform.position;
}
#if UNITY_4
internal void OnRenderVectors( Camera camera, float scale, AmplifyMotion.Quality quality )
#else
internal void OnRenderVectors( Camera camera, CommandBuffer renderCB, float scale, AmplifyMotion.Quality quality )
#endif
{
AmplifyMotion.MotionState state;
if ( m_states.TryGetValue( camera, out state ) )
{
if ( !state.Error )
{
#if UNITY_4
state.RenderVectors( camera, scale, quality );
#else
state.RenderVectors( camera, renderCB, scale, quality );
#endif
if ( m_resetAtFrame > 0 && Time.frameCount >= m_resetAtFrame )
m_resetAtFrame = -1;
}
}
}
#if UNITY_EDITOR
internal void OnRenderDebugHUD( Camera camera )
{
AmplifyMotion.MotionState state;
if ( m_states.TryGetValue( camera, out state ) )
{
if ( !state.Error )
state.RenderDebugHUD();
}
}
#endif
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H02_Continent (editable child object).<br/>
/// This is a generated base class of <see cref="H02_Continent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="H03_SubContinentObjects"/> of type <see cref="H03_SubContinentColl"/> (1:M relation to <see cref="H04_SubContinent"/>)<br/>
/// This class is an item of <see cref="H01_ContinentColl"/> collection.
/// </remarks>
[Serializable]
public partial class H02_Continent : BusinessBase<H02_Continent>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID");
/// <summary>
/// Gets the Continents ID.
/// </summary>
/// <value>The Continents ID.</value>
public int Continent_ID
{
get { return GetProperty(Continent_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Continent_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name");
/// <summary>
/// Gets or sets the Continents Name.
/// </summary>
/// <value>The Continents Name.</value>
public string Continent_Name
{
get { return GetProperty(Continent_NameProperty); }
set { SetProperty(Continent_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H03_Continent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H03_Continent_Child> H03_Continent_SingleObjectProperty = RegisterProperty<H03_Continent_Child>(p => p.H03_Continent_SingleObject, "H03 Continent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H03 Continent Single Object ("self load" child property).
/// </summary>
/// <value>The H03 Continent Single Object.</value>
public H03_Continent_Child H03_Continent_SingleObject
{
get { return GetProperty(H03_Continent_SingleObjectProperty); }
private set { LoadProperty(H03_Continent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H03_Continent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H03_Continent_ReChild> H03_Continent_ASingleObjectProperty = RegisterProperty<H03_Continent_ReChild>(p => p.H03_Continent_ASingleObject, "H03 Continent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H03 Continent ASingle Object ("self load" child property).
/// </summary>
/// <value>The H03 Continent ASingle Object.</value>
public H03_Continent_ReChild H03_Continent_ASingleObject
{
get { return GetProperty(H03_Continent_ASingleObjectProperty); }
private set { LoadProperty(H03_Continent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H03_SubContinentObjects"/> property.
/// </summary>
public static readonly PropertyInfo<H03_SubContinentColl> H03_SubContinentObjectsProperty = RegisterProperty<H03_SubContinentColl>(p => p.H03_SubContinentObjects, "H03 SubContinent Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the H03 Sub Continent Objects ("self load" child property).
/// </summary>
/// <value>The H03 Sub Continent Objects.</value>
public H03_SubContinentColl H03_SubContinentObjects
{
get { return GetProperty(H03_SubContinentObjectsProperty); }
private set { LoadProperty(H03_SubContinentObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H02_Continent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H02_Continent"/> object.</returns>
internal static H02_Continent NewH02_Continent()
{
return DataPortal.CreateChild<H02_Continent>();
}
/// <summary>
/// Factory method. Loads a <see cref="H02_Continent"/> object from the given H02_ContinentDto.
/// </summary>
/// <param name="data">The <see cref="H02_ContinentDto"/>.</param>
/// <returns>A reference to the fetched <see cref="H02_Continent"/> object.</returns>
internal static H02_Continent GetH02_Continent(H02_ContinentDto data)
{
H02_Continent obj = new H02_Continent();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H02_Continent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H02_Continent()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H02_Continent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(H03_Continent_SingleObjectProperty, DataPortal.CreateChild<H03_Continent_Child>());
LoadProperty(H03_Continent_ASingleObjectProperty, DataPortal.CreateChild<H03_Continent_ReChild>());
LoadProperty(H03_SubContinentObjectsProperty, DataPortal.CreateChild<H03_SubContinentColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H02_Continent"/> object from the given <see cref="H02_ContinentDto"/>.
/// </summary>
/// <param name="data">The H02_ContinentDto to use.</param>
private void Fetch(H02_ContinentDto data)
{
// Value properties
LoadProperty(Continent_IDProperty, data.Continent_ID);
LoadProperty(Continent_NameProperty, data.Continent_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(H03_Continent_SingleObjectProperty, H03_Continent_Child.GetH03_Continent_Child(Continent_ID));
LoadProperty(H03_Continent_ASingleObjectProperty, H03_Continent_ReChild.GetH03_Continent_ReChild(Continent_ID));
LoadProperty(H03_SubContinentObjectsProperty, H03_SubContinentColl.GetH03_SubContinentColl(Continent_ID));
}
/// <summary>
/// Inserts a new <see cref="H02_Continent"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert()
{
var dto = new H02_ContinentDto();
dto.Continent_Name = Continent_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IH02_ContinentDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(Continent_IDProperty, resultDto.Continent_ID);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new H02_ContinentDto();
dto.Continent_ID = Continent_ID;
dto.Continent_Name = Continent_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IH02_ContinentDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="H02_Continent"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IH02_ContinentDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(Continent_IDProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <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);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//
// Klak - Utilities for creative coding with Unity
//
// Copyright (C) 2016 Keijiro Takahashi
//
// 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 UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
using System.Reflection;
using Graphs = UnityEditor.Graphs;
namespace Klak.Wiring.Patcher
{
// Specialized edge drawer class
public class EdgeGUI : Graphs.IEdgeGUI
{
#region Public members
public Graphs.GraphGUI host { get; set; }
public List<int> edgeSelection { get; set; }
public EdgeGUI()
{
edgeSelection = new List<int>();
}
#endregion
#region IEdgeGUI implementation
public void DoEdges()
{
// Draw edges on repaint.
if (Event.current.type == EventType.Repaint)
{
var colorOff = Color.white;
var colorOn = new Color(0.6f, 0.75f, 1);
var i = 0;
foreach (var edge in host.graph.edges)
{
if (edge == _moveEdge) continue;
DrawEdge(edge, edgeSelection.Contains(i) ? colorOn : colorOff);
i++;
}
}
// Terminate dragging operation on mouse button up.
if (Event.current.type == EventType.MouseUp && _dragSourceSlot != null)
{
if (_moveEdge != null)
{
host.graph.RemoveEdge(_moveEdge);
_moveEdge = null;
}
if (_dropTarget == null)
{
EndDragging();
Event.current.Use();
}
}
}
public void DoDraggedEdge()
{
if (_dragSourceSlot == null) return;
var eventType = Event.current.GetTypeForControl(0);
if (eventType == EventType.Repaint)
{
// Draw the working edge.
var p1 = GetPositionAsFromSlot(_dragSourceSlot);
var p2 = _dropTarget != null ?
GetPositionAsToSlot(_dropTarget) :
Event.current.mousePosition;
DrawEdge(p1, p2, Color.white);
}
if (eventType == EventType.MouseDrag)
{
// Discard the last candidate.
_dropTarget = null;
Event.current.Use();
}
}
public void BeginSlotDragging(Graphs.Slot slot, bool allowStartDrag, bool allowEndDrag)
{
if (allowStartDrag)
{
// Start dragging with a new connection.
_dragSourceSlot = slot;
Event.current.Use();
}
if (allowEndDrag && slot.edges.Count > 0)
{
// Start dragging to modify an existing connection.
_moveEdge = slot.edges[slot.edges.Count - 1];
_dragSourceSlot = _moveEdge.fromSlot;
_dropTarget = slot;
Event.current.Use();
}
}
public void SlotDragging(Graphs.Slot slot, bool allowEndDrag, bool allowMultiple)
{
Debug.Assert(allowMultiple);
if (!allowEndDrag) return;
if (_dragSourceSlot == null || _dragSourceSlot == slot) return;
// Is this slot can be a drop target?
if (_dropTarget != slot &&
slot.node.graph.CanConnect(_dragSourceSlot, slot) &&
!slot.node.graph.Connected(_dragSourceSlot, slot))
{
_dropTarget = slot;
}
Event.current.Use();
}
public void EndSlotDragging(Graphs.Slot slot, bool allowMultiple)
{
Debug.Assert(allowMultiple);
// Do nothing if no target was specified.
if (_dropTarget != slot) return;
// If we're going to modify an existing edge, remove it.
if (_moveEdge != null) slot.node.graph.RemoveEdge(_moveEdge);
// Try to connect the edge to the target.
try
{
slot.node.graph.Connect(_dragSourceSlot, slot);
}
finally
{
EndDragging();
slot.node.graph.Dirty();
Event.current.Use();
}
UnityEngine.GUIUtility.ExitGUI();
}
public void EndDragging()
{
_dragSourceSlot = _dropTarget = null;
_moveEdge = null;
}
public Graphs.Edge FindClosestEdge()
{
// Target position
var point = Event.current.mousePosition;
// Candidate
var minDist = Mathf.Infinity;
var found = null as Graphs.Edge;
// Scan all the edges in the graph.
foreach (var edge in host.graph.edges)
{
var p1 = GetPositionAsFromSlot(edge.fromSlot);
var p2 = GetPositionAsToSlot(edge.toSlot);
var dist = HandleUtility.DistancePointLine(point, p1, p2);
// Record the current edge if the point is the closest one.
if (dist < minDist)
{
minDist = dist;
found = edge;
}
}
// Discard the result if it's too far.
return minDist < 12.0f ? found : null;
}
#endregion
#region Private members
Graphs.Edge _moveEdge;
Graphs.Slot _dragSourceSlot;
Graphs.Slot _dropTarget;
#endregion
#region Edge drawer
const float kEdgeWidth = 8;
const float kEdgeSlotYOffset = 9;
static void DrawEdge(Graphs.Edge edge, Color color)
{
var p1 = GetPositionAsFromSlot(edge.fromSlot);
var p2 = GetPositionAsToSlot(edge.toSlot);
DrawEdge(p1, p2, color * edge.color);
}
static void DrawEdge(Vector2 p1, Vector2 p2, Color color)
{
var l = Mathf.Min(Mathf.Abs(p1.y - p2.y), 50);
var p3 = p1 + new Vector2(l, 0);
var p4 = p2 - new Vector2(l, 0);
var texture = (Texture2D)Graphs.Styles.connectionTexture.image;
Handles.DrawBezier(p1, p2, p3, p4, color, texture, kEdgeWidth);
}
#endregion
#region Utilities to access private members
// Accessors for Slot.m_Position
static Rect GetSlotPosition(Graphs.Slot slot)
{
var flags = BindingFlags.NonPublic | BindingFlags.Instance;
var func = typeof(Graphs.Slot).GetField("m_Position", flags);
return (Rect)func.GetValue(slot);
}
static Vector2 GetPositionAsFromSlot(Graphs.Slot slot)
{
var rect = GetSlotPosition(slot);
return GUIClip(new Vector2(rect.xMax, rect.y + kEdgeSlotYOffset));
}
static Vector2 GetPositionAsToSlot(Graphs.Slot slot)
{
var rect = GetSlotPosition(slot);
return GUIClip(new Vector2(rect.x, rect.y + kEdgeSlotYOffset));
}
// Caller for GUIClip.Clip
static Vector2 GUIClip(Vector2 pos)
{
var type = Type.GetType("UnityEngine.GUIClip,UnityEngine");
var method = type.GetMethod("Clip", new Type[]{ typeof(Vector2) });
return (Vector2)method.Invoke(null, new object[]{ pos });
}
#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.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Buffers;
namespace System.IO
{
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
public abstract partial class TextReader : MarshalByRefObject, IDisposable
{
public static readonly TextReader Null = new NullTextReader();
protected TextReader() { }
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
public virtual int Peek()
{
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int n;
for (n = 0; n < count; n++)
{
int ch = Read();
if (ch == -1) break;
buffer[index + n] = (char)ch;
}
return n;
}
// Reads a span of characters. This method will read up to
// count characters from this TextReader into the
// span of characters Returns the actual number of characters read.
//
public virtual int Read(Span<char> buffer)
{
char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
try
{
int numRead = Read(array, 0, buffer.Length);
if ((uint)numRead > (uint)buffer.Length)
{
throw new IOException(SR.IO_InvalidReadLength);
}
new Span<char>(array, 0, numRead).CopyTo(buffer);
return numRead;
}
finally
{
ArrayPool<char>.Shared.Return(array);
}
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual string ReadToEnd()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(char[] buffer, int index, int count)
{
int i, n = 0;
do
{
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Blocking version of read for span of characters. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(Span<char> buffer)
{
char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
try
{
int numRead = ReadBlock(array, 0, buffer.Length);
if ((uint)numRead > (uint)buffer.Length)
{
throw new IOException(SR.IO_InvalidReadLength);
}
new Span<char>(array, 0, numRead).CopyTo(buffer);
return numRead;
}
finally
{
ArrayPool<char>.Shared.Return(array);
}
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual string? ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true)
{
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n')
{
Read();
}
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0)
{
return sb.ToString();
}
return null;
}
#region Task based Async APIs
public virtual Task<string?> ReadLineAsync() =>
Task<string?>.Factory.StartNew(state => ((TextReader)state!).ReadLine(), this,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
public virtual async Task<string> ReadToEndAsync()
{
var sb = new StringBuilder(4096);
char[] chars = ArrayPool<char>.Shared.Rent(4096);
try
{
int len;
while ((len = await ReadAsyncInternal(chars, default).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
}
finally
{
ArrayPool<char>.Shared.Return(chars);
}
return sb.ToString();
}
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask();
}
public virtual ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) =>
new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
ReadAsync(array.Array!, array.Offset, array.Count) :
Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state!;
return t.Item1.Read(t.Item2.Span);
}, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
internal virtual ValueTask<int> ReadAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken)
{
var tuple = new Tuple<TextReader, Memory<char>>(this, buffer);
return new ValueTask<int>(Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state!;
return t.Item1.Read(t.Item2.Span);
},
tuple, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
}
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadBlockAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask();
}
public virtual ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) =>
new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
ReadBlockAsync(array.Array!, array.Offset, array.Count) :
Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, Memory<char>>)state!;
return t.Item1.ReadBlock(t.Item2.Span);
}, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
internal async ValueTask<int> ReadBlockAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken)
{
int n = 0, i;
do
{
i = await ReadAsyncInternal(buffer.Slice(n), cancellationToken).ConfigureAwait(false);
n += i;
} while (i > 0 && n < buffer.Length);
return n;
}
#endregion
private sealed class NullTextReader : TextReader
{
public NullTextReader() { }
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override string? ReadLine()
{
return null;
}
}
public static TextReader Synchronized(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
return reader is SyncTextReader ? reader : new SyncTextReader(reader);
}
internal sealed class SyncTextReader : TextReader
{
internal readonly TextReader _in;
internal SyncTextReader(TextReader t)
{
_in = t;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override void Close() => _in.Close();
[MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing)
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_in).Dispose();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Peek() => _in.Peek();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read() => _in.Read();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read(char[] buffer, int index, int count) => _in.Read(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override string? ReadLine() => _in.ReadLine();
[MethodImpl(MethodImplOptions.Synchronized)]
public override string ReadToEnd() => _in.ReadToEnd();
//
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string?> ReadLineAsync() => Task.FromResult(ReadLine());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(ReadBlock(buffer, index, count));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(Read(buffer, index, count));
}
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define USE_TRACING
#define DEBUG
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Configuration;
using System.Net;
using NUnit.Framework;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.GoogleBase;
using Google.GData.Client.UnitTests;
namespace Google.GData.Client.LiveTests
{
[TestFixture]
[Category("LiveTest")]
public class GBatchTestSuite : BaseLiveTestClass
{
private string gBaseURI; // holds the base uri
private string gBaseKey; // holds the key
//////////////////////////////////////////////////////////////////////
/// <summary>default empty constructor</summary>
//////////////////////////////////////////////////////////////////////
public GBatchTestSuite()
{
}
//////////////////////////////////////////////////////////////////////
/// <summary>the setup method</summary>
//////////////////////////////////////////////////////////////////////
[SetUp] public override void InitTest()
{
base.InitTest();
GDataGAuthRequestFactory authFactory = this.factory as GDataGAuthRequestFactory;
if (authFactory != null)
{
authFactory.Handler = this.strAuthHandler;
}
}
/////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
/// <summary>the end it all method</summary>
//////////////////////////////////////////////////////////////////////
[TearDown] public override void EndTest()
{
Tracing.ExitTracing();
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>private void ReadConfigFile()</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
protected override void ReadConfigFile()
{
base.ReadConfigFile();
if (unitTestConfiguration.Contains("gBaseURI") == true)
{
this.gBaseURI = (string) unitTestConfiguration["gBaseURI"];
Tracing.TraceInfo("Read gBase URI value: " + this.gBaseURI);
}
if (unitTestConfiguration.Contains("gBaseKey") == true)
{
this.gBaseKey = (string) unitTestConfiguration["gBaseKey"];
Tracing.TraceInfo("Read gBaseKey value: " + this.gBaseKey);
}
}
/////////////////////////////////////////////////////////////////////////////
public override string ServiceName
{
get
{
return "gbase";
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void GoogleBaseAuthenticationTest()
{
Tracing.TraceMsg("Entering Base AuthenticationTest");
FeedQuery query = new FeedQuery();
Service service = new GBaseService(this.ApplicationName, this.gBaseKey);
int iCount;
if (this.gBaseURI != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.gBaseURI);
AtomFeed baseFeed = service.Query(query);
// this should have a batch URI
Assert.IsTrue(baseFeed.Batch != null, "This is a base Feed, it should have batch URI");
ObjectModelHelper.DumpAtomObject(baseFeed,CreateDumpFileName("AuthenticationTest"));
iCount = baseFeed.Entries.Count;
String strTitle = "Dinner time" + Guid.NewGuid().ToString();
if (baseFeed != null && baseFeed.Entries.Count > 0)
{
// get the first entry
AtomEntry entry = baseFeed.Entries[0];
entry = ObjectModelHelper.CreateGoogleBaseEntry(1);
entry.Title.Text = strTitle;
GBaseEntry newEntry = baseFeed.Insert(entry) as GBaseEntry;
newEntry.PublishingPriority = new PublishingPriority("high");
GBaseEntry updatedEntry = newEntry.Update() as GBaseEntry;
// publishing priority does not seem to be echoed back
// Assert.IsTrue(updatedEntry.PublishingPriority.Value == "high");
iCount++;
Tracing.TraceMsg("Created google base entry");
// try to get just that guy.....
FeedQuery singleQuery = new FeedQuery();
singleQuery.Uri = new Uri(newEntry.SelfUri.ToString());
AtomFeed newFeed = service.Query(singleQuery);
AtomEntry sameGuy = newFeed.Entries[0];
Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical");
}
baseFeed = service.Query(query);
if (baseFeed != null && baseFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (AtomEntry entry in baseFeed.Entries)
{
Tracing.TraceMsg("Entrie title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
entry.Content.Content = "Maybe stay until breakfast";
entry.Content.Type = "text";
entry.Update();
Tracing.TraceMsg("Updated entry");
}
}
}
baseFeed = service.Query(query);
if (baseFeed != null && baseFeed.Entries.Count > 0)
{
// look for the one with dinner time...
foreach (AtomEntry entry in baseFeed.Entries)
{
Tracing.TraceMsg("Entrie title: " + entry.Title.Text);
if (String.Compare(entry.Title.Text, strTitle)==0)
{
entry.Delete();
iCount--;
Tracing.TraceMsg("deleted entry");
}
}
}
baseFeed = service.Query(query);
service.Credentials = null;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs a batch upload test</summary>
//////////////////////////////////////////////////////////////////////
[Test]
public void GoogleBaseBatchInsert()
{
Tracing.TraceMsg("Entering GoogleBaseBatchUpload");
FeedQuery query = new FeedQuery();
Service service = new GBaseService(this.ApplicationName, this.gBaseKey);
if (this.gBaseURI != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.gBaseURI);
AtomFeed baseFeed = service.Query(query);
// this should have a batch URI
Assert.IsTrue(baseFeed.Batch != null, "This is a base Feed, it should have batch URI");
AtomFeed batchFeed = new AtomFeed(new Uri(this.gBaseURI), service);
// set the default operation. Unneeded, as the default is insert,
// but want to make sure the code is complete
batchFeed.BatchData = new GDataBatchFeedData();
batchFeed.BatchData.Type = GDataBatchOperationType.delete;
for (int i=0; i<20; i++)
{
AtomEntry entry = ObjectModelHelper.CreateGoogleBaseEntry(i);
entry.BatchData = new GDataBatchEntryData();
entry.BatchData.Type = GDataBatchOperationType.insert;
entry.BatchData.Id = i.ToString();
batchFeed.Entries.Add(entry);
}
AtomFeed resultFeed = service.Batch(batchFeed, new Uri(baseFeed.Batch));
foreach (AtomEntry resultEntry in resultFeed.Entries )
{
GDataBatchEntryData data = resultEntry.BatchData;
Assert.IsTrue(data.Status.Code == 201, "Status code should be 201, is:" + data.Status.Code);
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs a batch upload test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void GoogleBaseBatchDelete()
{
Tracing.TraceMsg("Entering GoogleBaseBatchDelete");
FeedQuery query = new FeedQuery();
Service service = new GBaseService(this.ApplicationName, this.gBaseKey);
if (this.gBaseURI != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.gBaseURI);
AtomFeed baseFeed = service.Query(query);
Tracing.TraceMsg("Queried");
// this should have a batch URI
Assert.IsTrue(baseFeed.Batch != null, "This is a base Feed, it should have batch URI");
AtomFeed batchFeed = new AtomFeed(new Uri(this.gBaseURI), service);
// set the default operation.
batchFeed.BatchData = new GDataBatchFeedData();
batchFeed.BatchData.Type = GDataBatchOperationType.delete;
Tracing.TraceMsg("Pouet ?");
int i = 1;
foreach (AtomEntry entry in baseFeed.Entries)
{
AtomEntry batchEntry = new AtomEntry();
batchEntry.Id = entry.Id;
batchEntry.BatchData = new GDataBatchEntryData();
batchEntry.BatchData.Id = i.ToString();
batchEntry.BatchData.Type = GDataBatchOperationType.delete;
batchFeed.Entries.Add(batchEntry);
i++;
}
AtomFeed resultFeed = service.Batch(batchFeed, new Uri(baseFeed.Batch));
foreach (AtomEntry resultEntry in resultFeed.Entries )
{
GDataBatchEntryData data = resultEntry.BatchData;
Assert.IsTrue(data.Status.Code == 200, "Status code should be 200, is:" + data.Status.Code);
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs a batch upload test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void GoogleBaseBatchUpdates()
{
Tracing.TraceMsg("Entering GoogleBaseBatchUpdates");
FeedQuery query = new FeedQuery();
Service service = new GBaseService(this.ApplicationName, this.gBaseKey);
if (this.gBaseURI != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.gBaseURI);
AtomFeed baseFeed = service.Query(query);
// this should have a batch URI
Assert.IsTrue(baseFeed.Batch != null, "This is a base Feed, it should have batch URI");
AtomFeed batchFeed = new AtomFeed(baseFeed);
// set the default operation.
batchFeed.BatchData = new GDataBatchFeedData();
batchFeed.BatchData.Type = GDataBatchOperationType.delete;
int i = 1;
foreach (AtomEntry entry in baseFeed.Entries)
{
AtomEntry batchEntry = batchFeed.Entries.CopyOrMove(entry);
batchEntry.BatchData = new GDataBatchEntryData();
batchEntry.BatchData.Id = i.ToString();
batchEntry.BatchData.Type = GDataBatchOperationType.update;
batchEntry.Title.Text = "Updated";
}
AtomFeed resultFeed = service.Batch(batchFeed, new Uri(baseFeed.Batch));
foreach (AtomEntry resultEntry in resultFeed.Entries )
{
GDataBatchEntryData data = resultEntry.BatchData;
Assert.IsTrue(data.Status.Code == 200, "Status code should be 200, is:" + data.Status.Code);
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs a batch upload test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void GoogleBaseBatchUpdateSameFeed()
{
Tracing.TraceMsg("Entering GoogleBaseBatchUpdateSameFeed");
FeedQuery query = new FeedQuery();
Service service = new GBaseService(this.ApplicationName, this.gBaseKey);
if (this.gBaseURI != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.gBaseURI);
AtomFeed baseFeed = service.Query(query);
// this should have a batch URI
Assert.IsTrue(baseFeed.Batch != null, "This is a base Feed, it should have batch URI");
int i = 0;
foreach (AtomEntry entry in baseFeed.Entries)
{
entry.BatchData = new GDataBatchEntryData();
entry.BatchData.Id = i.ToString();
entry.BatchData.Type = GDataBatchOperationType.update;
entry.Title.Text = "Updated";
i++;
}
AtomFeed resultFeed = service.Batch(baseFeed, new Uri(baseFeed.Batch));
foreach (AtomEntry resultEntry in resultFeed.Entries )
{
GDataBatchEntryData data = resultEntry.BatchData;
Assert.IsTrue(data.Status.Code == 200, "Status code should be 200, is:" + data.Status.Code);
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>runs a batch upload test</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void GoogleBaseBatchMix()
{
Tracing.TraceMsg("Entering GoogleBaseBatchMix");
FeedQuery query = new FeedQuery();
Service service = new GBaseService(this.ApplicationName, this.gBaseKey);
if (this.gBaseURI != null)
{
if (this.userName != null)
{
service.Credentials = new GDataCredentials(this.userName, this.passWord);
}
service.RequestFactory = this.factory;
query.Uri = new Uri(this.gBaseURI);
AtomFeed baseFeed = service.Query(query);
// this should have a batch URI
Assert.IsTrue(baseFeed.Batch != null, "This is a base Feed, it should have batch URI");
AtomFeed batchFeed = new AtomFeed(baseFeed);
// set the default operation.
batchFeed.BatchData = new GDataBatchFeedData();
batchFeed.BatchData.Type = GDataBatchOperationType.insert;
int id = 1;
bool fUpdate = true;
foreach (AtomEntry entry in baseFeed.Entries)
{
AtomEntry batchEntry = batchFeed.Entries.CopyOrMove(entry);
if (fUpdate==true)
{
batchEntry.BatchData = new GDataBatchEntryData();
batchEntry.BatchData.Id = id.ToString();
batchEntry.BatchData.Type = GDataBatchOperationType.update;
batchEntry.Title.Text = "Updated";
fUpdate = false;
}
else
{
batchEntry.BatchData = new GDataBatchEntryData();
batchEntry.BatchData.Id = id.ToString();
batchEntry.BatchData.Type = GDataBatchOperationType.delete;
fUpdate = true;
}
// insert one
id++;
batchEntry = ObjectModelHelper.CreateGoogleBaseEntry(1);
batchEntry.BatchData = new GDataBatchEntryData();
batchEntry.BatchData.Type = GDataBatchOperationType.insert;
batchEntry.BatchData.Id = id.ToString();
batchFeed.Entries.Add(batchEntry);
id++;
}
AtomFeed resultFeed = service.Batch(batchFeed, new Uri(baseFeed.Batch));
foreach (AtomEntry resultEntry in resultFeed.Entries )
{
GDataBatchEntryData data = resultEntry.BatchData;
int testcode = 200;
if (data.Type == GDataBatchOperationType.insert)
{
testcode = 201;
}
Assert.IsTrue(data.Status.Code == testcode, "Status code should be: " + testcode + ", is:" + data.Status.Code);
}
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Loads a test file with an error return</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void GoogleBaseErrorTest()
{
Tracing.TraceMsg("Entering GoogleBaseErrorTest");
FeedQuery query = new FeedQuery();
Uri uri = new Uri(CreateUri(this.resourcePath + "batcherror.xml"));
query.Uri = uri;
Service service = new GBaseService(this.ApplicationName, this.gBaseKey);
AtomFeed errorFeed = service.Query(query);
foreach (AtomEntry errorEntry in errorFeed.Entries )
{
GDataBatchEntryData data = errorEntry.BatchData;
if (data.Status.Code == 400)
{
Assert.IsTrue(data.Status.Errors.Count == 2);
GDataBatchError error = data.Status.Errors[0];
Assert.IsTrue(error.Type == "data");
Assert.IsTrue(error.Field == "expiration_date");
Assert.IsTrue(error.Reason != null);
Assert.IsTrue(error.Reason.StartsWith("Invalid type specified"));
error = data.Status.Errors[1];
Assert.IsTrue(error.Type == "data");
Assert.IsTrue(error.Field == "price_type");
Assert.IsTrue(error.Reason == "Invalid price type");
}
}
}
/////////////////////////////////////////////////////////////////////////////
} /////////////////////////////////////////////////////////////////////////////
}
| |
// 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.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// DeploymentsOperations operations.
/// </summary>
public partial interface IDeploymentsOperations
{
/// <summary>
/// Deletes a deployment from the deployment history.
/// </summary>
/// <remarks>
/// A template deployment that is currently running cannot be deleted.
/// Deleting a template deployment removes the associated deployment
/// operations. Deleting a template deployment does not affect the
/// state of the resource group. This is an asynchronous operation
/// that returns a status of 202 until the template deployment is
/// successfully deleted. The Location response header contains the
/// URI that is used to obtain the status of the process. While the
/// process is running, a call to the URI in the Location header
/// returns a status of 202. When the process finishes, the URI in
/// the Location header returns a status of 204 on success. If the
/// asynchronous request failed, the URI in the Location header
/// returns an error-level status code.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group with the deployment to delete. The
/// name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Checks whether the deployment exists.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group with the deployment to check. The
/// name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to check.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool>> CheckExistenceWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deploys resources to a resource group.
/// </summary>
/// <remarks>
/// You can provide the template and parameters directly in the
/// request or link to JSON files.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group to deploy the resources to. The
/// name is case insensitive. The resource group must already exist.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentExtended>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets a deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to get.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentExtended>> GetWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Cancels a currently running template deployment.
/// </summary>
/// <remarks>
/// You can cancel a deployment only if the provisioningState is
/// Accepted or Running. After the deployment is canceled, the
/// provisioningState is set to Canceled. Canceling a template
/// deployment stops the currently running template deployment and
/// leaves the resource group partially deployed.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to cancel.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> CancelWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Validates whether the specified template is syntactically correct
/// and will be accepted by Azure Resource Manager..
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group the template will be deployed to.
/// The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Parameters to validate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentValidateResult>> ValidateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Exports the template used for specified deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment from which to get the template.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentExportResult>> ExportTemplateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get all the deployments for a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group with the deployments to get. The
/// name is case insensitive.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentExtended>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<DeploymentExtendedFilter> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<DeploymentExtendedFilter>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a deployment from the deployment history.
/// </summary>
/// <remarks>
/// A template deployment that is currently running cannot be deleted.
/// Deleting a template deployment removes the associated deployment
/// operations. Deleting a template deployment does not affect the
/// state of the resource group. This is an asynchronous operation
/// that returns a status of 202 until the template deployment is
/// successfully deleted. The Location response header contains the
/// URI that is used to obtain the status of the process. While the
/// process is running, a call to the URI in the Location header
/// returns a status of 202. When the process finishes, the URI in
/// the Location header returns a status of 204 on success. If the
/// asynchronous request failed, the URI in the Location header
/// returns an error-level status code.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group with the deployment to delete. The
/// name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deploys resources to a resource group.
/// </summary>
/// <remarks>
/// You can provide the template and parameters directly in the
/// request or link to JSON files.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group to deploy the resources to. The
/// name is case insensitive. The resource group must already exist.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentExtended>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get all the deployments for a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentExtended>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) 2002 Ville Palo
// (C) 2003 Martin Willemoes Hansen
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using Xunit;
using System.Xml;
using System.Data.SqlTypes;
using System.Globalization;
namespace System.Data.Tests.SqlTypes
{
public class SqlSingleTest
{
public SqlSingleTest()
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
}
// Test constructor
[Fact]
public void Create()
{
SqlSingle Test = new SqlSingle((float)34.87);
SqlSingle Test2 = 45.2f;
Assert.Equal(34.87f, Test.Value);
Assert.Equal(45.2f, Test2.Value);
Test = new SqlSingle(-9000.6543);
Assert.Equal(-9000.6543f, Test.Value);
}
// Test public fields
[Fact]
public void PublicFields()
{
Assert.Equal(3.40282346638528859E+38f, SqlSingle.MaxValue.Value);
Assert.Equal(-3.40282346638528859E+38f, SqlSingle.MinValue.Value);
Assert.True(SqlSingle.Null.IsNull);
Assert.Equal(0f, SqlSingle.Zero.Value);
}
// Test properties
[Fact]
public void Properties()
{
SqlSingle Test = new SqlSingle(5443e12f);
SqlSingle Test1 = new SqlSingle(1);
Assert.True(SqlSingle.Null.IsNull);
Assert.Equal(5443e12f, Test.Value);
Assert.Equal(1, Test1.Value);
}
// PUBLIC METHODS
[Fact]
public void ArithmeticMethods()
{
SqlSingle Test0 = new SqlSingle(0);
SqlSingle Test1 = new SqlSingle(15E+18);
SqlSingle Test2 = new SqlSingle(-65E+6);
SqlSingle Test3 = new SqlSingle(5E+30);
SqlSingle Test4 = new SqlSingle(5E+18);
SqlSingle TestMax = new SqlSingle(SqlSingle.MaxValue.Value);
// Add()
Assert.Equal(15E+18f, SqlSingle.Add(Test1, Test0).Value);
Assert.Equal(1.5E+19f, SqlSingle.Add(Test1, Test2).Value);
try
{
SqlSingle test = SqlSingle.Add(SqlSingle.MaxValue,
SqlSingle.MaxValue);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// Divide()
Assert.Equal(3, SqlSingle.Divide(Test1, Test4));
Assert.Equal(-1.3E-23f, SqlSingle.Divide(Test2, Test3).Value);
try
{
SqlSingle test = SqlSingle.Divide(Test1, Test0).Value;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(DivideByZeroException), e.GetType());
}
// Multiply()
Assert.Equal((float)(7.5E+37), SqlSingle.Multiply(Test1, Test4).Value);
Assert.Equal(0, SqlSingle.Multiply(Test1, Test0).Value);
try
{
SqlSingle test = SqlSingle.Multiply(TestMax, Test1);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// Subtract()
Assert.Equal((float)(-5E+30), SqlSingle.Subtract(Test1, Test3).Value);
try
{
SqlSingle test = SqlSingle.Subtract(
SqlSingle.MinValue, SqlSingle.MaxValue);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void CompareTo()
{
SqlSingle Test1 = new SqlSingle(4E+30);
SqlSingle Test11 = new SqlSingle(4E+30);
SqlSingle Test2 = new SqlSingle(-9E+30);
SqlSingle Test3 = new SqlSingle(10000);
SqlString TestString = new SqlString("This is a test");
Assert.True(Test1.CompareTo(Test3) > 0);
Assert.True(Test2.CompareTo(Test3) < 0);
Assert.True(Test1.CompareTo(Test11) == 0);
Assert.True(Test11.CompareTo(SqlSingle.Null) > 0);
try
{
Test1.CompareTo(TestString);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
}
}
[Fact]
public void EqualsMethods()
{
SqlSingle Test0 = new SqlSingle(0);
SqlSingle Test1 = new SqlSingle(1.58e30);
SqlSingle Test2 = new SqlSingle(1.8e32);
SqlSingle Test22 = new SqlSingle(1.8e32);
Assert.True(!Test0.Equals(Test1));
Assert.True(!Test1.Equals(Test2));
Assert.True(!Test2.Equals(new SqlString("TEST")));
Assert.True(Test2.Equals(Test22));
// Static Equals()-method
Assert.True(SqlSingle.Equals(Test2, Test22).Value);
Assert.True(!SqlSingle.Equals(Test1, Test2).Value);
}
[Fact]
public void GetHashCodeTest()
{
SqlSingle Test15 = new SqlSingle(15);
// FIXME: Better way to test HashCode
Assert.Equal(Test15.GetHashCode(), Test15.GetHashCode());
}
[Fact]
public void GetTypeTest()
{
SqlSingle Test = new SqlSingle(84);
Assert.Equal("System.Data.SqlTypes.SqlSingle", Test.GetType().ToString());
Assert.Equal("System.Single", Test.Value.GetType().ToString());
}
[Fact]
public void Greaters()
{
SqlSingle Test1 = new SqlSingle(1e10);
SqlSingle Test11 = new SqlSingle(1e10);
SqlSingle Test2 = new SqlSingle(64e14);
// GreateThan ()
Assert.True(!SqlSingle.GreaterThan(Test1, Test2).Value);
Assert.True(SqlSingle.GreaterThan(Test2, Test1).Value);
Assert.True(!SqlSingle.GreaterThan(Test1, Test11).Value);
// GreaterTharOrEqual ()
Assert.True(!SqlSingle.GreaterThanOrEqual(Test1, Test2).Value);
Assert.True(SqlSingle.GreaterThanOrEqual(Test2, Test1).Value);
Assert.True(SqlSingle.GreaterThanOrEqual(Test1, Test11).Value);
}
[Fact]
public void Lessers()
{
SqlSingle Test1 = new SqlSingle(1.8e10);
SqlSingle Test11 = new SqlSingle(1.8e10);
SqlSingle Test2 = new SqlSingle(64e14);
// LessThan()
Assert.True(!SqlSingle.LessThan(Test1, Test11).Value);
Assert.True(!SqlSingle.LessThan(Test2, Test1).Value);
Assert.True(SqlSingle.LessThan(Test11, Test2).Value);
// LessThanOrEqual ()
Assert.True(SqlSingle.LessThanOrEqual(Test1, Test2).Value);
Assert.True(!SqlSingle.LessThanOrEqual(Test2, Test1).Value);
Assert.True(SqlSingle.LessThanOrEqual(Test11, Test1).Value);
Assert.True(SqlSingle.LessThanOrEqual(Test11, SqlSingle.Null).IsNull);
}
[Fact]
public void NotEquals()
{
SqlSingle Test1 = new SqlSingle(12800000000001);
SqlSingle Test2 = new SqlSingle(128e10);
SqlSingle Test22 = new SqlSingle(128e10);
Assert.True(SqlSingle.NotEquals(Test1, Test2).Value);
Assert.True(SqlSingle.NotEquals(Test2, Test1).Value);
Assert.True(SqlSingle.NotEquals(Test22, Test1).Value);
Assert.True(!SqlSingle.NotEquals(Test22, Test2).Value);
Assert.True(!SqlSingle.NotEquals(Test2, Test22).Value);
Assert.True(SqlSingle.NotEquals(SqlSingle.Null, Test22).IsNull);
Assert.True(SqlSingle.NotEquals(SqlSingle.Null, Test22).IsNull);
}
[Fact]
public void Parse()
{
try
{
SqlSingle.Parse(null);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentNullException), e.GetType());
}
try
{
SqlSingle.Parse("not-a-number");
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
try
{
SqlSingle.Parse("9e44");
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
Assert.Equal(150, SqlSingle.Parse("150").Value);
}
[Fact]
public void Conversions()
{
SqlSingle Test0 = new SqlSingle(0);
SqlSingle Test1 = new SqlSingle(250);
SqlSingle Test2 = new SqlSingle(64E+16);
SqlSingle Test3 = new SqlSingle(64E+30);
SqlSingle TestNull = SqlSingle.Null;
// ToSqlBoolean ()
Assert.True(Test1.ToSqlBoolean().Value);
Assert.True(!Test0.ToSqlBoolean().Value);
Assert.True(TestNull.ToSqlBoolean().IsNull);
// ToSqlByte ()
Assert.Equal((byte)250, Test1.ToSqlByte().Value);
Assert.Equal((byte)0, Test0.ToSqlByte().Value);
try
{
SqlByte b = (byte)Test2.ToSqlByte();
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlDecimal ()
Assert.Equal(250.00000000000000M, Test1.ToSqlDecimal().Value);
Assert.Equal(0, Test0.ToSqlDecimal().Value);
try
{
SqlDecimal test = Test3.ToSqlDecimal().Value;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlInt16 ()
Assert.Equal((short)250, Test1.ToSqlInt16().Value);
Assert.Equal((short)0, Test0.ToSqlInt16().Value);
try
{
SqlInt16 test = Test2.ToSqlInt16().Value;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlInt32 ()
Assert.Equal(250, Test1.ToSqlInt32().Value);
Assert.Equal(0, Test0.ToSqlInt32().Value);
try
{
SqlInt32 test = Test2.ToSqlInt32().Value;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlInt64 ()
Assert.Equal(250, Test1.ToSqlInt64().Value);
Assert.Equal(0, Test0.ToSqlInt64().Value);
try
{
SqlInt64 test = Test3.ToSqlInt64().Value;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlMoney ()
Assert.Equal(250.0000M, Test1.ToSqlMoney().Value);
Assert.Equal(0, Test0.ToSqlMoney().Value);
try
{
SqlMoney test = Test3.ToSqlMoney().Value;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlString ()
Assert.Equal("250", Test1.ToSqlString().Value);
Assert.Equal("0", Test0.ToSqlString().Value);
Assert.Equal("6.4E+17", Test2.ToSqlString().Value);
// ToString ()
Assert.Equal("250", Test1.ToString());
Assert.Equal("0", Test0.ToString());
Assert.Equal("6.4E+17", Test2.ToString());
}
// OPERATORS
[Fact]
public void ArithmeticOperators()
{
SqlSingle Test0 = new SqlSingle(0);
SqlSingle Test1 = new SqlSingle(24E+11);
SqlSingle Test2 = new SqlSingle(64E+32);
SqlSingle Test3 = new SqlSingle(12E+11);
SqlSingle Test4 = new SqlSingle(1E+10);
SqlSingle Test5 = new SqlSingle(2E+10);
// "+"-operator
Assert.Equal((SqlSingle)3E+10, Test4 + Test5);
try
{
SqlSingle test = SqlSingle.MaxValue + SqlSingle.MaxValue;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
try
{
SqlSingle test = SqlSingle.MaxValue + SqlSingle.MaxValue;
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// "/"-operator
Assert.Equal(2, Test1 / Test3);
try
{
SqlSingle test = Test3 / Test0;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(DivideByZeroException), e.GetType());
}
// "*"-operator
Assert.Equal((SqlSingle)2E+20, Test4 * Test5);
try
{
SqlSingle test = SqlSingle.MaxValue * Test1;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// "-"-operator
Assert.Equal((SqlSingle)12e11, Test1 - Test3);
try
{
SqlSingle test = SqlSingle.MinValue - SqlSingle.MaxValue;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void ThanOrEqualOperators()
{
SqlSingle Test1 = new SqlSingle(1.0E+14f);
SqlSingle Test2 = new SqlSingle(9.7E+11);
SqlSingle Test22 = new SqlSingle(9.7E+11);
SqlSingle Test3 = new SqlSingle(2.0E+22f);
// == -operator
Assert.True((Test2 == Test22).Value);
Assert.True(!(Test1 == Test2).Value);
Assert.True((Test1 == SqlSingle.Null).IsNull);
// != -operator
Assert.True(!(Test2 != Test22).Value);
Assert.True((Test2 != Test3).Value);
Assert.True((Test1 != Test3).Value);
Assert.True((Test1 != SqlSingle.Null).IsNull);
// > -operator
Assert.True((Test1 > Test2).Value);
Assert.True(!(Test1 > Test3).Value);
Assert.True(!(Test2 > Test22).Value);
Assert.True((Test1 > SqlSingle.Null).IsNull);
// >= -operator
Assert.True(!(Test1 >= Test3).Value);
Assert.True((Test3 >= Test1).Value);
Assert.True((Test2 >= Test22).Value);
Assert.True((Test1 >= SqlSingle.Null).IsNull);
// < -operator
Assert.True(!(Test1 < Test2).Value);
Assert.True((Test1 < Test3).Value);
Assert.True(!(Test2 < Test22).Value);
Assert.True((Test1 < SqlSingle.Null).IsNull);
// <= -operator
Assert.True((Test1 <= Test3).Value);
Assert.True(!(Test3 <= Test1).Value);
Assert.True((Test2 <= Test22).Value);
Assert.True((Test1 <= SqlSingle.Null).IsNull);
}
[Fact]
public void UnaryNegation()
{
SqlSingle Test = new SqlSingle(2000000001);
SqlSingle TestNeg = new SqlSingle(-3000);
SqlSingle Result = -Test;
Assert.Equal(-2000000001, Result.Value);
Result = -TestNeg;
Assert.Equal(3000, Result.Value);
}
[Fact]
public void SqlBooleanToSqlSingle()
{
SqlBoolean TestBoolean = new SqlBoolean(true);
SqlSingle Result;
Result = (SqlSingle)TestBoolean;
Assert.Equal(1, Result.Value);
Result = (SqlSingle)SqlBoolean.Null;
Assert.True(Result.IsNull);
}
[Fact]
public void SqlDoubleToSqlSingle()
{
SqlDouble Test = new SqlDouble(12e12);
SqlSingle TestSqlSingle = (SqlSingle)Test;
Assert.Equal(12e12f, TestSqlSingle.Value);
}
[Fact]
public void SqlSingleToSingle()
{
SqlSingle Test = new SqlSingle(12e12);
float Result = (float)Test;
Assert.Equal(12e12f, Result);
}
[Fact]
public void SqlStringToSqlSingle()
{
SqlString TestString = new SqlString("Test string");
SqlString TestString100 = new SqlString("100");
Assert.Equal(100, ((SqlSingle)TestString100).Value);
try
{
SqlSingle test = (SqlSingle)TestString;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
}
[Fact]
public void ByteToSqlSingle()
{
short TestShort = 14;
Assert.Equal(14, ((SqlSingle)TestShort).Value);
}
[Fact]
public void SqlDecimalToSqlSingle()
{
SqlDecimal TestDecimal64 = new SqlDecimal(64);
Assert.Equal(64, ((SqlSingle)TestDecimal64).Value);
Assert.Equal(SqlSingle.Null, SqlDecimal.Null);
}
[Fact]
public void SqlIntToSqlSingle()
{
SqlInt16 Test64 = new SqlInt16(64);
SqlInt32 Test640 = new SqlInt32(640);
SqlInt64 Test64000 = new SqlInt64(64000);
Assert.Equal(64, ((SqlSingle)Test64).Value);
Assert.Equal(640, ((SqlSingle)Test640).Value);
Assert.Equal(64000, ((SqlSingle)Test64000).Value);
}
[Fact]
public void SqlMoneyToSqlSingle()
{
SqlMoney TestMoney64 = new SqlMoney(64);
Assert.Equal(64, ((SqlSingle)TestMoney64).Value);
}
[Fact]
public void SingleToSqlSingle()
{
float TestSingle64 = 64;
Assert.Equal(64, ((SqlSingle)TestSingle64).Value);
}
[Fact]
public void GetXsdTypeTest()
{
XmlQualifiedName qualifiedName = SqlSingle.GetXsdType(null);
Assert.Equal("float", qualifiedName.Name);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AzureSearchTool
{
public class SearchModel : INotifyPropertyChanged
{
private string _service = "MaxMelcher";
private string _apiKey = "B98A05BCCACF2A0BA020FE6299CD4AA1";
private string _apiVersion = "2015-02-28-Preview";
private const string BaseUrl = "search.windows.net";
public string Service
{
get { return _service; }
set { _service = value; }
}
public string ApiKey
{
get { return _apiKey; }
set
{
_apiKey = value; OnPropertyChanged("ApiKey");
OnPropertyChanged("Url");
}
}
public bool IsAdminApiKey
{
get { return _isAdminApiKey; }
set { _isAdminApiKey = value;
OnPropertyChanged("IsAdminApiKey");
}
}
private string _filter = "";
public string Filter
{
get
{
return _filter;
}
set
{
_filter = value;
OnPropertyChanged("Filter");
OnPropertyChanged("Url");
}
}
public enum SearchTypes
{
Search,
Suggest
}
public SearchTypes SearchType
{
get { return _searchType; }
set { _searchType = value; OnPropertyChanged("Url"); }
}
public String SuggesterName
{
get { return _suggesterName; }
set { _suggesterName = value; OnPropertyChanged("Url"); }
}
public string MinimumCoverage
{
get { return _minimumCoverage; }
set { _minimumCoverage = value; OnPropertyChanged("Url"); }
}
public string Url
{
//https://maxmelcher.search.windows.net/indexes/twittersearch/docs?search=fifa&api-version=2015-02-28&$filter=Score gt 0.5&$top=25&$count=true
get
{
if (Index == null)
{
return "Index not valid";
}
string type = "";
if (SearchType == SearchTypes.Suggest)
{
type = "/suggest";
}
var url = string.Format("https://{0}.{1}/indexes/{2}/docs{4}?api-version={3}", Service, BaseUrl, Index.Name, ApiVersion, type);
if (!string.IsNullOrEmpty(SearchQuery))
{
var searchQuery = Uri.EscapeDataString(SearchQuery);
url += string.Format("&search={0}", searchQuery);
}
if (!string.IsNullOrEmpty(Top))
{
url += string.Format("&$top={0}", Top);
}
if (!string.IsNullOrEmpty(Skip))
{
url += string.Format("&$skip={0}", Skip);
}
if (!string.IsNullOrEmpty(Filter))
{
var filter = Uri.EscapeDataString(Filter);
url += string.Format("&$filter={0}", filter);
}
if (!string.IsNullOrEmpty(SearchMode))
{
url += string.Format("&searchMode={0}", SearchMode);
}
if (!string.IsNullOrEmpty(SearchFields))
{
url += string.Format("&searchFields={0}", SearchFields);
}
if (!string.IsNullOrEmpty(Count))
{
url += string.Format("&$count={0}", Count);
}
if (!string.IsNullOrEmpty(Orderby))
{
url += string.Format("&$orderby={0}", Orderby);
}
if (!string.IsNullOrEmpty(Select))
{
url += string.Format("&$select={0}", Select);
}
if (!string.IsNullOrEmpty(Facet))
{
var facet = Uri.EscapeDataString(Facet);
url += string.Format("&facet={0}", facet);
}
if (!string.IsNullOrEmpty(Highlight))
{
url += string.Format("&highlight={0}", Highlight);
}
if (!string.IsNullOrEmpty(HighlightPreTag))
{
var highlightPreTag = Uri.EscapeDataString(HighlightPreTag);
url += string.Format("&highlightPreTag={0}", highlightPreTag);
}
if (!string.IsNullOrEmpty(HighlightPostTag))
{
var highlightPostTag = Uri.EscapeDataString(HighlightPostTag);
url += string.Format("&highlightPostTag={0}", highlightPostTag);
}
if (!string.IsNullOrEmpty(ScoringProfile))
{
url += string.Format("&scoringProfile={0}", ScoringProfile);
}
if (!string.IsNullOrEmpty(ScoringParameter))
{
url += string.Format("&scoringParameter={0}", ScoringParameter);
}
if (!string.IsNullOrEmpty(MinimumCoverage))
{
url += string.Format("&minimumCoverage={0}", MinimumCoverage);
}
if (!string.IsNullOrEmpty(SuggesterName))
{
url += string.Format("&suggesterName={0}", SuggesterName);
}
if (Fuzzy)
{
url += string.Format("&fuzzy={0}", Fuzzy);
}
return url;
}
}
public string SearchQuery
{
get { return _searchQuery; }
set
{
_searchQuery = value;
OnPropertyChanged("Url");
}
}
public Index Index
{
get { return _index; }
set
{
_index = value;
OnPropertyChanged("Index");
OnPropertyChanged("Url");
}
}
public string ApiVersion
{
get { return _apiVersion; }
set
{
_apiVersion = value;
OnPropertyChanged("ApiVersion");
OnPropertyChanged("Url");
}
}
private string _top = "";
public string Top
{
get
{
return _top;
}
set
{
_top = value;
OnPropertyChanged("Top");
OnPropertyChanged("Url");
}
}
public bool Fuzzy
{
get { return _fuzzy; }
set
{
_fuzzy = value;
OnPropertyChanged("Fuzzy");
OnPropertyChanged("Url");
}
}
private string _skip = "";
public string Skip
{
get
{
return _skip;
}
set
{
_skip = value;
OnPropertyChanged("Skip");
OnPropertyChanged("Url");
}
}
public List<string> AvailableApiVersions
{
get
{
return new List<string>()
{
"2014-07-31-Preview", "2014-10-20-Preview", "2015-02-28-Preview", "2015-02-28"
};
}
}
private readonly ObservableCollection<Index> _indexes = new ObservableCollection<Index>();
private string _error;
private Index _index;
private string _searchQuery;
private string _searchResultRaw;
private string _status;
public ObservableCollection<Index> Indexes
{
get { return _indexes; }
}
private readonly DataTable _searchResults = new DataTable();
private readonly DataTable _suggestionResults = new DataTable();
private string _searchMode;
private string _searchFields;
private string _count;
private string _orderby;
private string _select;
private string _facet;
private string _highlight;
private string _highlightPreTag;
private string _highlightPostTag;
private string _scoringProfile;
private string _scoringParameter;
private SearchTypes _searchType = SearchTypes.Search;
private string _suggesterName;
private string _minimumCoverage;
private bool _fuzzy;
private bool _connected;
private bool _isAdminApiKey;
private bool _isQueryApiKey;
private string _indexName;
public DataTable SearchResults
{
get { return _searchResults; }
}
public DataTable SuggestionResults
{
get { return _suggestionResults; }
}
public async void Connect()
{
//do nothing if a query key is selected
if (IsQueryApiKey)
{
Connected = true;
Error = "";
return;
}
//todo handle timeout here
//https://maxmelcher.search.windows.net/indexes?api-version=2015-02-28-Preview
string indexUrl = string.Format("https://{0}.{1}/indexes?api-version={2}", Service, BaseUrl, ApiVersion);
WebClient client = GetWebClient();
try
{
var jsonIndexes = await client.DownloadStringTaskAsync(new Uri(indexUrl));
//{'@odata.context': 'https://maxmelcher.search.windows.net/$metadata#indexes','value':''}
var dummy = new
{
value = new Index[] { }
};
var result = JsonConvert.DeserializeAnonymousType(jsonIndexes, dummy);
Indexes.Clear();
foreach (Index index in result.value)
{
index.IsResolved = true;
Indexes.Add(index);
}
Error = "";
Connected = true;
}
catch (Exception ex)
{
Error = ex.Message;
Indexes.Clear();
Index = null;
Connected = false;
}
}
public bool Connected
{
get { return _connected; }
set { _connected = value; OnPropertyChanged("Connected"); }
}
public string Error
{
get { return _error; }
set
{
_error = value;
OnPropertyChanged("Error");
}
}
private WebClient GetWebClient()
{
var client = new WebClient();
client.Headers.Add("Content-Type", "application/json; charset=utf-8");
client.Headers.Add("api-key", ApiKey);
return client;
}
public void SelectIndex(Index index)
{
Index = index;
GetIndexStatistics();
}
private void GetIndexStatistics()
{
try
{
//https://MaxMelcher.search.windows.net/indexes/twittersearch/stats?api-version=2014-07-31-Preview
string statisticUrl = string.Format("https://{0}.{1}/indexes/{2}/stats?api-version={3}", Service, BaseUrl, Index.Name, ApiVersion);
var client = GetWebClient();
var jsonStats = client.DownloadString(statisticUrl);
/*
{
"@odata.context": "https://maxmelcher.search.windows.net/$metadata#Microsoft.Azure.Search.V2014_07_31_Preview.IndexStatistics",
"documentCount": 683,
"storageSize": 294722
}
*/
var stats = JsonConvert.DeserializeObject<dynamic>(jsonStats);
if (stats.documentCount.Type == JTokenType.Integer)
{
Index.Statistics.DocumentCount = stats.documentCount.Value;
}
if (stats.storageSize.Type == JTokenType.Integer)
{
Index.Statistics.StorageSize = stats.storageSize.Value;
}
}
catch (Exception ex)
{
Error = string.Format("Could not download index statistics, this is an indication that the service name, index name or the admin/query key is invalid. Exception: {0}", ex);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string SearchResultRaw
{
get { return _searchResultRaw; }
set
{
_searchResultRaw = value;
OnPropertyChanged("SearchResultRaw");
}
}
public string Status
{
get { return _status; }
set
{
_status = value;
OnPropertyChanged("Status");
}
}
public string SearchMode
{
get { return _searchMode; }
set
{
_searchMode = value;
OnPropertyChanged("Skip");
OnPropertyChanged("Url");
}
}
public List<string> AvailableSearchModes
{
get
{
return
new List<string>
{
"any", "all"
};
}
}
public string SearchFields
{
get { return _searchFields; }
set
{
var tmp = value;
//no spaces allowed here
tmp = tmp.Replace(" ", "");
_searchFields = tmp;
OnPropertyChanged("Skip");
OnPropertyChanged("SearchFields");
OnPropertyChanged("Url");
}
}
public List<string> AvailableCountModes
{
get { return new List<string> { "true", "false" }; }
}
public string Count
{
get { return _count; }
set
{
_count = value;
OnPropertyChanged("Count");
OnPropertyChanged("Url");
}
}
public string Orderby
{
get { return _orderby; }
set
{
_orderby = value;
OnPropertyChanged("Orderby");
OnPropertyChanged("Url");
}
}
public string Select
{
get
{
return _select;
}
set
{
_select = value;
OnPropertyChanged("Select");
OnPropertyChanged("Url");
}
}
public string Facet
{
get { return _facet; }
set
{
_facet = value;
OnPropertyChanged("Facet");
OnPropertyChanged("Url");
}
}
public string Highlight
{
get { return _highlight; }
set
{
_highlight = value;
OnPropertyChanged("Highlight");
OnPropertyChanged("Url");
}
}
public string HighlightPreTag
{
get { return _highlightPreTag; }
set
{
_highlightPreTag = value;
OnPropertyChanged("HighlightPreTag");
OnPropertyChanged("Url");
}
}
public string HighlightPostTag
{
get { return _highlightPostTag; }
set
{
_highlightPostTag = value;
OnPropertyChanged("HighlightPostTag");
OnPropertyChanged("Url");
}
}
public string ScoringProfile
{
get { return _scoringProfile; }
set
{
_scoringProfile = value;
OnPropertyChanged("ScoringProfile");
OnPropertyChanged("Url");
}
}
public string ScoringParameter
{
get { return _scoringParameter; }
set
{
_scoringParameter = value;
OnPropertyChanged("ScoringParameter");
OnPropertyChanged("Url");
}
}
public bool IsQueryApiKey
{
get { return _isQueryApiKey; }
set { _isQueryApiKey = value; OnPropertyChanged("IsQueryApiKey"); }
}
public string IndexName
{
get { return _indexName; }
set { _indexName = value; OnPropertyChanged("IndexName"); }
}
public void Search()
{
try
{
//clear the datatables and reset the columns
SearchResults.Clear();
SearchResults.Columns.Clear();
SuggestionResults.Clear();
SuggestionResults.Columns.Clear();
var client = GetWebClient();
var watch = new Stopwatch();
watch.Start();
SearchResultRaw = client.DownloadString(new Uri(Url));
watch.Stop();
/*
{
"@odata.context": "https://maxmelcher.search.windows.net/indexes('twittersearch')/$metadata#docs(Text,Mention,Created,Url,StatusId,Sentiment,Score)",
"@odata.count": 31,
"value": [
{
"@search.score": 0.094358146,
"Text": "RT @ynfa_thehub: #FIFA http://t.co/oi7ugyAhfz",
"Mention": "@ynfa_thehub",
"Created": null,
"Url": "https://twitter.com/Locket25/status/604595408925507585",
"StatusId": "604595408925507585",
"Sentiment": "good",
"Score": 0.7330736
}, ...
}
* */
dynamic results = JObject.Parse(SearchResultRaw);
//pretty print it
SearchResultRaw = JsonConvert.SerializeObject(results, Formatting.Indented);
if (results.value.Count > 0)
{
if (SearchType == SearchTypes.Search)
{
//create the columns
foreach (var col in results.value.First)
{
string name = col.Name;
name = name.Replace(".", "\x00B7");
SearchResults.Columns.Add(name);
}
//Todo: Mabye do more advanced column handling here, I am thinking of geolocation
//create the values for the table
foreach (var elem in results.value)
{
var row = SearchResults.Rows.Add();
foreach (var col in elem)
{
string name = col.Name;
name = name.Replace(".", "\x00B7");
if (col.Name == "@search.score")
{
row[name] = col.Value.Value;
}
else if (col.Name == "@search.highlights")
{
row[name] = col.Value.Text;
}
else if (col.Value is JArray)
{
var colValues = ((JArray)col.Value).Values();
row[name] = String.Format("[{0}]", String.Join("; ", colValues));
}
else if (col.Value is JObject && col.Value.type != null && col.Value.type == "Point") // TODO explicit null check required?
{
// Geography point
row[name] = String.Format("({0}; {1})", col.Value.coordinates[0], col.Value.coordinates[1]);
}
else
{
row[name] = col.Value.Value;
}
}
}
}
else if (SearchType == SearchTypes.Suggest)
{
//{"@odata.context":"https://maxmelcher.search.windows.net/indexes('twittersearch')/$metadata#docs(StatusId)",
//"value":[{"@search.text":"@NASA @SpaceX @NASA_Kennedy SpaceX rocket explodes after lift-off above Florida!! http://t.co/HPJYcZpSPQ #SpaceX #NASA","StatusId":"615251440731226112"},
//{"@search.text":"Friends if you find any fragments from the SpaceX rocket accident do not touch and call 321-867-2121 @NASAKennedy #SpaceX #NASASocial","StatusId":"615248094909865984"},
//{"@search.text":"RT @NASA: If you find debris in the vicinity of today @SpaceX launch mishap, please stay away & call 321-867-2121. @NASA_Kennedy #SpaceX","StatusId":"615245961682665474"},
//{"@search.text":"RT @NASA: If you find debris in the vicinity of today @SpaceX launch mishap, please stay away & call 321-867-2121. @NASA_Kennedy #SpaceX","StatusId":"615245997443145728"},
//{"@search.text":"RT @NASA: If you find debris in the vicinity of today @SpaceX launch mishap, please stay away & call 321-867-2121. @NASA_Kennedy #SpaceX","StatusId":"615246353262731264"}]}
//create the columns
foreach (var col in results.value.First)
{
string name = col.Name;
name = name.Replace(".", "\x00B7");
SuggestionResults.Columns.Add(name);
}
//create the values for the table
foreach (var elem in results.value)
{
var row = SuggestionResults.Rows.Add();
foreach (var col in elem)
{
string name = col.Name;
name = name.Replace(".", "\x00B7");
if (col.Name == "@search.score")
{
row[name] = col.Value.Value;
}
else if (col.Name == "@search.highlights")
{
row[name] = col.Value.Text;
}
else
{
row[name] = col.Value.Value;
}
}
}
}
Status = string.Format("Search Query executed in {0}ms", watch.ElapsedMilliseconds);
Error = "";
}
else
{
Status = string.Format("0 results - Search Query executed in {0}ms", watch.ElapsedMilliseconds);
Error = "";
}
}
catch (WebException ex) //handle the response errors, this gives nice insight what went wrong
{
if (ex.Response != null)
{
var stream = ex.Response.GetResponseStream();
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var tmp = reader.ReadToEnd();
var json = JObject.Parse(tmp);
var error = json["error"];
if (error["message"] != null)
{
Error = string.Format("Error: {0}", error["message"].Value<string>());
}
if (error["code"] != null)
{
Error += string.Format("\r\nCode: {0}", error["code"].Value<string>());
}
}
}
}
}
catch (Exception ex)
{
Error = ex.Message;
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: Boolean
**
**
** Purpose: The boolean class serves as a wrapper for the primitive
** type boolean.
**
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
using System.Diagnostics.Contracts;
// The Boolean class provides the
// object representation of the boolean primitive type.
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Boolean : IComparable, IConvertible
#if GENERICS_WORK
, IComparable<Boolean>, IEquatable<Boolean>
#endif
{
//
// Member Variables
//
private bool m_value;
// The true value.
//
internal const int True = 1;
// The false value.
//
internal const int False = 0;
//
// Internal Constants are real consts for performance.
//
// The internal string representation of true.
//
internal const String TrueLiteral = "True";
// The internal string representation of false.
//
internal const String FalseLiteral = "False";
//
// Public Constants
//
// The public string representation of true.
//
public static readonly String TrueString = TrueLiteral;
// The public string representation of false.
//
public static readonly String FalseString = FalseLiteral;
//
// Overriden Instance Methods
//
/*=================================GetHashCode==================================
**Args: None
**Returns: 1 or 0 depending on whether this instance represents true or false.
**Exceptions: None
**Overriden From: Value
==============================================================================*/
// Provides a hash code for this instance.
public override int GetHashCode() {
return (m_value)?True:False;
}
/*===================================ToString===================================
**Args: None
**Returns: "True" or "False" depending on the state of the boolean.
**Exceptions: None.
==============================================================================*/
// Converts the boolean value of this instance to a String.
public override String ToString() {
if (false == m_value) {
return FalseLiteral;
}
return TrueLiteral;
}
public String ToString(IFormatProvider provider) {
if (false == m_value) {
return FalseLiteral;
}
return TrueLiteral;
}
// Determines whether two Boolean objects are equal.
public override bool Equals (Object obj) {
//If it's not a boolean, we're definitely not equal
if (!(obj is Boolean)) {
return false;
}
return (m_value==((Boolean)obj).m_value);
}
public bool Equals(Boolean obj)
{
return m_value == obj;
}
// Compares this object to another object, returning an integer that
// indicates the relationship. For booleans, false sorts before true.
// null is considered to be less than any instance.
// If object is not of type boolean, this method throws an ArgumentException.
//
// Returns a value less than zero if this object
//
public int CompareTo(Object obj) {
if (obj==null) {
return 1;
}
if (!(obj is Boolean)) {
throw new ArgumentException (Environment.GetResourceString("Arg_MustBeBoolean"));
}
if (m_value==((Boolean)obj).m_value) {
return 0;
} else if (m_value==false) {
return -1;
}
return 1;
}
public int CompareTo(Boolean value) {
if (m_value==value) {
return 0;
} else if (m_value==false) {
return -1;
}
return 1;
}
//
// Static Methods
//
// Determines whether a String represents true or false.
//
public static Boolean Parse (String value) {
if (value==null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
Boolean result = false;
if (!TryParse(value, out result)) {
throw new FormatException(Environment.GetResourceString("Format_BadBoolean"));
}
else {
return result;
}
}
// Determines whether a String represents true or false.
//
public static Boolean TryParse (String value, out Boolean result) {
result = false;
if (value==null) {
return false;
}
// For perf reasons, let's first see if they're equal, then do the
// trim to get rid of white space, and check again.
if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) {
result = true;
return true;
}
if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) {
result = false;
return true;
}
// Special case: Trim whitespace as well as null characters.
value = TrimWhiteSpaceAndNull(value);
if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) {
result = true;
return true;
}
if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) {
result = false;
return true;
}
return false;
}
private static String TrimWhiteSpaceAndNull(String value) {
int start = 0;
int end = value.Length-1;
char nullChar = (char) 0x0000;
while (start < value.Length) {
if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) {
break;
}
start++;
}
while (end >= start) {
if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) {
break;
}
end--;
}
return value.Substring(start, end - start + 1);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode() {
return TypeCode.Boolean;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return m_value;
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "Char"));
}
/// <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 Convert.ToInt32(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", "Boolean", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using FluentAssertions;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Configurer;
using Microsoft.Extensions.DependencyModel.Tests;
using Microsoft.Extensions.EnvironmentAbstractions;
using Moq;
using Xunit;
namespace Microsoft.DotNet.Configurer.UnitTests
{
public class GivenAFirstTimeUseNoticeSentinel
{
private const string DOTNET_USER_PROFILE_FOLDER_PATH = "some path";
private FileSystemMockBuilder _fileSystemMockBuilder;
public GivenAFirstTimeUseNoticeSentinel()
{
_fileSystemMockBuilder = FileSystemMockBuilder.Create();
}
[Fact]
public void TheSentinelHasTheCurrentVersionInItsName()
{
FirstTimeUseNoticeSentinel.SENTINEL.Should().Contain($"{Product.Version}");
}
[Fact]
public void ItReturnsTrueIfTheSentinelExists()
{
_fileSystemMockBuilder.AddFiles(DOTNET_USER_PROFILE_FOLDER_PATH, FirstTimeUseNoticeSentinel.SENTINEL);
var fileSystemMock = _fileSystemMockBuilder.Build();
var firstTimeUseNoticeSentinel =
new FirstTimeUseNoticeSentinel(
DOTNET_USER_PROFILE_FOLDER_PATH,
fileSystemMock);
firstTimeUseNoticeSentinel.Exists().Should().BeTrue();
}
[Fact]
public void ItReturnsFalseIfTheSentinelDoesNotExist()
{
var fileSystemMock = _fileSystemMockBuilder.Build();
var firstTimeUseNoticeSentinel =
new FirstTimeUseNoticeSentinel(
DOTNET_USER_PROFILE_FOLDER_PATH,
fileSystemMock);
firstTimeUseNoticeSentinel.Exists().Should().BeFalse();
}
[Fact]
public void ItCreatesTheSentinelInTheDotnetUserProfileFolderPathIfItDoesNotExistAlready()
{
var fileSystemMock = _fileSystemMockBuilder.Build();
var firstTimeUseNoticeSentinel =
new FirstTimeUseNoticeSentinel(
DOTNET_USER_PROFILE_FOLDER_PATH,
fileSystemMock);
firstTimeUseNoticeSentinel.Exists().Should().BeFalse();
firstTimeUseNoticeSentinel.CreateIfNotExists();
firstTimeUseNoticeSentinel.Exists().Should().BeTrue();
}
[Fact]
public void ItDoesNotCreateTheSentinelAgainIfItAlreadyExistsInTheDotnetUserProfileFolderPath()
{
const string contentToValidateSentinelWasNotReplaced = "some string";
var sentinel = Path.Combine(DOTNET_USER_PROFILE_FOLDER_PATH, FirstTimeUseNoticeSentinel.SENTINEL);
_fileSystemMockBuilder.AddFile(sentinel, contentToValidateSentinelWasNotReplaced);
var fileSystemMock = _fileSystemMockBuilder.Build();
var firstTimeUseNoticeSentinel =
new FirstTimeUseNoticeSentinel(
DOTNET_USER_PROFILE_FOLDER_PATH,
fileSystemMock);
firstTimeUseNoticeSentinel.Exists().Should().BeTrue();
firstTimeUseNoticeSentinel.CreateIfNotExists();
fileSystemMock.File.ReadAllText(sentinel).Should().Be(contentToValidateSentinelWasNotReplaced);
}
[Fact]
public void ItCreatesTheDotnetUserProfileFolderIfItDoesNotExistAlreadyWhenCreatingTheSentinel()
{
var fileSystemMock = _fileSystemMockBuilder.Build();
var directoryMock = new DirectoryMockWithSpy(fileSystemMock.Directory);
var firstTimeUseNoticeSentinel =
new FirstTimeUseNoticeSentinel(
DOTNET_USER_PROFILE_FOLDER_PATH,
new FileSystemMock(
fileSystemMock.File,
directoryMock));
firstTimeUseNoticeSentinel.CreateIfNotExists();
directoryMock.Exists(DOTNET_USER_PROFILE_FOLDER_PATH).Should().BeTrue();
directoryMock.CreateDirectoryInvoked.Should().BeTrue();
}
[Fact]
public void ItDoesNotAttemptToCreateTheDotnetUserProfileFolderIfItAlreadyExistsWhenCreatingTheSentinel()
{
var fileSystemMock = _fileSystemMockBuilder.Build();
var directoryMock = new DirectoryMockWithSpy(fileSystemMock.Directory, new List<string> { DOTNET_USER_PROFILE_FOLDER_PATH });
var firstTimeUseNoticeSentinel =
new FirstTimeUseNoticeSentinel(
DOTNET_USER_PROFILE_FOLDER_PATH,
new FileSystemMock(
fileSystemMock.File,
directoryMock));
firstTimeUseNoticeSentinel.CreateIfNotExists();
directoryMock.CreateDirectoryInvoked.Should().BeFalse();
}
private class FileSystemMock : IFileSystem
{
public FileSystemMock(IFile file, IDirectory directory)
{
File = file;
Directory = directory;
}
public IFile File { get; private set; }
public IDirectory Directory { get; private set; }
}
private class DirectoryMockWithSpy : IDirectory
{
private readonly IDirectory _directorySystem;
public bool CreateDirectoryInvoked { get; set; }
public DirectoryMockWithSpy(IDirectory directorySystem, IList<string> directories = null)
{
if (directorySystem != null) _directorySystem = directorySystem;
if (directories != null)
{
foreach (var directory in directories)
{
_directorySystem.CreateDirectory(directory);
}
}
}
public bool Exists(string path)
{
return _directorySystem.Exists(path);
}
public ITemporaryDirectory CreateTemporaryDirectory()
{
throw new NotImplementedException();
}
public IEnumerable<string> EnumerateFiles(string path)
{
throw new NotImplementedException();
}
public IEnumerable<string> EnumerateFileSystemEntries(string path)
{
throw new NotImplementedException();
}
public IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern)
{
throw new NotImplementedException();
}
public string GetCurrentDirectory()
{
throw new NotImplementedException();
}
public void CreateDirectory(string path)
{
_directorySystem.CreateDirectory(path);
CreateDirectoryInvoked = true;
}
public void Delete(string path, bool recursive)
{
throw new NotImplementedException();
}
public void Move(string source, string destination)
{
throw new NotImplementedException();
}
}
}
}
| |
/*
* Copyright (c) 2006-2008, Second Life Reverse Engineering Team
* 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 Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using libsecondlife.StructuredData;
namespace libsecondlife
{
public partial class Primitive : LLObject
{
#region Enums
/// <summary>
/// Extra parameters for primitives, these flags are for features that have
/// been added after the original ObjectFlags that has all eight bits
/// reserved already
/// </summary>
[Flags]
public enum ExtraParamType : ushort
{
/// <summary>Whether this object has flexible parameters</summary>
Flexible = 0x10,
/// <summary>Whether this object has light parameters</summary>
Light = 0x20,
/// <summary>Whether this object is a sculpted prim</summary>
Sculpt = 0x30
}
/// <summary>
///
/// </summary>
[Flags]
public enum TextureAnimMode : uint
{
/// <summary>Disable texture animation</summary>
ANIM_OFF = 0x00,
/// <summary>Enable texture animation</summary>
ANIM_ON = 0x01,
/// <summary>Loop when animating textures</summary>
LOOP = 0x02,
/// <summary>Animate in reverse direction</summary>
REVERSE = 0x04,
/// <summary>Animate forward then reverse</summary>
PING_PONG = 0x08,
/// <summary>Slide texture smoothly instead of frame-stepping</summary>
SMOOTH = 0x10,
/// <summary>Rotate texture instead of using frames</summary>
ROTATE = 0x20,
/// <summary>Scale texture instead of using frames</summary>
SCALE = 0x40,
}
/// <summary>
///
/// </summary>
public enum JointType : byte
{
/// <summary></summary>
Invalid = 0,
/// <summary></summary>
Hinge = 1,
/// <summary></summary>
Point = 2,
/// <summary></summary>
//[Obsolete]
//LPoint = 3,
///// <summary></summary>
//[Obsolete]
//Wheel = 4
}
/// <summary>
///
/// </summary>
public enum SculptType : byte
{
/// <summary></summary>
None = 0,
/// <summary></summary>
Sphere = 1,
/// <summary></summary>
Torus = 2,
/// <summary></summary>
Plane = 3,
/// <summary></summary>
Cylinder = 4
}
/// <summary>
///
/// </summary>
public enum FaceType : ushort
{
/// <summary></summary>
PathBegin = 0x1 << 0,
/// <summary></summary>
PathEnd = 0x1 << 1,
/// <summary></summary>
InnerSide = 0x1 << 2,
/// <summary></summary>
ProfileBegin = 0x1 << 3,
/// <summary></summary>
ProfileEnd = 0x1 << 4,
/// <summary></summary>
OuterSide0 = 0x1 << 5,
/// <summary></summary>
OuterSide1 = 0x1 << 6,
/// <summary></summary>
OuterSide2 = 0x1 << 7,
/// <summary></summary>
OuterSide3 = 0x1 << 8
}
#endregion Enums
#region Subclasses
/// <summary>
/// Controls the texture animation of a particular prim
/// </summary>
public struct TextureAnimation
{
/// <summary></summary>
public TextureAnimMode Flags;
/// <summary></summary>
public uint Face;
/// <summary></summary>
public uint SizeX;
/// <summary></summary>
public uint SizeY;
/// <summary></summary>
public float Start;
/// <summary></summary>
public float Length;
/// <summary></summary>
public float Rate;
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="pos"></param>
public TextureAnimation(byte[] data, int pos)
{
if (data.Length >= 16)
{
Flags = (TextureAnimMode)((uint)data[pos++]);
Face = (uint)data[pos++];
SizeX = (uint)data[pos++];
SizeY = (uint)data[pos++];
Start = Helpers.BytesToFloat(data, pos);
Length = Helpers.BytesToFloat(data, pos + 4);
Rate = Helpers.BytesToFloat(data, pos + 8);
}
else
{
Flags = 0;
Face = 0;
SizeX = 0;
SizeY = 0;
Start = 0.0f;
Length = 0.0f;
Rate = 0.0f;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public byte[] GetBytes()
{
byte[] data = new byte[16];
int pos = 0;
data[pos++] = (byte)Flags;
data[pos++] = (byte)Face;
data[pos++] = (byte)SizeX;
data[pos++] = (byte)SizeY;
Helpers.FloatToBytes(Start).CopyTo(data, pos);
Helpers.FloatToBytes(Length).CopyTo(data, pos + 4);
Helpers.FloatToBytes(Rate).CopyTo(data, pos + 4);
return data;
}
}
/// <summary>
/// Information on the flexible properties of a primitive
/// </summary>
public struct FlexibleData
{
/// <summary></summary>
public int Softness;
/// <summary></summary>
public float Gravity;
/// <summary></summary>
public float Drag;
/// <summary></summary>
public float Wind;
/// <summary></summary>
public float Tension;
/// <summary></summary>
public LLVector3 Force;
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="pos"></param>
public FlexibleData(byte[] data, int pos)
{
if (data.Length >= 5)
{
Softness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7);
Tension = (float)(data[pos++] & 0x7F) / 10.0f;
Drag = (float)(data[pos++] & 0x7F) / 10.0f;
Gravity = (float)(data[pos++] / 10.0f) - 10.0f;
Wind = (float)data[pos++] / 10.0f;
Force = new LLVector3(data, pos);
}
else
{
Softness = 0;
Tension = 0.0f;
Drag = 0.0f;
Gravity = 0.0f;
Wind = 0.0f;
Force = LLVector3.Zero;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public byte[] GetBytes()
{
byte[] data = new byte[16];
int i = 0;
// Softness is packed in the upper bits of tension and drag
data[i] = (byte)((Softness & 2) << 6);
data[i + 1] = (byte)((Softness & 1) << 7);
data[i++] |= (byte)((byte)(Tension * 10.01f) & 0x7F);
data[i++] |= (byte)((byte)(Drag * 10.01f) & 0x7F);
data[i++] = (byte)((Gravity + 10.0f) * 10.01f);
data[i++] = (byte)(Wind * 10.01f);
Force.GetBytes().CopyTo(data, i);
return data;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public LLSD ToLLSD()
{
LLSDMap map = new LLSDMap();
map["simulate_lod"] = LLSD.FromInteger(Softness);
map["gravity"] = LLSD.FromReal(Gravity);
map["air_friction"] = LLSD.FromReal(Drag);
map["wind_sensitivity"] = LLSD.FromReal(Wind);
map["tension"] = LLSD.FromReal(Tension);
map["user_force"] = Force.ToLLSD();
return map;
}
public static FlexibleData FromLLSD(LLSD llsd)
{
FlexibleData flex = new FlexibleData();
if (llsd.Type == LLSDType.Map)
{
LLSDMap map = (LLSDMap)llsd;
flex.Softness = map["simulate_lod"].AsInteger();
flex.Gravity = (float)map["gravity"].AsReal();
flex.Drag = (float)map["air_friction"].AsReal();
flex.Wind = (float)map["wind_sensitivity"].AsReal();
flex.Tension = (float)map["tension"].AsReal();
flex.Force.FromLLSD(map["user_force"]);
}
return flex;
}
}
/// <summary>
/// Information on the light properties of a primitive
/// </summary>
public struct LightData
{
/// <summary></summary>
public LLColor Color;
/// <summary></summary>
public float Intensity;
/// <summary></summary>
public float Radius;
/// <summary></summary>
public float Cutoff;
/// <summary></summary>
public float Falloff;
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="pos"></param>
public LightData(byte[] data, int pos)
{
if (data.Length - pos >= 16)
{
Color = new LLColor(data, pos, false);
Radius = Helpers.BytesToFloat(data, pos + 4);
Cutoff = Helpers.BytesToFloat(data, pos + 8);
Falloff = Helpers.BytesToFloat(data, pos + 12);
// Alpha in color is actually intensity
Intensity = Color.A;
Color.A = 1f;
}
else
{
Color = LLColor.Black;
Radius = 0f;
Cutoff = 0f;
Falloff = 0f;
Intensity = 0f;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public byte[] GetBytes()
{
byte[] data = new byte[16];
// Alpha channel in color is intensity
LLColor tmpColor = Color;
tmpColor.A = Intensity;
tmpColor.GetBytes().CopyTo(data, 0);
Helpers.FloatToBytes(Radius).CopyTo(data, 4);
Helpers.FloatToBytes(Cutoff).CopyTo(data, 8);
Helpers.FloatToBytes(Falloff).CopyTo(data, 12);
return data;
}
public LLSD ToLLSD()
{
LLSDMap map = new LLSDMap();
map["color"] = Color.ToLLSD();
map["intensity"] = LLSD.FromReal(Intensity);
map["radius"] = LLSD.FromReal(Radius);
map["cutoff"] = LLSD.FromReal(Cutoff);
map["falloff"] = LLSD.FromReal(Falloff);
return map;
}
public static LightData FromLLSD(LLSD llsd)
{
LightData light = new LightData();
if (llsd.Type == LLSDType.Map)
{
LLSDMap map = (LLSDMap)llsd;
light.Color.FromLLSD(map["color"]);
light.Intensity = (float)map["intensity"].AsReal();
light.Radius = (float)map["radius"].AsReal();
light.Cutoff = (float)map["cutoff"].AsReal();
light.Falloff = (float)map["falloff"].AsReal();
}
return light;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("Color: {0} Intensity: {1} Radius: {2} Cutoff: {3} Falloff: {4}",
Color, Intensity, Radius, Cutoff, Falloff);
}
}
/// <summary>
/// Information on the sculpt properties of a sculpted primitive
/// </summary>
public struct SculptData
{
public LLUUID SculptTexture;
public SculptType Type;
public SculptData(byte[] data, int pos)
{
if (data.Length >= 17)
{
SculptTexture = new LLUUID(data, pos);
Type = (SculptType)data[pos + 16];
}
else
{
SculptTexture = LLUUID.Zero;
Type = SculptType.None;
}
}
public byte[] GetBytes()
{
byte[] data = new byte[17];
SculptTexture.GetBytes().CopyTo(data, 0);
data[16] = (byte)Type;
return data;
}
public LLSD ToLLSD()
{
LLSDMap map = new LLSDMap();
map["texture"] = LLSD.FromUUID(SculptTexture);
map["type"] = LLSD.FromInteger((int)Type);
return map;
}
public static SculptData FromLLSD(LLSD llsd)
{
SculptData sculpt = new SculptData();
if (llsd.Type == LLSDType.Map)
{
LLSDMap map = (LLSDMap)llsd;
sculpt.SculptTexture = map["texture"].AsUUID();
sculpt.Type = (SculptType)map["type"].AsInteger();
}
return sculpt;
}
}
#endregion Subclasses
#region Public Members
/// <summary></summary>
public TextureAnimation TextureAnim;
/// <summary></summary>
public FlexibleData Flexible;
/// <summary></summary>
public LightData Light;
/// <summary></summary>
public SculptData Sculpt;
/// <summary></summary>
public ParticleSystem ParticleSys;
/// <summary></summary>
public ClickAction ClickAction;
/// <summary></summary>
public LLUUID Sound;
/// <summary>Identifies the owner of the audio or particle system</summary>
public LLUUID OwnerID;
/// <summary></summary>
public byte SoundFlags;
/// <summary></summary>
public float SoundGain;
/// <summary></summary>
public float SoundRadius;
/// <summary></summary>
public string Text;
/// <summary></summary>
public LLColor TextColor;
/// <summary></summary>
public string MediaURL;
/// <summary></summary>
public JointType Joint;
/// <summary></summary>
public LLVector3 JointPivot;
/// <summary></summary>
public LLVector3 JointAxisOrAnchor;
#endregion Public Members
/// <summary>
/// Default constructor
/// </summary>
public Primitive()
{
}
public override string ToString()
{
return String.Format("ID: {0}, GroupID: {1}, ParentID: {2}, LocalID: {3}, Flags: {4}, " +
"State: {5}, PCode: {6}, Material: {7}", ID, GroupID, ParentID, LocalID, Flags, Data.State,
Data.PCode, Data.Material);
}
public LLSD ToLLSD()
{
LLSDMap path = new LLSDMap(14);
path["begin"] = LLSD.FromReal(Data.PathBegin);
path["curve"] = LLSD.FromInteger((int)Data.PathCurve);
path["end"] = LLSD.FromReal(Data.PathEnd);
path["radius_offset"] = LLSD.FromReal(Data.PathRadiusOffset);
path["revolutions"] = LLSD.FromReal(Data.PathRevolutions);
path["scale_x"] = LLSD.FromReal(Data.PathScaleX);
path["scale_y"] = LLSD.FromReal(Data.PathScaleY);
path["shear_x"] = LLSD.FromReal(Data.PathShearX);
path["shear_y"] = LLSD.FromReal(Data.PathShearY);
path["skew"] = LLSD.FromReal(Data.PathSkew);
path["taper_x"] = LLSD.FromReal(Data.PathTaperX);
path["taper_y"] = LLSD.FromReal(Data.PathTaperY);
path["twist"] = LLSD.FromReal(Data.PathTwist);
path["twist_begin"] = LLSD.FromReal(Data.PathTwistBegin);
LLSDMap profile = new LLSDMap(4);
profile["begin"] = LLSD.FromReal(Data.ProfileBegin);
profile["curve"] = LLSD.FromInteger((int)Data.ProfileCurve);
profile["hole"] = LLSD.FromInteger((int)Data.ProfileHole);
profile["end"] = LLSD.FromReal(Data.ProfileEnd);
profile["hollow"] = LLSD.FromReal(Data.ProfileHollow);
LLSDMap volume = new LLSDMap(2);
volume["path"] = path;
volume["profile"] = profile;
LLSDMap prim = new LLSDMap(9);
prim["name"] = LLSD.FromString(Properties.Name);
prim["description"] = LLSD.FromString(Properties.Description);
prim["phantom"] = LLSD.FromBoolean(((Flags & ObjectFlags.Phantom) != 0));
prim["physical"] = LLSD.FromBoolean(((Flags & ObjectFlags.Physics) != 0));
prim["position"] = Position.ToLLSD();
prim["rotation"] = Rotation.ToLLSD();
prim["scale"] = Scale.ToLLSD();
prim["material"] = LLSD.FromInteger((int)Data.Material);
prim["shadows"] = LLSD.FromBoolean(((Flags & ObjectFlags.CastShadows) != 0));
prim["textures"] = Textures.ToLLSD();
prim["volume"] = volume;
if (ParentID != 0)
prim["parentid"] = LLSD.FromInteger(ParentID);
prim["light"] = Light.ToLLSD();
prim["flex"] = Flexible.ToLLSD();
prim["sculpt"] = Sculpt.ToLLSD();
return prim;
}
public static Primitive FromLLSD(LLSD llsd)
{
Primitive prim = new Primitive();
LLObject.ObjectData data = new ObjectData();
LLSDMap map = (LLSDMap)llsd;
LLSDMap volume = (LLSDMap)map["volume"];
LLSDMap path = (LLSDMap)volume["path"];
LLSDMap profile = (LLSDMap)volume["profile"];
#region Path/Profile
data.PathBegin = (float)path["begin"].AsReal();
data.PathCurve = (PathCurve)path["curve"].AsInteger();
data.PathEnd = (float)path["end"].AsReal();
data.PathRadiusOffset = (float)path["radius_offset"].AsReal();
data.PathRevolutions = (float)path["revolutions"].AsReal();
data.PathScaleX = (float)path["scale_x"].AsReal();
data.PathScaleY = (float)path["scale_y"].AsReal();
data.PathShearX = (float)path["shear_x"].AsReal();
data.PathShearY = (float)path["shear_y"].AsReal();
data.PathSkew = (float)path["skew"].AsReal();
data.PathTaperX = (float)path["taper_x"].AsReal();
data.PathTaperY = (float)path["taper_y"].AsReal();
data.PathTwist = (float)path["twist"].AsReal();
data.PathTwistBegin = (float)path["twist_begin"].AsReal();
data.ProfileBegin = (float)profile["begin"].AsReal();
data.ProfileCurve = (ProfileCurve)profile["curve"].AsInteger();
data.ProfileHole = (HoleType)profile["hole"].AsInteger();
data.ProfileEnd = (float)profile["end"].AsReal();
data.ProfileHollow = (float)profile["hollow"].AsReal();
#endregion Path/Profile
prim.Data = data;
if (map["phantom"].AsBoolean())
prim.Flags |= ObjectFlags.Phantom;
if (map["physical"].AsBoolean())
prim.Flags |= ObjectFlags.Physics;
if (map["shadows"].AsBoolean())
prim.Flags |= ObjectFlags.CastShadows;
prim.ParentID = (uint)map["parentid"].AsInteger();
prim.Position.FromLLSD(map["position"]);
prim.Rotation.FromLLSD(map["rotation"]);
prim.Scale.FromLLSD(map["scale"]);
prim.Data.Material = (MaterialType)map["material"].AsInteger();
prim.Flexible = FlexibleData.FromLLSD(map["flex"]);
prim.Light = LightData.FromLLSD(map["light"]);
prim.Sculpt = SculptData.FromLLSD(map["sculpt"]);
prim.Textures = TextureEntry.FromLLSD(map["textures"]);
if (!string.IsNullOrEmpty(map["name"].AsString())) {
prim.Properties.Name = map["name"].AsString();
}
if (!string.IsNullOrEmpty(map["description"].AsString())) {
prim.Properties.Description = map["description"].AsString();
}
return prim;
}
internal int SetExtraParamsFromBytes(byte[] data, int pos)
{
int i = pos;
int totalLength = 1;
if (data.Length == 0 || pos >= data.Length)
return 0;
try
{
byte extraParamCount = data[i++];
for (int k = 0; k < extraParamCount; k++)
{
ExtraParamType type = (ExtraParamType)Helpers.BytesToUInt16(data, i);
i += 2;
uint paramLength = Helpers.BytesToUIntBig(data, i);
i += 4;
if (type == ExtraParamType.Flexible)
Flexible = new FlexibleData(data, i);
else if (type == ExtraParamType.Light)
Light = new LightData(data, i);
else if (type == ExtraParamType.Sculpt)
Sculpt = new SculptData(data, i);
i += (int)paramLength;
totalLength += (int)paramLength + 6;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return totalLength;
}
}
}
| |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
// using System.Data;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Color = SwinGameSDK.Color;
/// <summary>
/// Player has its own _PlayerGrid, and can see an _EnemyGrid, it can also check if
/// all ships are deployed and if all ships are detroyed. A Player can also attach.
/// </summary>
public class Player : IEnumerable<Ship>
{
private static readonly Regex _VALID_CODE = new Regex("^#([0-9a-f]{3}|[0-9a-f]{6})$",RegexOptions.IgnoreCase);
/// <summary>
/// Provides a random number generator.
/// </summary>
protected static Random _Random = new Random();
private Dictionary<ShipName, Ship> _Ships = new Dictionary<ShipName, Ship>();
private SeaGrid _playerGrid;
private ISeaGrid _enemyGrid;
/// <summary>
/// Provides access to the current game.
/// </summary>
protected BattleShipsGame _game;
private int _shots;
private int _hits;
private int _misses;
private readonly Color _col;
/// <summary>
/// Gets the color of this player's turn indicator light.
/// </summary>
/// <value>The turn indicator.</value>
public virtual Color TurnIndicator {
get {
return _col;
}
}
private static byte HexCharLookup(char digit) {
// For some reason .NET doesn't have this built-in, unless you cast to an Int32 first
byte res;
switch (digit) {
case '0':
res = 0;
break;
case '1':
res = 1;
break;
case '2':
res = 2;
break;
case '3':
res = 3;
break;
case '4':
res = 4;
break;
case '5':
res = 5;
break;
case '6':
res = 6;
break;
case '7':
res = 7;
break;
case '8':
res = 8;
break;
case '9':
res = 9;
break;
case 'A':
case 'a':
res = 10;
break;
case 'B':
case 'b':
res = 11;
break;
case 'C':
case 'c':
res = 12;
break;
case 'D':
case 'd':
res = 13;
break;
case 'E':
case 'e':
res = 14;
break;
case 'F':
case 'f':
res = 15;
break;
default:
throw new ArgumentOutOfRangeException("digit","Passed char must be a valid hexadecimal digit (0-9 A-F a-f).");
}
return res;
}
private byte LoadShorthand(char digit) {
byte d = HexCharLookup(digit);
return (byte)((d << 4) | d);
}
private byte LoadLonghand(char leadDigit,char trailingDigit) {
byte d1 = HexCharLookup(leadDigit);
byte d2 = HexCharLookup(trailingDigit);
return (byte)((d1 << 4) | d2);
}
/// <summary>
/// Generates a SwinGame Color based on the given color code.
/// </summary>
/// <param name="code">The color to generate.</param>
protected Color GetColor(string code) {
Color res;
Match m = _VALID_CODE.Match(code);
if (m.Success) {
bool shorthand = code.Length == 4;
byte r = shorthand ? LoadShorthand(code[1]) : LoadLonghand(code[1], code[2]);
byte g = shorthand ? LoadShorthand(code[2]) : LoadLonghand(code[3], code[4]);
byte b = shorthand ? LoadShorthand(code[3]) : LoadLonghand(code[5], code[6]);
byte a = 255;
res = Color.FromArgb((a << 24) + (r << 16) + (g << 8) + b);
} else {
res = Color.Transparent;
}
return res;
}
/// <summary>
/// Returns the game that the player is part of.
/// </summary>
/// <value>The game</value>
/// <returns>The game that the player is playing</returns>
public BattleShipsGame Game {
get { return _game; }
set { _game = value; }
}
/// <summary>
/// Sets the grid of the enemy player
/// </summary>
/// <value>The enemy's sea grid</value>
public ISeaGrid Enemy {
set { _enemyGrid = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="Player"/> class.
/// </summary>
/// <param name="controller">The current game.</param>
public Player(BattleShipsGame controller)
{
_game = controller;
_playerGrid = new SeaGrid(_Ships);
//for each ship add the ships name so the seagrid knows about them
foreach (ShipName name in Enum.GetValues(typeof(ShipName))) {
if (name != ShipName.None) {
_Ships.Add(name, new Ship(name));
}
}
_col = GetColor("#4ac925");
RandomizeDeployment();
}
/// <summary>
/// The EnemyGrid is a ISeaGrid because you shouldn't be allowed to see the enemies ships
/// </summary>
public ISeaGrid EnemyGrid {
get { return _enemyGrid; }
set { _enemyGrid = value; }
}
/// <summary>
/// The PlayerGrid is just a normal SeaGrid where the players ships can be deployed and seen
/// </summary>
public SeaGrid PlayerGrid {
get { return _playerGrid; }
}
/// <summary>
/// ReadyToDeploy returns true if all ships are deployed
/// </summary>
public bool ReadyToDeploy {
get { return _playerGrid.AllDeployed; }
}
/// <summary>
/// Gets a value indicating whether all of the player's ships have been destroyed.
/// </summary>
/// <value><c>true</c> if all ships are destroyed; otherwise, <c>false</c>.</value>
public bool IsDestroyed {
//Check if all ships are destroyed... -1 for the none ship
get { return _playerGrid.ShipsKilled == Enum.GetValues(typeof(ShipName)).Length - 1; }
}
/// <summary>
/// Returns the Player's ship with the given name.
/// </summary>
/// <param name="name">the name of the ship to return</param>
/// <value>The ship</value>
/// <returns>The ship with the indicated name</returns>
/// <remarks>The none ship returns nothing/null</remarks>
public Ship Ship(ShipName name) {
if (name == ShipName.None)
return null;
return _Ships[name];
}
/// <summary>
/// The number of shots the player has made
/// </summary>
/// <value>shots taken</value>
/// <returns>teh number of shots taken</returns>
public int Shots {
get { return _shots; }
}
/// <summary>
/// Gets the number of hits.
/// </summary>
public int Hits {
get { return _hits; }
}
/// <summary>
/// Total number of shots that missed
/// </summary>
/// <value>miss count</value>
/// <returns>the number of shots that have missed ships</returns>
public int Missed {
get { return _misses; }
}
/// <summary>
/// The current score.
/// </summary>
public int Score {
get {
if (IsDestroyed) {
return 0;
} else {
return (Hits * 12) - Shots - (PlayerGrid.ShipsKilled * 20);
}
}
}
/// <summary>
/// Makes it possible to enumerate over the ships the player
/// has.
/// </summary>
/// <returns>A Ship enumerator</returns>
public IEnumerator<Ship> GetShipEnumerator()
{
Ship[] result = new Ship[_Ships.Values.Count + 1];
_Ships.Values.CopyTo(result, 0);
List<Ship> lst = new List<Ship>();
lst.AddRange(result);
return lst.GetEnumerator();
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
IEnumerator<Ship> IEnumerable<Ship>.GetEnumerator()
{
return GetShipEnumerator();
}
/// <summary>
/// Makes it possible to enumerate over the ships the player
/// has.
/// </summary>
/// <returns>A Ship enumerator</returns>
public IEnumerator GetEnumerator()
{
Ship[] result = new Ship[_Ships.Values.Count + 1];
_Ships.Values.CopyTo(result, 0);
List<Ship> lst = new List<Ship>();
lst.AddRange(result);
return lst.GetEnumerator();
}
/// <summary>
/// Vitual Attack allows the player to shoot
/// </summary>
public virtual AttackResult Attack()
{
//human does nothing here...
return null;
}
/// <summary>
/// Shoot at a given row/column
/// </summary>
/// <param name="row">the row to attack</param>
/// <param name="col">the column to attack</param>
/// <returns>the result of the attack</returns>
internal AttackResult Shoot(int row, int col)
{
AttackResult result = default(AttackResult);
result = EnemyGrid.HitTile(row, col);
switch (result.Value) {
case ResultOfAttack.Destroyed:
case ResultOfAttack.Hit:
_shots += 1;
_hits += 1;
break;
case ResultOfAttack.Miss:
_shots += 1;
_misses += 1;
break;
}
return result;
}
/// <summary>
/// Ramdomizes the positioning of this player's ships.
/// </summary>
public virtual void RandomizeDeployment()
{
bool placementSuccessful = false;
Direction heading = default(Direction);
//for each ship to deploy in shipist
foreach (ShipName shipToPlace in Enum.GetValues(typeof(ShipName))) {
if (shipToPlace == ShipName.None)
continue;
placementSuccessful = false;
//generate random position until the ship can be placed
do {
int dir = _Random.Next(2);
int x = _Random.Next(0, 11);
int y = _Random.Next(0, 11);
if (dir == 0) {
heading = Direction.UpDown;
} else {
heading = Direction.LeftRight;
}
//try to place ship, if position unplaceable, generate new coordinates
try {
PlayerGrid.MoveShip(x, y, shipToPlace, heading);
placementSuccessful = true;
} catch {
placementSuccessful = false;
}
} while (!placementSuccessful);
}
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira ([email protected])
// 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class ConditionalExpression : Expression
{
protected Expression _condition;
protected Expression _trueValue;
protected Expression _falseValue;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ConditionalExpression CloneNode()
{
return (ConditionalExpression)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ConditionalExpression CleanClone()
{
return (ConditionalExpression)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.ConditionalExpression; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnConditionalExpression(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( ConditionalExpression)node;
if (!Node.Matches(_condition, other._condition)) return NoMatch("ConditionalExpression._condition");
if (!Node.Matches(_trueValue, other._trueValue)) return NoMatch("ConditionalExpression._trueValue");
if (!Node.Matches(_falseValue, other._falseValue)) return NoMatch("ConditionalExpression._falseValue");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_condition == existing)
{
this.Condition = (Expression)newNode;
return true;
}
if (_trueValue == existing)
{
this.TrueValue = (Expression)newNode;
return true;
}
if (_falseValue == existing)
{
this.FalseValue = (Expression)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
ConditionalExpression clone = (ConditionalExpression)FormatterServices.GetUninitializedObject(typeof(ConditionalExpression));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._expressionType = _expressionType;
if (null != _condition)
{
clone._condition = _condition.Clone() as Expression;
clone._condition.InitializeParent(clone);
}
if (null != _trueValue)
{
clone._trueValue = _trueValue.Clone() as Expression;
clone._trueValue.InitializeParent(clone);
}
if (null != _falseValue)
{
clone._falseValue = _falseValue.Clone() as Expression;
clone._falseValue.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
_expressionType = null;
if (null != _condition)
{
_condition.ClearTypeSystemBindings();
}
if (null != _trueValue)
{
_trueValue.ClearTypeSystemBindings();
}
if (null != _falseValue)
{
_falseValue.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression Condition
{
get { return _condition; }
set
{
if (_condition != value)
{
_condition = value;
if (null != _condition)
{
_condition.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression TrueValue
{
get { return _trueValue; }
set
{
if (_trueValue != value)
{
_trueValue = value;
if (null != _trueValue)
{
_trueValue.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression FalseValue
{
get { return _falseValue; }
set
{
if (_falseValue != value)
{
_falseValue = value;
if (null != _falseValue)
{
_falseValue.InitializeParent(this);
}
}
}
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using NUnit.Framework;
namespace NUnit.TestData.ExpectExceptionTest
{
[TestFixture]
public class BaseException
{
[Test]
[ExpectedException(typeof(ArgumentException))]
public void BaseExceptionTest()
{
throw new Exception();
}
}
[TestFixture]
public class DerivedException
{
[Test]
[ExpectedException(typeof(Exception))]
public void DerivedExceptionTest()
{
throw new ArgumentException();
}
}
[TestFixture]
public class MismatchedException
{
[Test]
[ExpectedException(typeof(ArgumentException))]
public void MismatchedExceptionType()
{
throw new ArgumentOutOfRangeException();
}
[Test]
[ExpectedException(ExpectedException=typeof(ArgumentException))]
public void MismatchedExceptionTypeAsNamedParameter()
{
throw new ArgumentOutOfRangeException();
}
[Test]
[ExpectedException(typeof(ArgumentException), UserMessage="custom message")]
public void MismatchedExceptionTypeWithUserMessage()
{
throw new ArgumentOutOfRangeException();
}
[Test]
[ExpectedException("System.ArgumentException")]
public void MismatchedExceptionName()
{
throw new ArgumentOutOfRangeException();
}
[Test]
[ExpectedException("System.ArgumentException", UserMessage="custom message")]
public void MismatchedExceptionNameWithUserMessage()
{
throw new ArgumentOutOfRangeException();
}
}
[TestFixture]
public class SetUpExceptionTests
{
[SetUp]
public void Init()
{
throw new ArgumentException("SetUp Exception");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void Test()
{
}
}
[TestFixture]
public class TearDownExceptionTests
{
[TearDown]
public void CleanUp()
{
throw new ArgumentException("TearDown Exception");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void Test()
{}
}
[TestFixture]
public class TestThrowsExceptionFixture
{
[Test]
public void TestThrow()
{
throw new Exception();
}
}
[TestFixture]
public class TestDoesNotThrowExceptionFixture
{
[Test, ExpectedException("System.ArgumentException")]
public void TestDoesNotThrowExceptionName()
{
}
[Test, ExpectedException("System.ArgumentException", UserMessage="custom message")]
public void TestDoesNotThrowExceptionNameWithUserMessage()
{
}
[Test, ExpectedException( typeof( System.ArgumentException ) )]
public void TestDoesNotThrowExceptionType()
{
}
[Test, ExpectedException( typeof( System.ArgumentException ), UserMessage="custom message" )]
public void TestDoesNotThrowExceptionTypeWithUserMessage()
{
}
[Test, ExpectedException]
public void TestDoesNotThrowUnspecifiedException()
{
}
[Test, ExpectedException( UserMessage="custom message" )]
public void TestDoesNotThrowUnspecifiedExceptionWithUserMessage()
{
}
}
[TestFixture]
public class TestThrowsExceptionWithRightMessage
{
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage="the message")]
public void TestThrow()
{
throw new Exception("the message");
}
}
[TestFixture]
public class TestThrowsArgumentOutOfRangeException
{
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException)) ]
public void TestThrow()
{
throw new ArgumentOutOfRangeException("param", "actual value", "the message");
}
}
[TestFixture]
public class TestThrowsExceptionWithWrongMessage
{
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage="not the message")]
public void TestThrow()
{
throw new Exception("the message");
}
[Test]
[ExpectedException( typeof(Exception), ExpectedMessage="not the message", UserMessage="custom message" )]
public void TestThrowWithUserMessage()
{
throw new Exception("the message");
}
}
[TestFixture]
public class TestAssertsBeforeThrowingException
{
[Test]
[ExpectedException(typeof(Exception))]
public void TestAssertFail()
{
Assert.Fail( "private message" );
}
}
[TestFixture]
public class ExceptionHandlerCalledClass : IExpectException
{
public bool HandlerCalled = false;
public bool AlternateHandlerCalled = false;
[Test, ExpectedException(typeof(ArgumentException))]
public void ThrowsArgumentException()
{
throw new ArgumentException();
}
[Test, ExpectedException(typeof(ArgumentException), Handler = "AlternateExceptionHandler")]
public void ThrowsArgumentException_AlternateHandler()
{
throw new ArgumentException();
}
[Test, ExpectedException(typeof(ArgumentException))]
public void ThrowsApplicationException()
{
throw new ApplicationException();
}
[Test, ExpectedException(typeof(ArgumentException), Handler = "AlternateExceptionHandler")]
public void ThrowsApplicationException_AlternateHandler()
{
throw new ApplicationException();
}
[Test, ExpectedException(typeof(ArgumentException), Handler = "DeliberatelyMissingHandler")]
public void MethodWithBadHandler()
{
throw new ArgumentException();
}
public void HandleException(Exception ex)
{
HandlerCalled = true;
}
public void AlternateExceptionHandler(Exception ex)
{
AlternateHandlerCalled = true;
}
}
}
| |
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 TestApp.Areas.HelpPage.ModelDescriptions;
using TestApp.Areas.HelpPage.Models;
namespace TestApp.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);
}
}
}
}
| |
namespace Humidifier.Redshift
{
using System.Collections.Generic;
using ClusterTypes;
public class Cluster : Humidifier.Resource
{
public static class Attributes
{
}
public override string AWSTypeName
{
get
{
return @"AWS::Redshift::Cluster";
}
}
/// <summary>
/// AllowVersionUpgrade
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-allowversionupgrade
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic AllowVersionUpgrade
{
get;
set;
}
/// <summary>
/// AutomatedSnapshotRetentionPeriod
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-automatedsnapshotretentionperiod
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic AutomatedSnapshotRetentionPeriod
{
get;
set;
}
/// <summary>
/// AvailabilityZone
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-availabilityzone
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic AvailabilityZone
{
get;
set;
}
/// <summary>
/// ClusterIdentifier
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clusteridentifier
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic ClusterIdentifier
{
get;
set;
}
/// <summary>
/// ClusterParameterGroupName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clusterparametergroupname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ClusterParameterGroupName
{
get;
set;
}
/// <summary>
/// ClusterSecurityGroups
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clustersecuritygroups
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic ClusterSecurityGroups
{
get;
set;
}
/// <summary>
/// ClusterSubnetGroupName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clustersubnetgroupname
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic ClusterSubnetGroupName
{
get;
set;
}
/// <summary>
/// ClusterType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clustertype
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ClusterType
{
get;
set;
}
/// <summary>
/// ClusterVersion
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clusterversion
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ClusterVersion
{
get;
set;
}
/// <summary>
/// DBName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-dbname
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic DBName
{
get;
set;
}
/// <summary>
/// ElasticIp
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-elasticip
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic ElasticIp
{
get;
set;
}
/// <summary>
/// Encrypted
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-encrypted
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Encrypted
{
get;
set;
}
/// <summary>
/// HsmClientCertificateIdentifier
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-hsmclientcertidentifier
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HsmClientCertificateIdentifier
{
get;
set;
}
/// <summary>
/// HsmConfigurationIdentifier
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-HsmConfigurationIdentifier
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HsmConfigurationIdentifier
{
get;
set;
}
/// <summary>
/// IamRoles
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-iamroles
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic IamRoles
{
get;
set;
}
/// <summary>
/// KmsKeyId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-kmskeyid
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic KmsKeyId
{
get;
set;
}
/// <summary>
/// LoggingProperties
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-loggingproperties
/// Required: False
/// UpdateType: Mutable
/// Type: LoggingProperties
/// </summary>
public LoggingProperties LoggingProperties
{
get;
set;
}
/// <summary>
/// MasterUserPassword
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-masteruserpassword
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MasterUserPassword
{
get;
set;
}
/// <summary>
/// MasterUsername
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-masterusername
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic MasterUsername
{
get;
set;
}
/// <summary>
/// NodeType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-nodetype
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic NodeType
{
get;
set;
}
/// <summary>
/// NumberOfNodes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-nodetype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic NumberOfNodes
{
get;
set;
}
/// <summary>
/// OwnerAccount
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-owneraccount
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic OwnerAccount
{
get;
set;
}
/// <summary>
/// Port
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-port
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Port
{
get;
set;
}
/// <summary>
/// PreferredMaintenanceWindow
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-preferredmaintenancewindow
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PreferredMaintenanceWindow
{
get;
set;
}
/// <summary>
/// PubliclyAccessible
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-publiclyaccessible
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic PubliclyAccessible
{
get;
set;
}
/// <summary>
/// SnapshotClusterIdentifier
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-snapshotclusteridentifier
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic SnapshotClusterIdentifier
{
get;
set;
}
/// <summary>
/// SnapshotIdentifier
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-snapshotidentifier
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic SnapshotIdentifier
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-tags
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: Tag
/// </summary>
public List<Tag> Tags
{
get;
set;
}
/// <summary>
/// VpcSecurityGroupIds
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-vpcsecuritygroupids
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic VpcSecurityGroupIds
{
get;
set;
}
}
namespace ClusterTypes
{
public class LoggingProperties
{
/// <summary>
/// BucketName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-redshift-cluster-loggingproperties.html#cfn-redshift-cluster-loggingproperties-bucketname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic BucketName
{
get;
set;
}
/// <summary>
/// S3KeyPrefix
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-redshift-cluster-loggingproperties.html#cfn-redshift-cluster-loggingproperties-s3keyprefix
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic S3KeyPrefix
{
get;
set;
}
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Utilities
// File : BuildProcess.AdditionalContent.cs
// Author : Eric Woodruff ([email protected])
// Updated : 06/30/2010
// Note : Copyright 2006-2010, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains the code used to merge the additional content into the
// working folder and build the table of contents entries for it.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.3.0.0 08/07/2006 EFW Created the code
// 1.3.3.1 12/08/2006 EFW Added support for colorizing <pre> tags in
// additional content files.
// 1.3.3.2 12/20/2006 EFW Added support for project property and shared
// content substitution.
// 1.4.0.0 02/23/2007 EFW Added support for Exclude content items and
// support for <code source="file"/> tags.
// 1.4.0.2 06/12/2007 EFW Added support for nested code blocks.
// 1.5.0.0 06/19/2007 EFW Various additions and updates for the June CTP
// 1.5.0.2 07/03/2007 EFW Added support for content site map file
// 1.5.2.0 09/13/2007 EFW Added support for calling plug-ins
// 1.6.0.0 09/28/2007 EFW Added support for transforming *.topic files
// 1.6.0.1 10/29/2007 EFW Link resolution now works on any tag with a cref
// attribute in it.
// 1.6.0.7 04/12/2007 EFW Added support for a split table of contents
// 1.8.0.0 07/26/2008 EFW Modified to support the new project format
// 1.8.0.1 01/21/2009 EFW Added support for removeRegionMarkers option on
// imported code blocks.
// 1.9.0.0 06/06/2010 EFW Added support for multi-format build output
// 1.9.0.0 06/30/2010 EFW Removed splitting of TOC collection
//=============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using ColorizerLibrary;
using SandcastleBuilder.Utils.ConceptualContent;
using SandcastleBuilder.Utils.PlugIn;
namespace SandcastleBuilder.Utils.BuildEngine
{
partial class BuildProcess
{
#region Private data members
//=====================================================================
// The table of contents entries for the additional and conceptual content
private TocEntryCollection toc;
// Regular expressions used to match table of contents options and to
// resolve namespace references in additional content files.
private static Regex reTocExclude = new Regex(
@"<!--\s*@TOCExclude\s*-->", RegexOptions.IgnoreCase);
internal static Regex reIsDefaultTopic = new Regex(
@"<!--\s*@DefaultTopic\s*-->", RegexOptions.IgnoreCase);
internal static Regex reSplitToc = new Regex(
@"<!--\s*@SplitTOC\s*-->", RegexOptions.IgnoreCase);
internal static Regex reSortOrder = new Regex(@"<!--\s*@SortOrder\s*" +
@"(?<SortOrder>\d{1,5})\s*-->",
RegexOptions.IgnoreCase);
private static Regex rePageTitle = new Regex(
@"<title>(?<Title>.*)</title>", RegexOptions.IgnoreCase |
RegexOptions.Singleline);
private static Regex reResolveLinks = new Regex(
"(<\\s*(?<Tag>\\w*)(?<PreAttrs>\\s+[^>]*)cref\\s*=" +
"\\s*\"(?<Link>.+?)\"(?<PostAttrs>.*?))(/>|(>(?<Content>.*?)" +
"<\\s*/(\\k<Tag>)\\s*>))", RegexOptions.IgnoreCase |
RegexOptions.Singleline);
private static Regex reColorizeCheck = new Regex(
@"<pre\s+[^>]*?lang(uage)?\s*=", RegexOptions.IgnoreCase |
RegexOptions.Singleline);
private static Regex reProjectTags = new Regex(
@"<\s*@(?<Field>\w*?)(:(?<Format>.*?))?\s*/?>");
private static Regex reSharedContent = new Regex(
"<\\s*include\\s*item\\s*=\\s*\"(?<Item>.*?)\"\\s*/\\s*>",
RegexOptions.IgnoreCase);
private static Regex reCodeBlock = new Regex(
"<code([^>]+?)source\\s*=\\s*\"(.*?)\"(.*?)(/>|>\\s*?</code>)",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static Regex reCodeRegion = new Regex(
"region\\s*=\\s*\"(.*?)\"", RegexOptions.IgnoreCase |
RegexOptions.Singleline);
private static Regex reIsNested = new Regex("nested\\s*=\\s*(\"|')true",
RegexOptions.IgnoreCase);
private static Regex reWillRemoveMarkers = new Regex(
"removeRegionMarkers\\s*=\\s*(\"|')true", RegexOptions.IgnoreCase);
private static Regex reRemoveRegionMarkers = new Regex(
@"^.*?#(pragma\s+)?(region|end\s?region).*?$",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
private static Regex reSpanScript = new Regex(
"<(span|script)([^>]*?)(/>)", RegexOptions.IgnoreCase);
// NOTE: This same expression is used in the CodeBlockComponent.
// See it for details on what it is and what it does.
private static Regex reMatchRegion = new Regex(
@"\#(pragma\s+)?region\s+(.*?(((?<Open>\#(pragma\s+)?region\s+).*?)+" +
@"((?<Close-Open>\#(pragma\s+)?end\s?region).*?)+)*(?(Open)(?!)))" +
@"\#(pragma\s+)?end\s?region", RegexOptions.IgnoreCase |
RegexOptions.Singleline);
private MatchEvaluator linkMatchEval, contentMatchEval,
codeBlockMatchEval;
// The XML documents used to resolve shared content
private XPathNavigator sharedContent, sharedBuilderContent, styleContent;
private string pathToRoot; // Path to root for resolved links
private CodeColorizer codeColorizer; // The code colorizer
// XSL transformation variables
private string xslStylesheet;
private XslCompiledTransform xslTransform;
private XsltArgumentList xslArguments;
#endregion
/// <summary>
/// This is called to copy the additional content files and build a
/// list of them for the help file project.
/// </summary>
/// <remarks>Note that for wilcard content items, the folders are
/// copied recursively.</remarks>
protected void CopyAdditionalContent()
{
Dictionary<string, TocEntryCollection> tocItems =
new Dictionary<string, TocEntryCollection>();
TocEntryCollection parentToc;
TocEntry tocEntry, tocFolder;
FileItemCollection contentItems;
string projectPath, source, filename, dirName;
string[] parts;
int part;
this.ReportProgress(BuildStep.CopyAdditionalContent, "Copying additional content files...");
if(this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
return;
// A plug-in might add or remove additional content so call
// them before checking to see if there is anything to copy.
this.ExecutePlugIns(ExecutionBehaviors.Before);
if(!project.HasItems(BuildAction.Content) && !project.HasItems(BuildAction.SiteMap))
{
this.ReportProgress("No additional content to copy");
this.ExecutePlugIns(ExecutionBehaviors.After);
return;
}
toc = new TocEntryCollection();
tocItems.Add(String.Empty, toc);
// Now copy the content files
contentItems = new FileItemCollection(project, BuildAction.Content);
projectPath = FolderPath.TerminatePath(Path.GetDirectoryName(originalProjectName));
foreach(FileItem fileItem in contentItems)
{
source = fileItem.Include;
dirName = Path.GetDirectoryName(fileItem.Link.ToString().Substring(projectPath.Length));
filename = Path.Combine(dirName, Path.GetFileName(source));
if(source.EndsWith(".htm", StringComparison.OrdinalIgnoreCase) ||
source.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ||
source.EndsWith(".topic", StringComparison.OrdinalIgnoreCase))
{
tocEntry = BuildProcess.GetTocInfo(source);
// Exclude the page if so indicated via the item metadata
if(fileItem.ExcludeFromToc)
tocEntry.IncludePage = false;
// .topic files get transformed into .html files
if(source.EndsWith(".topic", StringComparison.OrdinalIgnoreCase))
filename = Path.ChangeExtension(filename, ".html");
tocEntry.SourceFile = new FilePath(source, project);
tocEntry.DestinationFile = filename;
// Figure out where to add the entry
parts = tocEntry.DestinationFile.Split('\\');
pathToRoot = String.Empty;
parentToc = toc;
for(part = 0; part < parts.Length - 1; part++)
{
pathToRoot += parts[part] + @"\";
// Create place holders if necessary
if(!tocItems.TryGetValue(pathToRoot, out parentToc))
{
tocFolder = new TocEntry(project);
tocFolder.Title = parts[part];
if(part == 0)
toc.Add(tocFolder);
else
tocItems[String.Join(@"\", parts, 0, part) + @"\"].Add(tocFolder);
parentToc = tocFolder.Children;
tocItems.Add(pathToRoot, parentToc);
}
}
parentToc.Add(tocEntry);
if(tocEntry.IncludePage && tocEntry.IsDefaultTopic)
defaultTopic = tocEntry.DestinationFile;
}
else
tocEntry = null;
this.EnsureOutputFoldersExist(dirName);
foreach(string baseFolder in this.HelpFormatOutputFolders)
{
// If the file contains items that need to be resolved,
// it is handled separately.
if(tocEntry != null &&
(tocEntry.HasLinks || tocEntry.HasCodeBlocks ||
tocEntry.NeedsColorizing || tocEntry.HasProjectTags ||
source.EndsWith(".topic", StringComparison.OrdinalIgnoreCase)))
{
// Figure out the path to the root if needed
parts = tocEntry.DestinationFile.Split('\\');
pathToRoot = String.Empty;
for(part = 0; part < parts.Length - 1; part++)
pathToRoot += "../";
this.ResolveLinksAndCopy(source, baseFolder + filename, tocEntry);
}
else
{
this.ReportProgress("{0} -> {1}{2}", source, baseFolder, filename);
// All attributes are turned off so that we can delete it later
File.Copy(source, baseFolder + filename, true);
File.SetAttributes(baseFolder + filename, FileAttributes.Normal);
}
}
}
// Remove excluded nodes, merge folder item info into the root
// nodes, and sort the items. If a site map isn't defined, this
// will define the layout of the items.
toc.RemoveExcludedNodes(null);
toc.Sort();
codeColorizer = null;
sharedContent = sharedBuilderContent = styleContent = null;
this.ExecutePlugIns(ExecutionBehaviors.After);
}
/// <summary>
/// This is used to merge the conceptual content table of contents with
/// any additional content table of contents information.
/// </summary>
/// <remarks>This will also split the table of contents if any entry
/// has the "split" option. A split in the conceptual content will
/// take precedence as additional content is always appended to
/// the end of the conceptual content. Likewise, a default topic in
/// the conceptual content will take precedence over a default topic
/// in the additional content.</remarks>
private void MergeConceptualAndAdditionalContentTocInfo()
{
FileItemCollection siteMapFiles;
List<ITableOfContents> tocFiles;
TocEntryCollection siteMap, mergedToc;
TocEntry tocEntry;
this.ReportProgress(BuildStep.MergeTablesOfContents,
"Merging conceptual and additional tables of contents...");
if(this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
return;
this.ExecutePlugIns(ExecutionBehaviors.Before);
// Add the conceptual content layout files
tocFiles = new List<ITableOfContents>();
foreach(TopicCollection topics in conceptualContent.Topics)
tocFiles.Add(topics);
// Load all site maps and add them to the list
siteMapFiles = new FileItemCollection(project, BuildAction.SiteMap);
foreach(FileItem fileItem in siteMapFiles)
{
this.ReportProgress(" Loading site map '{0}'", fileItem.FullPath);
siteMap = new TocEntryCollection(fileItem);
siteMap.Load();
// Merge destination file information into the site map
foreach(TocEntry site in siteMap)
this.MergeTocInfo(site);
tocFiles.Add(siteMap);
}
// Sort the files
tocFiles.Sort((x, y) =>
{
FileItem fx = x.ContentLayoutFile, fy = y.ContentLayoutFile;
if(fx.SortOrder < fy.SortOrder)
return -1;
if(fx.SortOrder > fy.SortOrder)
return 1;
return String.Compare(fx.Name, fy.Name, StringComparison.OrdinalIgnoreCase);
});
// Create the merged TOC
mergedToc = new TocEntryCollection();
foreach(ITableOfContents file in tocFiles)
file.GenerateTableOfContents(mergedToc, project);
// If there were no site maps, add items copied from the project.
// Empty container nodes are ignored.
if(siteMapFiles.Count == 0 && toc != null && toc.Count != 0)
foreach(TocEntry t in toc)
if(t.DestinationFile != null || t.Children.Count != 0)
mergedToc.Add(t);
toc = mergedToc;
if(toc.Count != 0)
{
// Look for the default topic
tocEntry = toc.FindDefaultTopic();
if(tocEntry != null)
defaultTopic = tocEntry.DestinationFile;
}
this.ExecutePlugIns(ExecutionBehaviors.After);
}
/// <summary>
/// This is used to merge destination file information into the site
/// map TOC.
/// </summary>
/// <param name="site">The site entry to update</param>
/// <remarks>In addition, files in the site map that do not exist in
/// the TOC built from the defined content will be processed and
/// copied to the root folder.</remarks>
private void MergeTocInfo(TocEntry site)
{
TocEntry match;
string source, filename;
if(site.SourceFile.Path.Length != 0)
{
match = toc.Find(site.SourceFile);
if(match != null)
site.DestinationFile = match.DestinationFile;
else
{
source = site.SourceFile;
site.DestinationFile = Path.GetFileName(source);
filename = site.DestinationFile;
// .topic files get transformed into .html files
if(source.EndsWith(".topic", StringComparison.OrdinalIgnoreCase))
site.DestinationFile = Path.ChangeExtension(site.DestinationFile, ".html");
// Check to see if anything needs resolving
if(source.EndsWith(".htm", StringComparison.OrdinalIgnoreCase) ||
source.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ||
source.EndsWith(".topic", StringComparison.OrdinalIgnoreCase))
match = BuildProcess.GetTocInfo(source);
foreach(string baseFolder in this.HelpFormatOutputFolders)
{
// If the file contains items that need to be resolved, it is handled separately
if(match != null && (match.HasLinks || match.HasCodeBlocks ||
match.NeedsColorizing || match.HasProjectTags ||
source.EndsWith(".topic", StringComparison.OrdinalIgnoreCase)))
{
// Files are always copied to the root
pathToRoot = String.Empty;
this.ResolveLinksAndCopy(source, baseFolder + filename, match);
}
else
{
this.ReportProgress("{0} -> {1}{2}", source, baseFolder, filename);
// All attributes are turned off so that we can delete it later
File.Copy(source, baseFolder + filename, true);
File.SetAttributes(baseFolder + filename, FileAttributes.Normal);
}
}
}
}
if(site.Children.Count != 0)
foreach(TocEntry entry in site.Children)
this.MergeTocInfo(entry);
}
/// <summary>
/// This is used to extract table of contents information from a file
/// that will appear in the help file's table of contents.
/// </summary>
/// <param name="filename">The file from which to extract the
/// information</param>
/// <returns>The table of contents entry</returns>
internal static TocEntry GetTocInfo(string filename)
{
TocEntry tocEntry;
Encoding enc = Encoding.Default;
string content;
content = BuildProcess.ReadWithEncoding(filename, ref enc);
tocEntry = new TocEntry(null);
tocEntry.IncludePage = !reTocExclude.IsMatch(content);
tocEntry.IsDefaultTopic = reIsDefaultTopic.IsMatch(content);
if(reSplitToc.IsMatch(content))
tocEntry.ApiParentMode = ApiParentMode.InsertAfter;
Match m = reSortOrder.Match(content);
if(m.Success)
tocEntry.SortOrder = Convert.ToInt32(m.Groups["SortOrder"].Value, CultureInfo.InvariantCulture);
// Get the page title if possible. If not found, use the filename
// without the path or extension as the page title.
m = rePageTitle.Match(content);
if(!m.Success)
tocEntry.Title = Path.GetFileNameWithoutExtension(filename);
else
tocEntry.Title = HttpUtility.HtmlDecode(m.Groups["Title"].Value).Replace(
"\r", String.Empty).Replace("\n", String.Empty);
// Since we've got the file loaded, see if there are links
// that need to be resolved when the file is copied, if it
// contains <pre> blocks that should be colorized, or if it
// contains tags or shared content items that need replacing.
tocEntry.HasLinks = reResolveLinks.IsMatch(content);
tocEntry.HasCodeBlocks = reCodeBlock.IsMatch(content);
tocEntry.NeedsColorizing = reColorizeCheck.IsMatch(content);
tocEntry.HasProjectTags = (reProjectTags.IsMatch(content) || reSharedContent.IsMatch(content));
return tocEntry;
}
/// <summary>
/// This is called to load an additional content file, resolve links
/// to namespace content and copy it to the output folder.
/// </summary>
/// <param name="sourceFile">The source filename to copy</param>
/// <param name="destFile">The destination filename</param>
/// <param name="entry">The entry being resolved.</param>
internal void ResolveLinksAndCopy(string sourceFile, string destFile,
TocEntry entry)
{
Encoding enc = Encoding.Default;
string content, script, syntaxFile;
int pos;
// For topics, change the extenstion back to ".topic". It's
// ".html" in the TOC as that's what it ends up as after
// transformation.
if(sourceFile.EndsWith(".topic", StringComparison.OrdinalIgnoreCase))
destFile = Path.ChangeExtension(destFile, ".topic");
this.ReportProgress("{0} -> {1}", sourceFile, destFile);
// When reading the file, use the default encoding but detect the
// encoding if byte order marks are present.
content = BuildProcess.ReadWithEncoding(sourceFile, ref enc);
// Expand <code> tags if necessary
if(entry.HasCodeBlocks)
content = reCodeBlock.Replace(content, codeBlockMatchEval);
// Colorize <pre> tags if necessary
if(entry.NeedsColorizing || entry.HasCodeBlocks)
{
// Initialize code colorizer on first use
if(codeColorizer == null)
codeColorizer = new CodeColorizer(shfbFolder + @"Colorizer\highlight.xml",
shfbFolder + @"Colorizer\highlight.xsl");
// Set the path the "Copy" image
codeColorizer.CopyImageUrl = pathToRoot + "icons/CopyCode.gif";
// Colorize it and replace the "Copy" literal text with the
// shared content include item so that it gets localized.
content = codeColorizer.ProcessAndHighlightText(content);
content = content.Replace(codeColorizer.CopyText + "</span",
"<include item=\"copyCode\"/></span");
entry.HasProjectTags = true;
// Add the links to the colorizer stylesheet and script files
// unless it's going to be transformed. In which case, the
// links should be in the XSL stylesheet.
if(!sourceFile.EndsWith(".topic", StringComparison.OrdinalIgnoreCase) &&
!sourceFile.EndsWith(".xsl", StringComparison.OrdinalIgnoreCase))
{
script = String.Format(CultureInfo.InvariantCulture,
"<link type='text/css' rel='stylesheet' href='{0}styles/highlight.css' />" +
"<script type='text/javascript' src='{0}scripts/highlight.js'></script>", pathToRoot);
pos = content.IndexOf("</head>", StringComparison.Ordinal);
// Create a <head> section if one doesn't exist
if(pos == -1)
{
script = "<head>" + script + "</head>";
pos = content.IndexOf("<html>", StringComparison.Ordinal);
if(pos != -1)
pos += 6;
else
pos = 0;
}
content = content.Insert(pos, script);
}
// Copy the colorizer files if not already there
this.EnsureOutputFoldersExist("icons");
this.EnsureOutputFoldersExist("styles");
this.EnsureOutputFoldersExist("scripts");
foreach(string baseFolder in this.HelpFormatOutputFolders)
if(!File.Exists(baseFolder + @"styles\highlight.css"))
{
syntaxFile = baseFolder + @"styles\highlight.css";
File.Copy(shfbFolder + @"Colorizer\highlight.css", syntaxFile);
File.SetAttributes(syntaxFile, FileAttributes.Normal);
syntaxFile = baseFolder + @"scripts\highlight.js";
File.Copy(shfbFolder + @"Colorizer\highlight.js", syntaxFile);
File.SetAttributes(syntaxFile, FileAttributes.Normal);
// Always copy the image files, they may be different. Also, delete the
// destination file first if it exists as the filename casing may be different.
syntaxFile = baseFolder + @"icons\CopyCode.gif";
if(File.Exists(syntaxFile))
{
File.SetAttributes(syntaxFile, FileAttributes.Normal);
File.Delete(syntaxFile);
}
File.Copy(shfbFolder + @"Colorizer\CopyCode.gif", syntaxFile);
File.SetAttributes(syntaxFile, FileAttributes.Normal);
syntaxFile = baseFolder + @"icons\CopyCode_h.gif";
if(File.Exists(syntaxFile))
{
File.SetAttributes(syntaxFile, FileAttributes.Normal);
File.Delete(syntaxFile);
}
File.Copy(shfbFolder + @"Colorizer\CopyCode_h.gif", syntaxFile);
File.SetAttributes(syntaxFile, FileAttributes.Normal);
}
}
// Use a regular expression to find and replace all tags with
// cref attributes with a link to the help file content. This
// needs to happen after the code block processing as they
// may contain <see> tags that need to be resolved.
if(entry.HasLinks || entry.HasCodeBlocks)
content = reResolveLinks.Replace(content, linkMatchEval);
// Replace project option tags with project option values
if(entry.HasProjectTags)
{
// Project tags can be nested
while(reProjectTags.IsMatch(content))
content = reProjectTags.Replace(content, fieldMatchEval);
// Shared content items can be nested
while(reSharedContent.IsMatch(content))
content = reSharedContent.Replace(content, contentMatchEval);
}
// Write the file back out with the appropriate encoding
using(StreamWriter sw = new StreamWriter(destFile, false, enc))
{
sw.Write(content);
}
// Transform .topic files into .html files
if(sourceFile.EndsWith(".topic", StringComparison.OrdinalIgnoreCase))
this.XslTransform(destFile);
}
/// <summary>
/// Replace a link to a namespace item with a link to the HTML page
/// for it.
/// </summary>
/// <param name="match">The match that was found</param>
/// <returns>The string to use as the replacement</returns>
private string OnLinkMatch(Match match)
{
XmlNodeList elements;
string tag, preAttrs, link, postAttrs, content, href;
tag = match.Groups["Tag"].Value;
preAttrs = match.Groups["PreAttrs"].Value;
link = match.Groups["Link"].Value;
postAttrs = match.Groups["PostAttrs"].Value;
content = match.Groups["Content"].Value;
// If the tag is "see", change it to an anchor tag ("a")
if(tag == "see")
{
tag = "a";
// Use the link as the content if no text is specified
if(String.IsNullOrEmpty(content))
content = link;
}
// If it looks like we've got a prefix, try for a "starts with"
// match. If not, try for a substring match after the prefix.
// This should give the best results before going more general.
if(link.IndexOf(':') != -1)
elements = apisNode.SelectNodes("api[starts-with(@id,'" +
link + "')]/file");
else
elements = apisNode.SelectNodes(
"api[substring-after(@id,':') = '" + link + "']/file");
// Find all nodes containing the text if the above didn't find
// anything and use the first one found.
if(elements.Count == 0)
elements = apisNode.SelectNodes("api[contains(@id,'" + link +
"')]/file");
// Anything found?
if(elements.Count == 0)
{
this.ReportProgress("\tResolve Links: No matches found " +
"for '{0}'", link);
// If it's an anchor tag, show it as a bold, non-clickable link
if(tag == "a")
return String.Format(CultureInfo.InvariantCulture,
"<b>{0}</b>", content);
// All other tags will use a dummy href value
href = "#";
}
else
{
// If one match is found, use it as the href value
if(elements.Count == 1)
this.ReportProgress("\tResolve Links: Matched '{0}' to '{1}'",
link, elements[0].ParentNode.Attributes["id"].Value);
else
{
// If multiple matches are found, issue a warning, dump all
// matches, and then use first match as the href value.
this.ReportProgress("\tResolve Links: Multiple matches " +
"found for '{0}':", link);
foreach(XmlNode n in elements)
this.ReportProgress("\t\t{0}",
n.ParentNode.Attributes["id"].Value);
this.ReportProgress("\t\tUsing '{0}' for link",
elements[0].ParentNode.Attributes["id"].Value);
}
href = String.Format(CultureInfo.InvariantCulture,
"{0}html/{1}.htm", pathToRoot,
elements[0].Attributes["name"].Value);
}
if(!String.IsNullOrEmpty(content))
return String.Format(CultureInfo.InvariantCulture,
"<{0} {1} href=\"{2}\" {3}>{4}</{0}>", tag, preAttrs, href,
postAttrs, content);
return String.Format(CultureInfo.InvariantCulture,
"<{0} {1} href=\"{2}\" {3}/>", tag, preAttrs, href, postAttrs);
}
/// <summary>
/// Replace a shared content item with it's value. Note that these
/// may be nested.
/// </summary>
/// <param name="match">The match that was found</param>
/// <returns>The string to use as the replacement</returns>
private string OnContentMatch(Match match)
{
XPathDocument contentFile;
XPathNavigator item;
string content = String.Empty;
// Load the shared content files on first use
if(sharedContent == null)
{
contentFile = new XPathDocument(presentationFolder +
@"content\shared_content.xml");
sharedContent = contentFile.CreateNavigator();
contentFile = new XPathDocument(workingFolder +
"SharedBuilderContent.xml");
sharedBuilderContent = contentFile.CreateNavigator();
contentFile = new XPathDocument(workingFolder +
"PresentationStyleBuilderContent.xml");
styleContent = contentFile.CreateNavigator();
}
// Give preference to the help file builder's shared content files
item = sharedBuilderContent.SelectSingleNode("content/item[@id='" +
match.Groups["Item"] + "']");
if(item == null)
item = styleContent.SelectSingleNode("content/item[@id='" +
match.Groups["Item"] + "']");
if(item == null)
item = sharedContent.SelectSingleNode("content/item[@id='" +
match.Groups["Item"] + "']");
if(item != null)
content = item.InnerXml;
return content;
}
/// <summary>
/// This is used to load a code block from an external file.
/// </summary>
/// <returns>The HTML encoded block extracted from the file and
/// wrapped in a <pre> tag ready for colorizing.</returns>
/// <remarks>If a region attribute is found, only the named region
/// is returned. If n region attribute is found, the whole file is
/// returned. Relative paths are assumed to be relative to the
/// project folder.</remarks>
private string OnCodeBlockMatch(Match match)
{
Regex reFindRegion;
Match find, m;
string sourceFile = null, region = null, codeBlock = null,
options = match.Groups[1].Value + match.Groups[3].Value;
sourceFile = match.Groups[2].Value;
try
{
sourceFile = Environment.ExpandEnvironmentVariables(sourceFile);
if(!Path.IsPathRooted(sourceFile))
sourceFile = Path.GetFullPath(projectFolder + sourceFile);
using(StreamReader sr = new StreamReader(sourceFile))
{
codeBlock = sr.ReadToEnd();
}
}
catch(ArgumentException argEx)
{
throw new BuilderException("BE0013", String.Format(
CultureInfo.InvariantCulture, "Possible invalid path " +
"'{0}{1}'.", projectFolder, sourceFile), argEx);
}
catch(IOException ioEx)
{
throw new BuilderException("BE0014", String.Format(
CultureInfo.InvariantCulture, "Unable to load source " +
"file '{0}'.", sourceFile), ioEx);
}
// If no region is specified, the whole file is included
m = reCodeRegion.Match(options);
if(m.Success)
{
region = m.Groups[1].Value;
options = options.Remove(m.Index, m.Length);
// Find the start of the region. This gives us an immediate
// starting match on the second search and we can look for the
// matching #endregion without caring about the region name.
// Otherwise, nested regions get in the way and complicate
// things.
reFindRegion = new Regex("\\#(pragma\\s+)?region\\s+\"?" +
Regex.Escape(region), RegexOptions.IgnoreCase);
find = reFindRegion.Match(codeBlock);
if(!find.Success)
throw new BuilderException("BE0015", String.Format(
CultureInfo.InvariantCulture, "Unable to locate " +
"start of region '{0}' in source file '{1}'", region,
sourceFile));
// Find the end of the region taking into account any
// nested regions.
m = reMatchRegion.Match(codeBlock, find.Index);
if(!m.Success)
throw new BuilderException("BE0016", String.Format(
CultureInfo.InvariantCulture, "Unable to extract " +
"region '{0}' in source file '{1}{2}' (missing " +
"#endregion?)", region, projectFolder, sourceFile));
// Extract just the specified region starting after the
// description.
codeBlock = m.Groups[2].Value.Substring(
m.Groups[2].Value.IndexOf('\n') + 1);
// Strip off the trailing comment characters if present
if(codeBlock[codeBlock.Length - 1] == ' ')
codeBlock = codeBlock.TrimEnd();
// VB commented #End Region statement within a method body
if(codeBlock[codeBlock.Length - 1] == '\'')
codeBlock = codeBlock.Substring(0, codeBlock.Length - 1);
// XML/XAML commented #endregion statement
if(codeBlock.EndsWith("<!--", StringComparison.Ordinal))
codeBlock = codeBlock.Substring(0, codeBlock.Length - 4);
// C or SQL style commented #endregion statement
if(codeBlock.EndsWith("/*", StringComparison.Ordinal) ||
codeBlock.EndsWith("--", StringComparison.Ordinal))
codeBlock = codeBlock.Substring(0, codeBlock.Length - 2);
}
// Remove nested region markers?
if(reWillRemoveMarkers.IsMatch(options))
{
codeBlock = reRemoveRegionMarkers.Replace(codeBlock, String.Empty);
codeBlock = codeBlock.Replace("\r\n\n", "\r\n");
}
// If nested, don't wrap it in a <pre> tag
if(reIsNested.IsMatch(options))
return codeBlock;
// Return the HTML encoded block
return "<pre xml:space=\"preserve\" " + options + ">" + HttpUtility.HtmlEncode(
codeBlock) + "</pre>";
}
/// <summary>
/// This is used to transform a *.topic file into a *.html file using
/// an XSLT transformation based on the presentation style.
/// </summary>
/// <param name="sourceFile">The source topic filename</param>
private void XslTransform(string sourceFile)
{
TocEntry tocInfo;
XmlReader reader = null;
XmlWriter writer = null;
XsltSettings settings;
XmlReaderSettings readerSettings;
XmlWriterSettings writerSettings;
Encoding enc = Encoding.Default;
FileItemCollection transforms;
string content;
string sourceStylesheet, destFile = Path.ChangeExtension(sourceFile, ".html");
try
{
readerSettings = new XmlReaderSettings();
readerSettings.ProhibitDtd = false;
readerSettings.CloseInput = true;
// Create the transform on first use
if(xslTransform == null)
{
transforms = new FileItemCollection(project, BuildAction.TopicTransform);
if(transforms.Count != 0)
{
if(transforms.Count > 1)
this.ReportWarning("BE0011", "Multiple topic " +
"transformations found. Using '{0}'",
transforms[0].FullPath);
sourceStylesheet = transforms[0].FullPath;
}
else
sourceStylesheet = templateFolder + presentationParam + ".xsl";
xslStylesheet = workingFolder + Path.GetFileName(sourceStylesheet);
tocInfo = BuildProcess.GetTocInfo(sourceStylesheet);
// The stylesheet may contain shared content items so we
// must resolve it this way rather than using
// TransformTemplate.
this.ResolveLinksAndCopy(sourceStylesheet, xslStylesheet, tocInfo);
xslTransform = new XslCompiledTransform();
settings = new XsltSettings(true, true);
xslArguments = new XsltArgumentList();
xslTransform.Load(XmlReader.Create(xslStylesheet,
readerSettings), settings, new XmlUrlResolver());
}
this.ReportProgress("Applying XSL transformation '{0}' to '{1}'.", xslStylesheet, sourceFile);
reader = XmlReader.Create(sourceFile, readerSettings);
writerSettings = xslTransform.OutputSettings.Clone();
writerSettings.CloseOutput = true;
writerSettings.Indent = false;
writer = XmlWriter.Create(destFile, writerSettings);
xslArguments.Clear();
xslArguments.AddParam("pathToRoot", String.Empty, pathToRoot);
xslTransform.Transform(reader, xslArguments, writer);
}
catch(Exception ex)
{
throw new BuilderException("BE0017", String.Format(
CultureInfo.InvariantCulture, "Unexpected error " +
"using '{0}' to transform additional content file '{1}' " +
"to '{2}'. The error is: {3}\r\n{4}", xslStylesheet,
sourceFile, destFile, ex.Message,
(ex.InnerException == null) ? String.Empty :
ex.InnerException.Message));
}
finally
{
if(reader != null)
reader.Close();
if(writer != null)
{
writer.Flush();
writer.Close();
}
}
// The source topic file is deleted as the transformed file
// takes its place.
File.Delete(sourceFile);
// <span> and <script> tags cannot be self-closing if empty.
// The template may contain them correctly but when written out
// as XML, they get converted to self-closing tags which breaks
// them. To fix them, convert them to full start and close tags.
content = BuildProcess.ReadWithEncoding(destFile, ref enc);
content = reSpanScript.Replace(content, "<$1$2></$1>");
// An XSL transform might have added tags and include items that
// need replacing so run it through those options if needed.
tocInfo = BuildProcess.GetTocInfo(destFile);
// Expand <code> tags if necessary
if(tocInfo.HasCodeBlocks)
content = reCodeBlock.Replace(content, codeBlockMatchEval);
// Colorize <pre> tags if necessary
if(tocInfo.NeedsColorizing || tocInfo.HasCodeBlocks)
{
// Initialize code colorizer on first use
if(codeColorizer == null)
codeColorizer = new CodeColorizer(shfbFolder + @"Colorizer\highlight.xml",
shfbFolder + @"Colorizer\highlight.xsl");
// Set the path the "Copy" image
codeColorizer.CopyImageUrl = pathToRoot + "icons/CopyCode.gif";
// Colorize it and replace the "Copy" literal text with the
// shared content include item so that it gets localized.
content = codeColorizer.ProcessAndHighlightText(content);
content = content.Replace(codeColorizer.CopyText + "</span",
"<include item=\"copyCode\"/></span");
tocInfo.HasProjectTags = true;
}
// Use a regular expression to find and replace all tags with
// cref attributes with a link to the help file content. This
// needs to happen after the code block processing as they
// may contain <see> tags that need to be resolved.
if(tocInfo.HasLinks || tocInfo.HasCodeBlocks)
content = reResolveLinks.Replace(content, linkMatchEval);
// Replace project option tags with project option values
if(tocInfo.HasProjectTags)
{
// Project tags can be nested
while(reProjectTags.IsMatch(content))
content = reProjectTags.Replace(content, fieldMatchEval);
// Shared content items can be nested
while(reSharedContent.IsMatch(content))
content = reSharedContent.Replace(content, contentMatchEval);
}
// Write the file back out with the appropriate encoding
using(StreamWriter sw = new StreamWriter(destFile, false, enc))
{
sw.Write(content);
}
}
}
}
| |
using System;
using System.Collections.Generic;
/// <summary>
/// CopyTo(T[],System.Int32)
/// </summary>
public class QueueCopyTo
{
public static int Main()
{
QueueCopyTo test = new QueueCopyTo();
TestLibrary.TestFramework.BeginTestCase("QueueCopyTo");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Test whether CopyTo(T[],System.Int32) is successful when System.Int32 is zero.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "third", "fourth" };
TestQueue.CopyTo(TestArray, 0);
if (TestArray[0] != "one" || TestArray[1] != "two" || TestArray[2] != "third"
|| TestArray[3] != "fourth" || TestArray.GetLength(0) != 4)
{
TestLibrary.TestFramework.LogError("P01.1", "CopyTo(T[],System.Int32) failed when System.Int32 is zero!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Test whether CopyTo(T[],System.Int32) is successful when System.Int32 is greater than zero.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, 1);
if (TestArray.GetLength(0) != 4 || TestArray[0] != "first" || TestArray[1] != "one" || TestArray[2] != "two")
{
TestLibrary.TestFramework.LogError("P02.1", "CopyTo(T[],System.Int32) failed when System.Int32 is greater than zero!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException should be thrown when array is a null reference.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = null;
TestQueue.CopyTo(TestArray, 0);
TestLibrary.TestFramework.LogError("N01.1", "ArgumentNullException is not thrown when array is a null reference!");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N01.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException should be thrown when index is less than zero.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, -1);
TestLibrary.TestFramework.LogError("N02.1", "ArgumentOutOfRangeException is not thrown when index is less than zero!");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N02.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentException should be thrown when index is equal to the length of array.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, 4);
TestLibrary.TestFramework.LogError("N03.1", "ArgumentException is not thrown when index is equal to the length of array!");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N03.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentException should be thrown when index is greater than the length of array.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, 10);
TestLibrary.TestFramework.LogError("N04.1", "ArgumentException is not thrown when index is greater than the length of array!");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N04.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentException should be thrown when the number of elements in the source Queue is greater than the available space from index to the end of the destination array.");
try
{
Queue<string> TestQueue = new Queue<string>();
TestQueue.Enqueue("one");
TestQueue.Enqueue("two");
string[] TestArray = { "first", "second", "", "" };
TestQueue.CopyTo(TestArray, 3);
TestLibrary.TestFramework.LogError("N05.1", "ArgumentException is not thrown when the number of elements in the source Queue is greater than the available space from index to the end of the destination array!");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N05.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogVerbose(e.StackTrace);
retVal = false;
}
return retVal;
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcbsv = Google.Cloud.BigQuery.Storage.V1;
using sys = System;
namespace Google.Cloud.BigQuery.Storage.V1
{
/// <summary>Resource name for the <c>ReadSession</c> resource.</summary>
public sealed partial class ReadSessionName : gax::IResourceName, sys::IEquatable<ReadSessionName>
{
/// <summary>The possible contents of <see cref="ReadSessionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/sessions/{session}</c>.
/// </summary>
ProjectLocationSession = 1,
}
private static gax::PathTemplate s_projectLocationSession = new gax::PathTemplate("projects/{project}/locations/{location}/sessions/{session}");
/// <summary>Creates a <see cref="ReadSessionName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ReadSessionName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ReadSessionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ReadSessionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ReadSessionName"/> with the pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ReadSessionName"/> constructed from the provided ids.</returns>
public static ReadSessionName FromProjectLocationSession(string projectId, string locationId, string sessionId) =>
new ReadSessionName(ResourceNameType.ProjectLocationSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ReadSessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ReadSessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string sessionId) =>
FormatProjectLocationSession(projectId, locationId, sessionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ReadSessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ReadSessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}</c>.
/// </returns>
public static string FormatProjectLocationSession(string projectId, string locationId, string sessionId) =>
s_projectLocationSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>Parses the given resource name string into a new <see cref="ReadSessionName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/sessions/{session}</c></description></item>
/// </list>
/// </remarks>
/// <param name="readSessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ReadSessionName"/> if successful.</returns>
public static ReadSessionName Parse(string readSessionName) => Parse(readSessionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ReadSessionName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/sessions/{session}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="readSessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ReadSessionName"/> if successful.</returns>
public static ReadSessionName Parse(string readSessionName, bool allowUnparsed) =>
TryParse(readSessionName, allowUnparsed, out ReadSessionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ReadSessionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/sessions/{session}</c></description></item>
/// </list>
/// </remarks>
/// <param name="readSessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ReadSessionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string readSessionName, out ReadSessionName result) =>
TryParse(readSessionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ReadSessionName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/sessions/{session}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="readSessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ReadSessionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string readSessionName, bool allowUnparsed, out ReadSessionName result)
{
gax::GaxPreconditions.CheckNotNull(readSessionName, nameof(readSessionName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationSession.TryParseName(readSessionName, out resourceName))
{
result = FromProjectLocationSession(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(readSessionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ReadSessionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string sessionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
SessionId = sessionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ReadSessionName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
public ReadSessionName(string projectId, string locationId, string sessionId) : this(ResourceNameType.ProjectLocationSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Session</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SessionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationSession: return s_projectLocationSession.Expand(ProjectId, LocationId, SessionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ReadSessionName);
/// <inheritdoc/>
public bool Equals(ReadSessionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ReadSessionName a, ReadSessionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ReadSessionName a, ReadSessionName b) => !(a == b);
}
/// <summary>Resource name for the <c>ReadStream</c> resource.</summary>
public sealed partial class ReadStreamName : gax::IResourceName, sys::IEquatable<ReadStreamName>
{
/// <summary>The possible contents of <see cref="ReadStreamName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>.
/// </summary>
ProjectLocationSessionStream = 1,
}
private static gax::PathTemplate s_projectLocationSessionStream = new gax::PathTemplate("projects/{project}/locations/{location}/sessions/{session}/streams/{stream}");
/// <summary>Creates a <see cref="ReadStreamName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ReadStreamName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ReadStreamName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ReadStreamName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ReadStreamName"/> with the pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="streamId">The <c>Stream</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ReadStreamName"/> constructed from the provided ids.</returns>
public static ReadStreamName FromProjectLocationSessionStream(string projectId, string locationId, string sessionId, string streamId) =>
new ReadStreamName(ResourceNameType.ProjectLocationSessionStream, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), streamId: gax::GaxPreconditions.CheckNotNullOrEmpty(streamId, nameof(streamId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ReadStreamName"/> with pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="streamId">The <c>Stream</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ReadStreamName"/> with pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string sessionId, string streamId) =>
FormatProjectLocationSessionStream(projectId, locationId, sessionId, streamId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ReadStreamName"/> with pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="streamId">The <c>Stream</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ReadStreamName"/> with pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>.
/// </returns>
public static string FormatProjectLocationSessionStream(string projectId, string locationId, string sessionId, string streamId) =>
s_projectLocationSessionStream.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(streamId, nameof(streamId)));
/// <summary>Parses the given resource name string into a new <see cref="ReadStreamName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="readStreamName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ReadStreamName"/> if successful.</returns>
public static ReadStreamName Parse(string readStreamName) => Parse(readStreamName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ReadStreamName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="readStreamName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ReadStreamName"/> if successful.</returns>
public static ReadStreamName Parse(string readStreamName, bool allowUnparsed) =>
TryParse(readStreamName, allowUnparsed, out ReadStreamName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ReadStreamName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="readStreamName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ReadStreamName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string readStreamName, out ReadStreamName result) =>
TryParse(readStreamName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ReadStreamName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="readStreamName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ReadStreamName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string readStreamName, bool allowUnparsed, out ReadStreamName result)
{
gax::GaxPreconditions.CheckNotNull(readStreamName, nameof(readStreamName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationSessionStream.TryParseName(readStreamName, out resourceName))
{
result = FromProjectLocationSessionStream(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(readStreamName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ReadStreamName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string sessionId = null, string streamId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
SessionId = sessionId;
StreamId = streamId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ReadStreamName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/sessions/{session}/streams/{stream}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="streamId">The <c>Stream</c> ID. Must not be <c>null</c> or empty.</param>
public ReadStreamName(string projectId, string locationId, string sessionId, string streamId) : this(ResourceNameType.ProjectLocationSessionStream, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), streamId: gax::GaxPreconditions.CheckNotNullOrEmpty(streamId, nameof(streamId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Session</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SessionId { get; }
/// <summary>
/// The <c>Stream</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string StreamId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationSessionStream: return s_projectLocationSessionStream.Expand(ProjectId, LocationId, SessionId, StreamId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ReadStreamName);
/// <inheritdoc/>
public bool Equals(ReadStreamName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ReadStreamName a, ReadStreamName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ReadStreamName a, ReadStreamName b) => !(a == b);
}
/// <summary>Resource name for the <c>WriteStream</c> resource.</summary>
public sealed partial class WriteStreamName : gax::IResourceName, sys::IEquatable<WriteStreamName>
{
/// <summary>The possible contents of <see cref="WriteStreamName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c>
/// .
/// </summary>
ProjectDatasetTableStream = 1,
}
private static gax::PathTemplate s_projectDatasetTableStream = new gax::PathTemplate("projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}");
/// <summary>Creates a <see cref="WriteStreamName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="WriteStreamName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static WriteStreamName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new WriteStreamName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="WriteStreamName"/> with the pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="streamId">The <c>Stream</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="WriteStreamName"/> constructed from the provided ids.</returns>
public static WriteStreamName FromProjectDatasetTableStream(string projectId, string datasetId, string tableId, string streamId) =>
new WriteStreamName(ResourceNameType.ProjectDatasetTableStream, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)), streamId: gax::GaxPreconditions.CheckNotNullOrEmpty(streamId, nameof(streamId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WriteStreamName"/> with pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="streamId">The <c>Stream</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WriteStreamName"/> with pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c>.
/// </returns>
public static string Format(string projectId, string datasetId, string tableId, string streamId) =>
FormatProjectDatasetTableStream(projectId, datasetId, tableId, streamId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WriteStreamName"/> with pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="streamId">The <c>Stream</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WriteStreamName"/> with pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c>.
/// </returns>
public static string FormatProjectDatasetTableStream(string projectId, string datasetId, string tableId, string streamId) =>
s_projectDatasetTableStream.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)), gax::GaxPreconditions.CheckNotNullOrEmpty(streamId, nameof(streamId)));
/// <summary>Parses the given resource name string into a new <see cref="WriteStreamName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="writeStreamName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="WriteStreamName"/> if successful.</returns>
public static WriteStreamName Parse(string writeStreamName) => Parse(writeStreamName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="WriteStreamName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="writeStreamName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="WriteStreamName"/> if successful.</returns>
public static WriteStreamName Parse(string writeStreamName, bool allowUnparsed) =>
TryParse(writeStreamName, allowUnparsed, out WriteStreamName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WriteStreamName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="writeStreamName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WriteStreamName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string writeStreamName, out WriteStreamName result) =>
TryParse(writeStreamName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WriteStreamName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="writeStreamName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WriteStreamName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string writeStreamName, bool allowUnparsed, out WriteStreamName result)
{
gax::GaxPreconditions.CheckNotNull(writeStreamName, nameof(writeStreamName));
gax::TemplatedResourceName resourceName;
if (s_projectDatasetTableStream.TryParseName(writeStreamName, out resourceName))
{
result = FromProjectDatasetTableStream(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(writeStreamName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private WriteStreamName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string datasetId = null, string projectId = null, string streamId = null, string tableId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DatasetId = datasetId;
ProjectId = projectId;
StreamId = streamId;
TableId = tableId;
}
/// <summary>
/// Constructs a new instance of a <see cref="WriteStreamName"/> class from the component parts of pattern
/// <c>projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="streamId">The <c>Stream</c> ID. Must not be <c>null</c> or empty.</param>
public WriteStreamName(string projectId, string datasetId, string tableId, string streamId) : this(ResourceNameType.ProjectDatasetTableStream, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)), streamId: gax::GaxPreconditions.CheckNotNullOrEmpty(streamId, nameof(streamId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Dataset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DatasetId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Stream</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string StreamId { get; }
/// <summary>
/// The <c>Table</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TableId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectDatasetTableStream: return s_projectDatasetTableStream.Expand(ProjectId, DatasetId, TableId, StreamId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as WriteStreamName);
/// <inheritdoc/>
public bool Equals(WriteStreamName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(WriteStreamName a, WriteStreamName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(WriteStreamName a, WriteStreamName b) => !(a == b);
}
public partial class ReadSession
{
/// <summary>
/// <see cref="gcbsv::ReadSessionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbsv::ReadSessionName ReadSessionName
{
get => string.IsNullOrEmpty(Name) ? null : gcbsv::ReadSessionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary><see cref="TableName"/>-typed view over the <see cref="Table"/> resource name property.</summary>
public TableName TableAsTableName
{
get => string.IsNullOrEmpty(Table) ? null : TableName.Parse(Table, allowUnparsed: true);
set => Table = value?.ToString() ?? "";
}
}
public partial class ReadStream
{
/// <summary>
/// <see cref="gcbsv::ReadStreamName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbsv::ReadStreamName ReadStreamName
{
get => string.IsNullOrEmpty(Name) ? null : gcbsv::ReadStreamName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class WriteStream
{
/// <summary>
/// <see cref="gcbsv::WriteStreamName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbsv::WriteStreamName WriteStreamName
{
get => string.IsNullOrEmpty(Name) ? null : gcbsv::WriteStreamName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// Summary description for StyleCtl.
/// </summary>
internal class StyleCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
// flags for controlling whether syntax changed for a particular property
private bool fPadLeft, fPadRight, fPadTop, fPadBottom;
private bool fEndColor, fBackColor, fGradient, fDEName, fDEOutput;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label14;
private Oranikle.Studio.Controls.CustomTextControl tbPadLeft;
private Oranikle.Studio.Controls.CustomTextControl tbPadRight;
private Oranikle.Studio.Controls.CustomTextControl tbPadTop;
private System.Windows.Forms.GroupBox grpBoxPadding;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label3;
private Oranikle.Studio.Controls.StyledButton bBackColor;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label15;
private Oranikle.Studio.Controls.StyledComboBox cbEndColor;
private Oranikle.Studio.Controls.StyledComboBox cbBackColor;
private Oranikle.Studio.Controls.StyledButton bEndColor;
private Oranikle.Studio.Controls.StyledComboBox cbGradient;
private Oranikle.Studio.Controls.CustomTextControl tbPadBottom;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private Oranikle.Studio.Controls.CustomTextControl tbDEName;
private Oranikle.Studio.Controls.StyledComboBox cbDEOutput;
private System.Windows.Forms.GroupBox gbXML;
private Oranikle.Studio.Controls.StyledButton bValueExpr;
private Oranikle.Studio.Controls.StyledButton button1;
private Oranikle.Studio.Controls.StyledButton button2;
private Oranikle.Studio.Controls.StyledButton button3;
private Oranikle.Studio.Controls.StyledButton bGradient;
private Oranikle.Studio.Controls.StyledButton bExprBackColor;
private Oranikle.Studio.Controls.StyledButton bExprEndColor;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal StyleCtl(DesignXmlDraw dxDraw, List<XmlNode> reportItems)
{
_ReportItems = reportItems;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(_ReportItems[0]);
}
private void InitValues(XmlNode node)
{
cbEndColor.Items.AddRange(StaticLists.ColorList);
cbBackColor.Items.AddRange(StaticLists.ColorList);
XmlNode sNode = _Draw.GetNamedChildNode(node, "Style");
// Handle padding
tbPadLeft.Text = _Draw.GetElementValue(sNode, "PaddingLeft", "0pt");
tbPadRight.Text = _Draw.GetElementValue(sNode, "PaddingRight", "0pt");
tbPadTop.Text = _Draw.GetElementValue(sNode, "PaddingTop", "0pt");
tbPadBottom.Text = _Draw.GetElementValue(sNode, "PaddingBottom", "0pt");
this.cbBackColor.Text = _Draw.GetElementValue(sNode, "BackgroundColor", "");
this.cbEndColor.Text = _Draw.GetElementValue(sNode, "BackgroundGradientEndColor", "");
this.cbGradient.Text = _Draw.GetElementValue(sNode, "BackgroundGradientType", "None");
this.tbDEName.Text = _Draw.GetElementValue(node, "DataElementName", "");
this.cbDEOutput.Text = _Draw.GetElementValue(node, "DataElementOutput", "Auto");
if (node.Name != "Chart")
{ // only chart support gradients
this.cbEndColor.Enabled = bExprEndColor.Enabled =
cbGradient.Enabled = bGradient.Enabled =
this.bEndColor.Enabled = bExprEndColor.Enabled = false;
}
if (node.Name == "Line" || node.Name == "System.Drawing.Image")
{
gbXML.Visible = false;
}
// nothing has changed now
fPadLeft = fPadRight = fPadTop = fPadBottom =
fEndColor = fBackColor = fGradient = fDEName = fDEOutput = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label11 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.tbPadLeft = new Oranikle.Studio.Controls.CustomTextControl();
this.tbPadRight = new Oranikle.Studio.Controls.CustomTextControl();
this.tbPadTop = new Oranikle.Studio.Controls.CustomTextControl();
this.tbPadBottom = new Oranikle.Studio.Controls.CustomTextControl();
this.grpBoxPadding = new System.Windows.Forms.GroupBox();
this.button3 = new Oranikle.Studio.Controls.StyledButton();
this.button2 = new Oranikle.Studio.Controls.StyledButton();
this.button1 = new Oranikle.Studio.Controls.StyledButton();
this.bValueExpr = new Oranikle.Studio.Controls.StyledButton();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.bGradient = new Oranikle.Studio.Controls.StyledButton();
this.bExprBackColor = new Oranikle.Studio.Controls.StyledButton();
this.bExprEndColor = new Oranikle.Studio.Controls.StyledButton();
this.bEndColor = new Oranikle.Studio.Controls.StyledButton();
this.cbBackColor = new Oranikle.Studio.Controls.StyledComboBox();
this.cbEndColor = new Oranikle.Studio.Controls.StyledComboBox();
this.label15 = new System.Windows.Forms.Label();
this.cbGradient = new Oranikle.Studio.Controls.StyledComboBox();
this.label10 = new System.Windows.Forms.Label();
this.bBackColor = new Oranikle.Studio.Controls.StyledButton();
this.label3 = new System.Windows.Forms.Label();
this.gbXML = new System.Windows.Forms.GroupBox();
this.cbDEOutput = new Oranikle.Studio.Controls.StyledComboBox();
this.tbDEName = new Oranikle.Studio.Controls.CustomTextControl();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.grpBoxPadding.SuspendLayout();
this.groupBox1.SuspendLayout();
this.gbXML.SuspendLayout();
this.SuspendLayout();
//
// label11
//
this.label11.Location = new System.Drawing.Point(8, 28);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(32, 16);
this.label11.TabIndex = 20;
this.label11.Text = "Left";
//
// label12
//
this.label12.Location = new System.Drawing.Point(224, 28);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(32, 16);
this.label12.TabIndex = 21;
this.label12.Text = "Right";
//
// label13
//
this.label13.Location = new System.Drawing.Point(8, 60);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(32, 16);
this.label13.TabIndex = 22;
this.label13.Text = "Top";
//
// label14
//
this.label14.Location = new System.Drawing.Point(216, 60);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(40, 16);
this.label14.TabIndex = 23;
this.label14.Text = "Bottom";
//
// tbPadLeft
//
this.tbPadLeft.AddX = 0;
this.tbPadLeft.AddY = 0;
this.tbPadLeft.AllowSpace = false;
this.tbPadLeft.BorderColor = System.Drawing.Color.LightGray;
this.tbPadLeft.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbPadLeft.ChangeVisibility = false;
this.tbPadLeft.ChildControl = null;
this.tbPadLeft.ConvertEnterToTab = true;
this.tbPadLeft.ConvertEnterToTabForDialogs = false;
this.tbPadLeft.Decimals = 0;
this.tbPadLeft.DisplayList = new object[0];
this.tbPadLeft.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbPadLeft.Location = new System.Drawing.Point(48, 26);
this.tbPadLeft.Name = "tbPadLeft";
this.tbPadLeft.OnDropDownCloseFocus = true;
this.tbPadLeft.SelectType = 0;
this.tbPadLeft.Size = new System.Drawing.Size(128, 20);
this.tbPadLeft.TabIndex = 0;
this.tbPadLeft.UseValueForChildsVisibilty = false;
this.tbPadLeft.Value = true;
this.tbPadLeft.TextChanged += new System.EventHandler(this.tbPadLeft_TextChanged);
//
// tbPadRight
//
this.tbPadRight.AddX = 0;
this.tbPadRight.AddY = 0;
this.tbPadRight.AllowSpace = false;
this.tbPadRight.BorderColor = System.Drawing.Color.LightGray;
this.tbPadRight.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbPadRight.ChangeVisibility = false;
this.tbPadRight.ChildControl = null;
this.tbPadRight.ConvertEnterToTab = true;
this.tbPadRight.ConvertEnterToTabForDialogs = false;
this.tbPadRight.Decimals = 0;
this.tbPadRight.DisplayList = new object[0];
this.tbPadRight.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbPadRight.Location = new System.Drawing.Point(264, 26);
this.tbPadRight.Name = "tbPadRight";
this.tbPadRight.OnDropDownCloseFocus = true;
this.tbPadRight.SelectType = 0;
this.tbPadRight.Size = new System.Drawing.Size(128, 20);
this.tbPadRight.TabIndex = 2;
this.tbPadRight.UseValueForChildsVisibilty = false;
this.tbPadRight.Value = true;
this.tbPadRight.TextChanged += new System.EventHandler(this.tbPadRight_TextChanged);
//
// tbPadTop
//
this.tbPadTop.AddX = 0;
this.tbPadTop.AddY = 0;
this.tbPadTop.AllowSpace = false;
this.tbPadTop.BorderColor = System.Drawing.Color.LightGray;
this.tbPadTop.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbPadTop.ChangeVisibility = false;
this.tbPadTop.ChildControl = null;
this.tbPadTop.ConvertEnterToTab = true;
this.tbPadTop.ConvertEnterToTabForDialogs = false;
this.tbPadTop.Decimals = 0;
this.tbPadTop.DisplayList = new object[0];
this.tbPadTop.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbPadTop.Location = new System.Drawing.Point(48, 58);
this.tbPadTop.Name = "tbPadTop";
this.tbPadTop.OnDropDownCloseFocus = true;
this.tbPadTop.SelectType = 0;
this.tbPadTop.Size = new System.Drawing.Size(128, 20);
this.tbPadTop.TabIndex = 4;
this.tbPadTop.UseValueForChildsVisibilty = false;
this.tbPadTop.Value = true;
this.tbPadTop.TextChanged += new System.EventHandler(this.tbPadTop_TextChanged);
//
// tbPadBottom
//
this.tbPadBottom.AddX = 0;
this.tbPadBottom.AddY = 0;
this.tbPadBottom.AllowSpace = false;
this.tbPadBottom.BorderColor = System.Drawing.Color.LightGray;
this.tbPadBottom.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbPadBottom.ChangeVisibility = false;
this.tbPadBottom.ChildControl = null;
this.tbPadBottom.ConvertEnterToTab = true;
this.tbPadBottom.ConvertEnterToTabForDialogs = false;
this.tbPadBottom.Decimals = 0;
this.tbPadBottom.DisplayList = new object[0];
this.tbPadBottom.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbPadBottom.Location = new System.Drawing.Point(264, 58);
this.tbPadBottom.Name = "tbPadBottom";
this.tbPadBottom.OnDropDownCloseFocus = true;
this.tbPadBottom.SelectType = 0;
this.tbPadBottom.Size = new System.Drawing.Size(128, 20);
this.tbPadBottom.TabIndex = 6;
this.tbPadBottom.UseValueForChildsVisibilty = false;
this.tbPadBottom.Value = true;
this.tbPadBottom.TextChanged += new System.EventHandler(this.tbPadBottom_TextChanged);
//
// grpBoxPadding
//
this.grpBoxPadding.Controls.Add(this.button3);
this.grpBoxPadding.Controls.Add(this.button2);
this.grpBoxPadding.Controls.Add(this.button1);
this.grpBoxPadding.Controls.Add(this.bValueExpr);
this.grpBoxPadding.Controls.Add(this.label13);
this.grpBoxPadding.Controls.Add(this.tbPadRight);
this.grpBoxPadding.Controls.Add(this.label14);
this.grpBoxPadding.Controls.Add(this.label11);
this.grpBoxPadding.Controls.Add(this.tbPadBottom);
this.grpBoxPadding.Controls.Add(this.label12);
this.grpBoxPadding.Controls.Add(this.tbPadTop);
this.grpBoxPadding.Controls.Add(this.tbPadLeft);
this.grpBoxPadding.Location = new System.Drawing.Point(16, 96);
this.grpBoxPadding.Name = "grpBoxPadding";
this.grpBoxPadding.Size = new System.Drawing.Size(432, 88);
this.grpBoxPadding.TabIndex = 1;
this.grpBoxPadding.TabStop = false;
this.grpBoxPadding.Text = "Padding";
//
// button3
//
this.button3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.button3.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.button3.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.button3.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button3.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.button3.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button3.Location = new System.Drawing.Point(400, 26);
this.button3.Name = "button3";
this.button3.OverriddenSize = null;
this.button3.Size = new System.Drawing.Size(22, 21);
this.button3.TabIndex = 3;
this.button3.Tag = "pright";
this.button3.Text = "fx";
this.button3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.bExpr_Click);
//
// button2
//
this.button2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.button2.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.button2.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.button2.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.button2.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button2.Location = new System.Drawing.Point(400, 58);
this.button2.Name = "button2";
this.button2.OverriddenSize = null;
this.button2.Size = new System.Drawing.Size(22, 21);
this.button2.TabIndex = 7;
this.button2.Tag = "pbottom";
this.button2.Text = "fx";
this.button2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.bExpr_Click);
//
// button1
//
this.button1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.button1.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.button1.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.button1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.button1.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button1.Location = new System.Drawing.Point(184, 58);
this.button1.Name = "button1";
this.button1.OverriddenSize = null;
this.button1.Size = new System.Drawing.Size(22, 21);
this.button1.TabIndex = 5;
this.button1.Tag = "ptop";
this.button1.Text = "fx";
this.button1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.bExpr_Click);
//
// bValueExpr
//
this.bValueExpr.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bValueExpr.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bValueExpr.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bValueExpr.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bValueExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bValueExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bValueExpr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bValueExpr.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bValueExpr.Location = new System.Drawing.Point(184, 26);
this.bValueExpr.Name = "bValueExpr";
this.bValueExpr.OverriddenSize = null;
this.bValueExpr.Size = new System.Drawing.Size(22, 21);
this.bValueExpr.TabIndex = 1;
this.bValueExpr.Tag = "pleft";
this.bValueExpr.Text = "fx";
this.bValueExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bValueExpr.UseVisualStyleBackColor = true;
this.bValueExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.bGradient);
this.groupBox1.Controls.Add(this.bExprBackColor);
this.groupBox1.Controls.Add(this.bExprEndColor);
this.groupBox1.Controls.Add(this.bEndColor);
this.groupBox1.Controls.Add(this.cbBackColor);
this.groupBox1.Controls.Add(this.cbEndColor);
this.groupBox1.Controls.Add(this.label15);
this.groupBox1.Controls.Add(this.cbGradient);
this.groupBox1.Controls.Add(this.label10);
this.groupBox1.Controls.Add(this.bBackColor);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Location = new System.Drawing.Point(16, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(432, 80);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Background";
//
// bGradient
//
this.bGradient.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bGradient.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bGradient.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bGradient.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bGradient.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bGradient.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bGradient.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bGradient.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bGradient.Location = new System.Drawing.Point(253, 42);
this.bGradient.Name = "bGradient";
this.bGradient.OverriddenSize = null;
this.bGradient.Size = new System.Drawing.Size(22, 21);
this.bGradient.TabIndex = 4;
this.bGradient.Tag = "bgradient";
this.bGradient.Text = "fx";
this.bGradient.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bGradient.UseVisualStyleBackColor = true;
this.bGradient.Click += new System.EventHandler(this.bExpr_Click);
//
// bExprBackColor
//
this.bExprBackColor.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bExprBackColor.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bExprBackColor.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bExprBackColor.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bExprBackColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bExprBackColor.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bExprBackColor.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bExprBackColor.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExprBackColor.Location = new System.Drawing.Point(102, 42);
this.bExprBackColor.Name = "bExprBackColor";
this.bExprBackColor.OverriddenSize = null;
this.bExprBackColor.Size = new System.Drawing.Size(22, 21);
this.bExprBackColor.TabIndex = 1;
this.bExprBackColor.Tag = "bcolor";
this.bExprBackColor.Text = "fx";
this.bExprBackColor.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExprBackColor.UseVisualStyleBackColor = true;
this.bExprBackColor.Click += new System.EventHandler(this.bExpr_Click);
//
// bExprEndColor
//
this.bExprEndColor.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bExprEndColor.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bExprEndColor.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bExprEndColor.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bExprEndColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bExprEndColor.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bExprEndColor.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bExprEndColor.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExprEndColor.Location = new System.Drawing.Point(377, 42);
this.bExprEndColor.Name = "bExprEndColor";
this.bExprEndColor.OverriddenSize = null;
this.bExprEndColor.Size = new System.Drawing.Size(22, 21);
this.bExprEndColor.TabIndex = 6;
this.bExprEndColor.Tag = "bendcolor";
this.bExprEndColor.Text = "fx";
this.bExprEndColor.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExprEndColor.UseVisualStyleBackColor = true;
this.bExprEndColor.Click += new System.EventHandler(this.bExpr_Click);
//
// bEndColor
//
this.bEndColor.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bEndColor.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bEndColor.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bEndColor.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bEndColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bEndColor.Font = new System.Drawing.Font("Arial", 9F);
this.bEndColor.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bEndColor.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bEndColor.Location = new System.Drawing.Point(404, 42);
this.bEndColor.Name = "bEndColor";
this.bEndColor.OverriddenSize = null;
this.bEndColor.Size = new System.Drawing.Size(22, 21);
this.bEndColor.TabIndex = 7;
this.bEndColor.Text = "...";
this.bEndColor.UseVisualStyleBackColor = true;
this.bEndColor.Click += new System.EventHandler(this.bColor_Click);
//
// cbBackColor
//
this.cbBackColor.AutoAdjustItemHeight = false;
this.cbBackColor.BorderColor = System.Drawing.Color.LightGray;
this.cbBackColor.ConvertEnterToTabForDialogs = false;
this.cbBackColor.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbBackColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbBackColor.Location = new System.Drawing.Point(8, 42);
this.cbBackColor.Name = "cbBackColor";
this.cbBackColor.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbBackColor.SeparatorMargin = 1;
this.cbBackColor.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbBackColor.SeparatorWidth = 1;
this.cbBackColor.Size = new System.Drawing.Size(88, 21);
this.cbBackColor.TabIndex = 0;
this.cbBackColor.SelectedIndexChanged += new System.EventHandler(this.cbBackColor_SelectedIndexChanged);
this.cbBackColor.TextChanged += new System.EventHandler(this.cbBackColor_SelectedIndexChanged);
//
// cbEndColor
//
this.cbEndColor.AutoAdjustItemHeight = false;
this.cbEndColor.BorderColor = System.Drawing.Color.LightGray;
this.cbEndColor.ConvertEnterToTabForDialogs = false;
this.cbEndColor.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbEndColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbEndColor.Location = new System.Drawing.Point(286, 42);
this.cbEndColor.Name = "cbEndColor";
this.cbEndColor.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbEndColor.SeparatorMargin = 1;
this.cbEndColor.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbEndColor.SeparatorWidth = 1;
this.cbEndColor.Size = new System.Drawing.Size(88, 21);
this.cbEndColor.TabIndex = 5;
this.cbEndColor.SelectedIndexChanged += new System.EventHandler(this.cbEndColor_SelectedIndexChanged);
this.cbEndColor.TextChanged += new System.EventHandler(this.cbEndColor_SelectedIndexChanged);
//
// label15
//
this.label15.Location = new System.Drawing.Point(286, 24);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(56, 16);
this.label15.TabIndex = 5;
this.label15.Text = "End Color";
//
// cbGradient
//
this.cbGradient.AutoAdjustItemHeight = false;
this.cbGradient.BorderColor = System.Drawing.Color.LightGray;
this.cbGradient.ConvertEnterToTabForDialogs = false;
this.cbGradient.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbGradient.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbGradient.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbGradient.Items.AddRange(new object[] {
"None",
"LeftRight",
"TopBottom",
"Center",
"DiagonalLeft",
"DiagonalRight",
"HorizontalCenter",
"VerticalCenter"});
this.cbGradient.Location = new System.Drawing.Point(161, 42);
this.cbGradient.Name = "cbGradient";
this.cbGradient.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbGradient.SeparatorMargin = 1;
this.cbGradient.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbGradient.SeparatorWidth = 1;
this.cbGradient.Size = new System.Drawing.Size(88, 21);
this.cbGradient.TabIndex = 3;
this.cbGradient.SelectedIndexChanged += new System.EventHandler(this.cbGradient_SelectedIndexChanged);
//
// label10
//
this.label10.Location = new System.Drawing.Point(161, 24);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(48, 16);
this.label10.TabIndex = 3;
this.label10.Text = "Gradient";
//
// bBackColor
//
this.bBackColor.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bBackColor.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bBackColor.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bBackColor.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bBackColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bBackColor.Font = new System.Drawing.Font("Arial", 9F);
this.bBackColor.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bBackColor.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bBackColor.Location = new System.Drawing.Point(128, 42);
this.bBackColor.Name = "bBackColor";
this.bBackColor.OverriddenSize = null;
this.bBackColor.Size = new System.Drawing.Size(22, 21);
this.bBackColor.TabIndex = 2;
this.bBackColor.Text = "...";
this.bBackColor.UseVisualStyleBackColor = true;
this.bBackColor.Click += new System.EventHandler(this.bColor_Click);
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 24);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(32, 16);
this.label3.TabIndex = 0;
this.label3.Text = "Color";
//
// gbXML
//
this.gbXML.Controls.Add(this.cbDEOutput);
this.gbXML.Controls.Add(this.tbDEName);
this.gbXML.Controls.Add(this.label2);
this.gbXML.Controls.Add(this.label1);
this.gbXML.Location = new System.Drawing.Point(16, 200);
this.gbXML.Name = "gbXML";
this.gbXML.Size = new System.Drawing.Size(432, 80);
this.gbXML.TabIndex = 24;
this.gbXML.TabStop = false;
this.gbXML.Text = "XML";
//
// cbDEOutput
//
this.cbDEOutput.AutoAdjustItemHeight = false;
this.cbDEOutput.BorderColor = System.Drawing.Color.LightGray;
this.cbDEOutput.ConvertEnterToTabForDialogs = false;
this.cbDEOutput.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbDEOutput.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDEOutput.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbDEOutput.Items.AddRange(new object[] {
"Output",
"NoOutput",
"ContentsOnly",
"Auto"});
this.cbDEOutput.Location = new System.Drawing.Point(138, 43);
this.cbDEOutput.Name = "cbDEOutput";
this.cbDEOutput.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbDEOutput.SeparatorMargin = 1;
this.cbDEOutput.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbDEOutput.SeparatorWidth = 1;
this.cbDEOutput.Size = new System.Drawing.Size(117, 21);
this.cbDEOutput.TabIndex = 3;
this.cbDEOutput.SelectedIndexChanged += new System.EventHandler(this.cbDEOutput_SelectedIndexChanged);
//
// tbDEName
//
this.tbDEName.AddX = 0;
this.tbDEName.AddY = 0;
this.tbDEName.AllowSpace = false;
this.tbDEName.BorderColor = System.Drawing.Color.LightGray;
this.tbDEName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbDEName.ChangeVisibility = false;
this.tbDEName.ChildControl = null;
this.tbDEName.ConvertEnterToTab = true;
this.tbDEName.ConvertEnterToTabForDialogs = false;
this.tbDEName.Decimals = 0;
this.tbDEName.DisplayList = new object[0];
this.tbDEName.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbDEName.Location = new System.Drawing.Point(137, 18);
this.tbDEName.Name = "tbDEName";
this.tbDEName.OnDropDownCloseFocus = true;
this.tbDEName.SelectType = 0;
this.tbDEName.Size = new System.Drawing.Size(279, 20);
this.tbDEName.TabIndex = 2;
this.tbDEName.Text = "textBox1";
this.tbDEName.UseValueForChildsVisibilty = false;
this.tbDEName.Value = true;
this.tbDEName.TextChanged += new System.EventHandler(this.tbDEName_TextChanged);
//
// label2
//
this.label2.Location = new System.Drawing.Point(11, 43);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(116, 20);
this.label2.TabIndex = 1;
this.label2.Text = "DataElementOutput";
//
// label1
//
this.label1.Location = new System.Drawing.Point(10, 18);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100, 20);
this.label1.TabIndex = 0;
this.label1.Text = "DataElementName";
//
// StyleCtl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.grpBoxPadding);
this.Controls.Add(this.gbXML);
this.Name = "StyleCtl";
this.Size = new System.Drawing.Size(472, 312);
this.grpBoxPadding.ResumeLayout(false);
this.grpBoxPadding.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.gbXML.ResumeLayout(false);
this.gbXML.PerformLayout();
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
string name="";
try
{
if (fPadLeft && !this.tbPadLeft.Text.StartsWith("="))
{
name = "Left";
DesignerUtility.ValidateSize(this.tbPadLeft.Text, true, false);
}
if (fPadRight && !this.tbPadRight.Text.StartsWith("="))
{
name = "Right";
DesignerUtility.ValidateSize(this.tbPadRight.Text, true, false);
}
if (fPadTop && !this.tbPadTop.Text.StartsWith("="))
{
name = "Top";
DesignerUtility.ValidateSize(this.tbPadTop.Text, true, false);
}
if (fPadBottom && !this.tbPadBottom.Text.StartsWith("="))
{
name = "Bottom";
DesignerUtility.ValidateSize(this.tbPadBottom.Text, true, false);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, name + " Padding Invalid");
return false;
}
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// nothing has changed now
fPadLeft = fPadRight = fPadTop = fPadBottom =
fEndColor = fBackColor = fGradient = fDEName = fDEOutput = false;
}
private void bFont_Click(object sender, System.EventArgs e)
{
using (FontDialog fd = new FontDialog())
{
fd.ShowColor = true;
if (fd.ShowDialog() != DialogResult.OK)
return;
}
return;
}
private void bColor_Click(object sender, System.EventArgs e)
{
using (ColorDialog cd = new ColorDialog())
{
cd.AnyColor = true;
cd.FullOpen = true;
cd.CustomColors = RdlDesigner.GetCustomColors();
if (cd.ShowDialog() != DialogResult.OK)
return;
RdlDesigner.SetCustomColors(cd.CustomColors);
if (sender == this.bEndColor)
cbEndColor.Text = ColorTranslator.ToHtml(cd.Color);
else if (sender == this.bBackColor)
cbBackColor.Text = ColorTranslator.ToHtml(cd.Color);
}
return;
}
private void cbBackColor_SelectedIndexChanged(object sender, System.EventArgs e)
{
fBackColor = true;
}
private void cbGradient_SelectedIndexChanged(object sender, System.EventArgs e)
{
fGradient = true;
}
private void cbEndColor_SelectedIndexChanged(object sender, System.EventArgs e)
{
fEndColor = true;
}
private void tbPadLeft_TextChanged(object sender, System.EventArgs e)
{
fPadLeft = true;
}
private void tbPadRight_TextChanged(object sender, System.EventArgs e)
{
fPadRight = true;
}
private void tbPadTop_TextChanged(object sender, System.EventArgs e)
{
fPadTop = true;
}
private void tbPadBottom_TextChanged(object sender, System.EventArgs e)
{
fPadBottom = true;
}
private void ApplyChanges(XmlNode rNode)
{
XmlNode xNode = _Draw.GetNamedChildNode(rNode, "Style");
if (fPadLeft)
{ _Draw.SetElement(xNode, "PaddingLeft", tbPadLeft.Text); }
if (fPadRight)
{ _Draw.SetElement(xNode, "PaddingRight", tbPadRight.Text); }
if (fPadTop)
{ _Draw.SetElement(xNode, "PaddingTop", tbPadTop.Text); }
if (fPadBottom)
{ _Draw.SetElement(xNode, "PaddingBottom", tbPadBottom.Text); }
if (fEndColor)
{ _Draw.SetElement(xNode, "BackgroundGradientEndColor", cbEndColor.Text); }
if (fBackColor)
{ _Draw.SetElement(xNode, "BackgroundColor", cbBackColor.Text); }
if (fGradient)
{ _Draw.SetElement(xNode, "BackgroundGradientType", cbGradient.Text); }
if (fDEName)
{ _Draw.SetElement(rNode, "DataElementName", tbDEName.Text); }
if (fDEOutput)
{ _Draw.SetElement(rNode, "DataElementOutput", cbDEOutput.Text); }
}
private void cbDEOutput_SelectedIndexChanged(object sender, System.EventArgs e)
{
fDEOutput = true;
}
private void tbDEName_TextChanged(object sender, System.EventArgs e)
{
fDEName = true;
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
bool bColor=false;
switch (b.Tag as string)
{
case "pleft":
c = tbPadLeft;
break;
case "pright":
c = tbPadRight;
break;
case "ptop":
c = tbPadTop;
break;
case "pbottom":
c = tbPadBottom;
break;
case "bcolor":
c = cbBackColor;
bColor = true;
break;
case "bgradient":
c = cbGradient;
break;
case "bendcolor":
c = cbEndColor;
bColor = true;
break;
}
if (c == null)
return;
XmlNode sNode = _ReportItems[0];
using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor))
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
}
return;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace EventManager.Server.WepApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* Copyright (c) 2011 Alex Fort
* 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.
* 3. 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.
*/
namespace Schemin.Parse
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Schemin.AST;
using Schemin.Tokenize;
public class PairParser
{
public ScheminPair Parse(List<Token> tokens, bool quoteLists)
{
TransformQuoteTokens(tokens);
int currentPosition = 0;
ScheminPair totalParsed = new ScheminPair();
while (currentPosition < tokens.Count)
{
totalParsed = totalParsed.Append(ParseTopLevel(tokens, ref currentPosition));
}
return totalParsed.Cons(new ScheminPrimitive("begin"));
}
private IScheminType ParseTopLevel(List<Token> tokens, ref int currentPosition)
{
switch (tokens[currentPosition].Type)
{
case TokenType.OpenParen:
if (tokens[currentPosition + 1].Type == TokenType.CloseParen)
{
currentPosition++;
return new ScheminPair();
}
else
{
currentPosition++;
return ParseList(tokens, ref currentPosition);
}
case TokenType.VectorLiteral:
return ParseVector(tokens, ref currentPosition);
default:
IScheminType converted = ConvertToken(tokens[currentPosition]);
currentPosition++;
return converted;
}
}
private IScheminType ParseList(List<Token> tokens, ref int currentPosition)
{
ScheminPair built = new ScheminPair();
switch (tokens[currentPosition].Type)
{
case TokenType.CloseParen:
if (tokens[currentPosition - 1].Type == TokenType.OpenParen)
{
currentPosition++;
return new ScheminPair();
}
currentPosition++;
return null;
case TokenType.OpenParen:
currentPosition++;
built.Car = ParseList(tokens, ref currentPosition);
built.Cdr = ParseList(tokens, ref currentPosition);
return built;
case TokenType.VectorLiteral:
built.Car = ParseVector(tokens, ref currentPosition);
built.Cdr = ParseList(tokens, ref currentPosition);
return built;
case TokenType.Dot:
currentPosition++;
return ParseDot(tokens, ref currentPosition);
default:
built.Car = ConvertToken(tokens[currentPosition]);
currentPosition++;
built.Cdr = ParseList(tokens, ref currentPosition);
return built;
}
}
private IScheminType ParseVector(List<Token> tokens, ref int currentPosition)
{
currentPosition += 2;
ScheminVector parsed = ((ScheminPair) ParseList(tokens, ref currentPosition)).ToVector();
return parsed;
}
private IScheminType ParseDot(List<Token> tokens, ref int currentPosition)
{
switch (tokens[currentPosition].Type)
{
case TokenType.OpenParen:
currentPosition++;
IScheminType parsed = ParseList(tokens, ref currentPosition);
currentPosition++;
return parsed;
case TokenType.VectorLiteral:
IScheminType parsedVec = ParseVector(tokens, ref currentPosition);
currentPosition++;
return parsedVec;
default:
var converted = ConvertToken(tokens[currentPosition]);
currentPosition += 2;
return converted;
}
}
private void TransformQuoteTokens(List<Token> tokens)
{
for (int i = 0; i < tokens.Count; i++)
{
switch (tokens[i].Type)
{
case TokenType.Quote:
case TokenType.BackQuote:
case TokenType.Comma:
case TokenType.AtComma:
RemapQuoteToken(tokens, i);
break;
}
}
}
private void RemapQuoteToken(List<Token> tokens, int currentPosition)
{
tokens[currentPosition] = RemapQuote(tokens[currentPosition]);
tokens.Insert(currentPosition, new Token(TokenType.OpenParen, "("));
int quotedTermination = FindQuotedTermination(tokens, currentPosition + 2);
tokens.Insert(quotedTermination, new Token(TokenType.CloseParen, ")"));
}
private IScheminType ConvertToken(Token token)
{
switch (token.Type)
{
case TokenType.Symbol:
return AtomFactory.GetAtom(token.Value);
case TokenType.IntegerLiteral:
return new ScheminInteger(BigInteger.Parse(token.Value));
case TokenType.DecimalLiteral:
return new ScheminDecimal(decimal.Parse(token.Value));
case TokenType.StringLiteral:
return new ScheminString(token.Value);
case TokenType.BoolLiteral:
return ScheminBool.GetValue(token.Value == "#t" ? true : false);
case TokenType.CharLiteral:
return new ScheminChar(token.Value.Replace("#\\", ""));
default:
throw new Exception(string.Format("Unable to convert token of type: {0}", token.Type));
}
}
private Token RemapQuote(Token quote)
{
Dictionary<string, Token> remapped = new Dictionary<string, Token>();
remapped.Add("'", new Token(TokenType.Symbol, "quote"));
remapped.Add("`", new Token(TokenType.Symbol, "quasiquote"));
remapped.Add(",", new Token(TokenType.Symbol, "unquote"));
remapped.Add(",@", new Token(TokenType.Symbol, "unquote-splicing"));
return remapped[quote.Value];
}
private int FindQuotedTermination(List<Token> tokens, int startIndex)
{
switch (tokens[startIndex].Type)
{
case TokenType.OpenParen:
startIndex++;
return FindMatchingParen(tokens, startIndex);
case TokenType.VectorLiteral:
startIndex += 2;
return FindMatchingParen(tokens, startIndex);
case TokenType.AtComma:
case TokenType.BackQuote:
case TokenType.Quote:
case TokenType.Comma:
while (!(IsQuotable(tokens[startIndex])))
startIndex++;
return startIndex + 1;
default:
return startIndex + 1;
}
}
private bool IsQuoteToken(Token token)
{
string[] quotes = { "'", "`", ",", ",@" };
if (quotes.Contains(token.Value))
{
return true;
}
return false;
}
private bool IsQuotable(Token token)
{
TokenType[] quotables = { TokenType.DecimalLiteral, TokenType.IntegerLiteral, TokenType.OpenParen,
TokenType.StringLiteral, TokenType.Symbol, TokenType.VectorLiteral };
if (quotables.Contains(token.Type))
{
return true;
}
else
{
return false;
}
}
private int FindMatchingParen(List<Token> tokens, int startIndex)
{
int neededClosing = 1;
while (neededClosing != 0)
{
if (tokens[startIndex].Type == TokenType.CloseParen)
{
neededClosing--;
}
else if (tokens[startIndex].Type == TokenType.OpenParen)
{
neededClosing++;
}
if (neededClosing == 0)
break;
startIndex++;
}
return startIndex;
}
}
}
| |
/*-
* Automatically built by dist/s_java_csharp.
*
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2010 Oracle and/or its affiliates. All rights reserved.
*/
using System;
using System.Runtime.InteropServices;
namespace BerkeleyDB.Internal {
[StructLayout(LayoutKind.Sequential)]
internal struct BTreeStatStruct {
internal uint bt_magic;
internal uint bt_version;
internal uint bt_metaflags;
internal uint bt_nkeys;
internal uint bt_ndata;
internal uint bt_pagecnt;
internal uint bt_pagesize;
internal uint bt_minkey;
internal uint bt_re_len;
internal uint bt_re_pad;
internal uint bt_levels;
internal uint bt_int_pg;
internal uint bt_leaf_pg;
internal uint bt_dup_pg;
internal uint bt_over_pg;
internal uint bt_empty_pg;
internal uint bt_free;
internal ulong bt_int_pgfree;
internal ulong bt_leaf_pgfree;
internal ulong bt_dup_pgfree;
internal ulong bt_over_pgfree;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HashStatStruct {
internal uint hash_magic;
internal uint hash_version;
internal uint hash_metaflags;
internal uint hash_nkeys;
internal uint hash_ndata;
internal uint hash_pagecnt;
internal uint hash_pagesize;
internal uint hash_ffactor;
internal uint hash_buckets;
internal uint hash_free;
internal ulong hash_bfree;
internal uint hash_bigpages;
internal ulong hash_big_bfree;
internal uint hash_overflows;
internal ulong hash_ovfl_free;
internal uint hash_dup;
internal ulong hash_dup_free;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LockStatStruct {
internal uint st_id;
internal uint st_cur_maxid;
internal uint st_maxlocks;
internal uint st_maxlockers;
internal uint st_maxobjects;
internal uint st_partitions;
internal int st_nmodes;
internal uint st_nlockers;
internal uint st_nlocks;
internal uint st_maxnlocks;
internal uint st_maxhlocks;
internal ulong st_locksteals;
internal ulong st_maxlsteals;
internal uint st_maxnlockers;
internal uint st_nobjects;
internal uint st_maxnobjects;
internal uint st_maxhobjects;
internal ulong st_objectsteals;
internal ulong st_maxosteals;
internal ulong st_nrequests;
internal ulong st_nreleases;
internal ulong st_nupgrade;
internal ulong st_ndowngrade;
internal ulong st_lock_wait;
internal ulong st_lock_nowait;
internal ulong st_ndeadlocks;
internal uint st_locktimeout;
internal ulong st_nlocktimeouts;
internal uint st_txntimeout;
internal ulong st_ntxntimeouts;
internal ulong st_part_wait;
internal ulong st_part_nowait;
internal ulong st_part_max_wait;
internal ulong st_part_max_nowait;
internal ulong st_objs_wait;
internal ulong st_objs_nowait;
internal ulong st_lockers_wait;
internal ulong st_lockers_nowait;
internal ulong st_region_wait;
internal ulong st_region_nowait;
internal uint st_hash_len;
internal IntPtr st_regsize;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LogStatStruct {
internal uint st_magic;
internal uint st_version;
internal int st_mode;
internal uint st_lg_bsize;
internal uint st_lg_size;
internal uint st_wc_bytes;
internal uint st_wc_mbytes;
internal ulong st_record;
internal uint st_w_bytes;
internal uint st_w_mbytes;
internal ulong st_wcount;
internal ulong st_wcount_fill;
internal ulong st_rcount;
internal ulong st_scount;
internal ulong st_region_wait;
internal ulong st_region_nowait;
internal uint st_cur_file;
internal uint st_cur_offset;
internal uint st_disk_file;
internal uint st_disk_offset;
internal uint st_maxcommitperflush;
internal uint st_mincommitperflush;
internal IntPtr st_regsize;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MPoolFileStatStruct {
internal string file_name;
internal uint st_pagesize;
internal uint st_map;
internal ulong st_cache_hit;
internal ulong st_cache_miss;
internal ulong st_page_create;
internal ulong st_page_in;
internal ulong st_page_out;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MPoolStatStruct {
internal uint st_gbytes;
internal uint st_bytes;
internal uint st_ncache;
internal uint st_max_ncache;
internal IntPtr st_mmapsize;
internal int st_maxopenfd;
internal int st_maxwrite;
internal uint st_maxwrite_sleep;
internal uint st_pages;
internal uint st_map;
internal ulong st_cache_hit;
internal ulong st_cache_miss;
internal ulong st_page_create;
internal ulong st_page_in;
internal ulong st_page_out;
internal ulong st_ro_evict;
internal ulong st_rw_evict;
internal ulong st_page_trickle;
internal uint st_page_clean;
internal uint st_page_dirty;
internal uint st_hash_buckets;
internal uint st_pagesize;
internal uint st_hash_searches;
internal uint st_hash_longest;
internal ulong st_hash_examined;
internal ulong st_hash_nowait;
internal ulong st_hash_wait;
internal ulong st_hash_max_nowait;
internal ulong st_hash_max_wait;
internal ulong st_region_nowait;
internal ulong st_region_wait;
internal ulong st_mvcc_frozen;
internal ulong st_mvcc_thawed;
internal ulong st_mvcc_freed;
internal ulong st_alloc;
internal ulong st_alloc_buckets;
internal ulong st_alloc_max_buckets;
internal ulong st_alloc_pages;
internal ulong st_alloc_max_pages;
internal ulong st_io_wait;
internal ulong st_sync_interrupted;
internal IntPtr st_regsize;
}
internal struct MempStatStruct {
internal MPoolStatStruct st;
internal MPoolFileStatStruct[] files;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MutexStatStruct {
internal uint st_mutex_align;
internal uint st_mutex_tas_spins;
internal uint st_mutex_cnt;
internal uint st_mutex_free;
internal uint st_mutex_inuse;
internal uint st_mutex_inuse_max;
internal ulong st_region_wait;
internal ulong st_region_nowait;
internal IntPtr st_regsize;
}
[StructLayout(LayoutKind.Sequential)]
internal struct QueueStatStruct {
internal uint qs_magic;
internal uint qs_version;
internal uint qs_metaflags;
internal uint qs_nkeys;
internal uint qs_ndata;
internal uint qs_pagesize;
internal uint qs_extentsize;
internal uint qs_pages;
internal uint qs_re_len;
internal uint qs_re_pad;
internal uint qs_pgfree;
internal uint qs_first_recno;
internal uint qs_cur_recno;
}
[StructLayout(LayoutKind.Sequential)]
internal struct RecnoStatStruct {
internal uint bt_magic;
internal uint bt_version;
internal uint bt_metaflags;
internal uint bt_nkeys;
internal uint bt_ndata;
internal uint bt_pagecnt;
internal uint bt_pagesize;
internal uint bt_minkey;
internal uint bt_re_len;
internal uint bt_re_pad;
internal uint bt_levels;
internal uint bt_int_pg;
internal uint bt_leaf_pg;
internal uint bt_dup_pg;
internal uint bt_over_pg;
internal uint bt_empty_pg;
internal uint bt_free;
internal ulong bt_int_pgfree;
internal ulong bt_leaf_pgfree;
internal ulong bt_dup_pgfree;
internal ulong bt_over_pgfree;
}
[StructLayout(LayoutKind.Sequential)]
internal struct RepMgrStatStruct {
internal ulong st_perm_failed;
internal ulong st_msgs_queued;
internal ulong st_msgs_dropped;
internal ulong st_connection_drop;
internal ulong st_connect_fail;
internal ulong st_elect_threads;
internal ulong st_max_elect_threads;
}
[StructLayout(LayoutKind.Sequential)]
internal struct ReplicationStatStruct {
/* !!!
* Many replication statistics fields cannot be protected by a mutex
* without an unacceptable performance penalty, since most message
* processing is done without the need to hold a region-wide lock.
* Fields whose comments end with a '+' may be updated without holding
* the replication or log mutexes (as appropriate), and thus may be
* off somewhat (or, on unreasonable architectures under unlucky
* circumstances, garbaged).
*/
internal uint st_startup_complete;
internal ulong st_log_queued;
internal uint st_status;
internal DB_LSN_STRUCT st_next_lsn;
internal DB_LSN_STRUCT st_waiting_lsn;
internal DB_LSN_STRUCT st_max_perm_lsn;
internal uint st_next_pg;
internal uint st_waiting_pg;
internal uint st_dupmasters;
internal int st_env_id;
internal uint st_env_priority;
internal ulong st_bulk_fills;
internal ulong st_bulk_overflows;
internal ulong st_bulk_records;
internal ulong st_bulk_transfers;
internal ulong st_client_rerequests;
internal ulong st_client_svc_req;
internal ulong st_client_svc_miss;
internal uint st_gen;
internal uint st_egen;
internal ulong st_log_duplicated;
internal ulong st_log_queued_max;
internal ulong st_log_queued_total;
internal ulong st_log_records;
internal ulong st_log_requested;
internal int st_master;
internal ulong st_master_changes;
internal ulong st_msgs_badgen;
internal ulong st_msgs_processed;
internal ulong st_msgs_recover;
internal ulong st_msgs_send_failures;
internal ulong st_msgs_sent;
internal ulong st_newsites;
internal uint st_nsites;
internal ulong st_nthrottles;
internal ulong st_outdated;
internal ulong st_pg_duplicated;
internal ulong st_pg_records;
internal ulong st_pg_requested;
internal ulong st_txns_applied;
internal ulong st_startsync_delayed;
internal ulong st_elections;
internal ulong st_elections_won;
internal int st_election_cur_winner;
internal uint st_election_gen;
internal DB_LSN_STRUCT st_election_lsn;
internal uint st_election_nsites;
internal uint st_election_nvotes;
internal uint st_election_priority;
internal int st_election_status;
internal uint st_election_tiebreaker;
internal uint st_election_votes;
internal uint st_election_sec;
internal uint st_election_usec;
internal uint st_max_lease_sec;
internal uint st_max_lease_usec;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SequenceStatStruct {
internal ulong st_wait;
internal ulong st_nowait;
internal long st_current;
internal long st_value;
internal long st_last_value;
internal long st_min;
internal long st_max;
internal int st_cache_size;
internal uint st_flags;
}
[StructLayout(LayoutKind.Sequential)]
internal struct TransactionStatStruct {
internal uint st_nrestores;
internal DB_LSN_STRUCT st_last_ckp;
internal long st_time_ckp;
internal uint st_last_txnid;
internal uint st_maxtxns;
internal ulong st_naborts;
internal ulong st_nbegins;
internal ulong st_ncommits;
internal uint st_nactive;
internal uint st_nsnapshot;
internal uint st_maxnactive;
internal uint st_maxnsnapshot;
internal IntPtr st_txnarray;
internal ulong st_region_wait;
internal ulong st_region_nowait;
internal IntPtr st_regsize;
}
internal struct DB_LSN_STRUCT {
internal uint file;
internal uint offset;
}
internal enum DB_TXN_ACTIVE_STATUS {
TXN_ABORTED = 1,
TXN_COMMITTED = 2,
TXN_PREPARED = 3,
TXN_RUNNING = 4,
}
[StructLayout(LayoutKind.Sequential)]
internal struct DB_TXN_ACTIVE {
internal uint txnid;
internal uint parentid;
internal int pid;
internal uint tid;
internal DB_LSN_STRUCT lsn;
internal DB_LSN_STRUCT read_lsn;
internal uint mvcc_ref;
internal uint priority;
internal DB_TXN_ACTIVE_STATUS status;
}
internal struct TxnStatStruct {
internal TransactionStatStruct st;
internal DB_TXN_ACTIVE[] st_txnarray;
internal byte[][] st_txngids;
internal string[] st_txnnames;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Rhapsody.Properties;
using Rhapsody.Utilities;
namespace Rhapsody.Core
{
internal class Album
{
private Context _context;
private Session _session;
public event EventHandler ArtistNameChanged;
public event EventHandler NameChanged;
public event EventHandler YearChanged;
public event EventHandler TypeChanged;
public event EventHandler CoverChanged;
public string ArtistName
{
get;
set;
}
public string ArtistDirectoryName
{
get
{
return StringHelper.MakeFileSystemFriendly(ArtistName);
}
}
public string Name
{
get;
set;
}
public string FullName
{
get
{
var fullName = Name;
var marks = GetMarksString();
if (marks != null)
fullName += " " + marks;
return fullName;
}
}
public string AlbumDirectoryName
{
get
{
var albumDirectoryName = string.Format("{0} - {1}", ReleaseYear, StringHelper.MakeFileSystemFriendly(Name));
var marks = GetMarksString();
if (marks != null)
albumDirectoryName += " " + marks;
return albumDirectoryName;
}
}
public DirectoryInfo AlbumDirectory
{
get;
private set;
}
public string ReleaseYear
{
get;
set;
}
public string Type
{
get;
set;
}
public Picture Cover
{
get;
set;
}
public List<Disc> Discs
{
get;
private set;
}
public DirectoryInfo SourceDirectory
{
get;
private set;
}
public FileInfo PlaylistFile
{
get;
private set;
}
public bool AreFilesDamaged
{
get
{
return Discs.SelectMany(disc => disc.Tracks).Any(track => !track.IsMpegDataValid);
}
}
public bool AreFilesOfLowQuality
{
get
{
return Discs.SelectMany(disc => disc.Tracks).Any(track => track.MpegFileInfo.Exists && (!track.IsAudioVersionValid || !track.IsLayerValid || !track.IsBitrateValid || !track.IsSampleRateValid || !track.IsChannelModeValid));
}
}
public bool AreFilesInconsistent
{
get
{
return !Discs.SelectMany(disc => disc.Tracks).AllEqual(track => track.MpegFileInfo.Exists ? string.Format("{0}/{1}/{2}/{3}/{4}", track.MpegFileInfo.AudioVersion, track.MpegFileInfo.Layer, track.MpegFileInfo.IsVbr ? -1 : track.MpegFileInfo.Bitrate, track.MpegFileInfo.SampleRate, track.MpegFileInfo.ChannelMode) : string.Empty);
}
}
public TimeSpan Duration
{
get
{
return Discs.Aggregate(TimeSpan.Zero, (current, disc) => current + disc.Duration);
}
}
private Album()
{
Discs = new List<Disc>();
}
private Album(Session session, Context context) : this()
{
_session = session;
_context = context;
}
public Album(DirectoryInfo sourceDirectory, IProgress progress, CancellationToken cancellationToken, Session session, Context context) : this(session, context)
{
var discDirectories = new List<DirectoryInfo>();
discDirectories.Add(sourceDirectory);
discDirectories.AddRange(sourceDirectory.GetDirectories());
progress.Begin(discDirectories.Sum(directory => directory.GetFiles("*.mp3").Length));
foreach (var directory in discDirectories)
{
var disc = new Disc(this, _session, _context);
foreach (var file in directory.GetFiles("*.mp3"))
{
cancellationToken.ThrowIfCancellationRequested();
progress.Advance(file.Name);
var track = new Track(file, disc, _session, _context);
disc.Tracks.Add(track);
}
if (disc.Tracks.Count > 0)
Discs.Add(disc);
}
SourceDirectory = sourceDirectory;
}
public bool Validate()
{
if (string.IsNullOrEmpty(ArtistName))
return false;
if (string.IsNullOrEmpty(Name))
return false;
if (string.IsNullOrEmpty(ReleaseYear))
return false;
if (!StringHelper.IsValidYear(ReleaseYear))
return false;
if (Discs.Count == 0)
return false;
foreach (var disc in Discs)
{
if (disc.Tracks.Count == 0)
return false;
foreach (var track in disc.Tracks)
if (string.IsNullOrEmpty(track.Name))
return false;
}
return true;
}
public IEnumerable<Issue> DetectIssues(IProgress progress, CancellationToken cancellationToken)
{
progress.Begin(2 + Discs.Sum(disc => disc.Tracks.Count + 1)); // Artist Name + Album Name + (Disk Name + Track Count)*
progress.Advance(string.Format("Artist: {0}", ArtistName));
foreach (var validator in _context.GetArtistValidators(this))
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var issue in validator.Validate())
yield return issue;
}
progress.Advance(string.Format("Album: {0}", Name));
foreach (var validator in _context.GetAlbumValidators(this))
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var issue in validator.Validate())
yield return issue;
}
foreach (var disc in Discs)
{
progress.Advance(string.Format("Disc {0} Name: {1}", disc.Index, Name));
foreach (var validator in _context.GetDiscValidators(disc))
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var issue in validator.Validate())
yield return issue;
}
foreach (var track in disc.Tracks)
{
progress.Advance(string.Format(@"Disc {0}\Track {1}: {2}", disc.Index, track.Index, Name));
foreach (var validator in _context.GetTrackValidators(track))
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var issue in validator.Validate())
yield return issue;
}
}
}
}
public void SaveTo(DirectoryInfo destinationDirectory, IProgress progress, CancellationToken cancellationToken)
{
progress.Begin(Discs.Sum(disc => disc.Tracks.Count));
if (!destinationDirectory.Exists)
destinationDirectory.Create();
var artistDirectory = destinationDirectory.CreateSubdirectory(ArtistDirectoryName);
if (artistDirectory.GetDirectories(AlbumDirectoryName).Length != 0)
throw new Exception("Album directory exists!");
var albumDirectory = artistDirectory.CreateSubdirectory(AlbumDirectoryName);
foreach (var disc in Discs)
disc.SaveTo(albumDirectory, progress, cancellationToken);
GeneratePlaylist(albumDirectory);
AlbumDirectory = albumDirectory;
}
private void GeneratePlaylist(DirectoryInfo albumDirectory)
{
if (Settings.Default.NoPlaylist)
return;
var filename = Path.Combine(albumDirectory.FullName, string.Format("@ {0} ({1}).m3u", StringHelper.MakeFileSystemFriendly(Name), ReleaseYear));
using (Stream stream = File.Open(filename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using (var writer = new StreamWriter(stream))
{
writer.WriteLine("#EXTM3U");
foreach (var disc in Discs)
{
foreach (var track in disc.Tracks)
{
writer.WriteLine("#EXTINF:{0},{1} - {2}", track.MpegFileInfo.Duration.TotalSeconds, ArtistName, track.Name);
if (Discs.Count == 1)
writer.WriteLine(string.Format(@"{0}", track.FileName));
else
writer.WriteLine(string.Format(@"{0}\{1}", disc.DirectoryName, track.FileName));
}
}
}
}
PlaylistFile = new FileInfo(filename);
}
private string GetMarksString()
{
var marks = string.Join(" ", GetMarks().Select(mark => string.Format("[{0}]", mark)).ToArray());
if (marks.Length == 0)
return null;
return marks;
}
private IEnumerable<string> GetMarks()
{
if (!string.IsNullOrEmpty(Type))
yield return Type;
if ((AreFilesDamaged || AreFilesInconsistent || AreFilesOfLowQuality) && Settings.Default.MarkDamagedAlbums)
yield return "Damaged";
}
public void OnArtistNameChanged()
{
if (ArtistNameChanged != null)
ArtistNameChanged(this, EventArgs.Empty);
}
public void OnNameChanged()
{
if (NameChanged != null)
NameChanged(this, EventArgs.Empty);
}
public void OnYearChanged()
{
if (YearChanged != null)
YearChanged(this, EventArgs.Empty);
}
public void OnTypeChanged()
{
if (TypeChanged != null)
TypeChanged(this, EventArgs.Empty);
}
public void OnCoverChanged()
{
if (CoverChanged != null)
CoverChanged(this, EventArgs.Empty);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="AdGroupAudienceViewServiceClient"/> instances.</summary>
public sealed partial class AdGroupAudienceViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupAudienceViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupAudienceViewServiceSettings"/>.</returns>
public static AdGroupAudienceViewServiceSettings GetDefault() => new AdGroupAudienceViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="AdGroupAudienceViewServiceSettings"/> object with default settings.
/// </summary>
public AdGroupAudienceViewServiceSettings()
{
}
private AdGroupAudienceViewServiceSettings(AdGroupAudienceViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdGroupAudienceViewSettings = existing.GetAdGroupAudienceViewSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupAudienceViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupAudienceViewServiceClient.GetAdGroupAudienceView</c> and
/// <c>AdGroupAudienceViewServiceClient.GetAdGroupAudienceViewAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAdGroupAudienceViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdGroupAudienceViewServiceSettings"/> object.</returns>
public AdGroupAudienceViewServiceSettings Clone() => new AdGroupAudienceViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupAudienceViewServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AdGroupAudienceViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupAudienceViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupAudienceViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupAudienceViewServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupAudienceViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupAudienceViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupAudienceViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupAudienceViewServiceClient Build()
{
AdGroupAudienceViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupAudienceViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupAudienceViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupAudienceViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupAudienceViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupAudienceViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupAudienceViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupAudienceViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupAudienceViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupAudienceViewServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdGroupAudienceViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group audience views.
/// </remarks>
public abstract partial class AdGroupAudienceViewServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupAudienceViewService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdGroupAudienceViewService scopes.</summary>
/// <remarks>
/// The default AdGroupAudienceViewService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdGroupAudienceViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupAudienceViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupAudienceViewServiceClient"/>.</returns>
public static stt::Task<AdGroupAudienceViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupAudienceViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupAudienceViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupAudienceViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupAudienceViewServiceClient"/>.</returns>
public static AdGroupAudienceViewServiceClient Create() => new AdGroupAudienceViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupAudienceViewServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdGroupAudienceViewServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupAudienceViewServiceClient"/>.</returns>
internal static AdGroupAudienceViewServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupAudienceViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupAudienceViewService.AdGroupAudienceViewServiceClient grpcClient = new AdGroupAudienceViewService.AdGroupAudienceViewServiceClient(callInvoker);
return new AdGroupAudienceViewServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdGroupAudienceViewService client</summary>
public virtual AdGroupAudienceViewService.AdGroupAudienceViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAudienceView GetAdGroupAudienceView(GetAdGroupAudienceViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAudienceView> GetAdGroupAudienceViewAsync(GetAdGroupAudienceViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAudienceView> GetAdGroupAudienceViewAsync(GetAdGroupAudienceViewRequest request, st::CancellationToken cancellationToken) =>
GetAdGroupAudienceViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group audience view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAudienceView GetAdGroupAudienceView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAudienceView(new GetAdGroupAudienceViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group audience view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAudienceView> GetAdGroupAudienceViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAudienceViewAsync(new GetAdGroupAudienceViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group audience view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAudienceView> GetAdGroupAudienceViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAudienceViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group audience view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAudienceView GetAdGroupAudienceView(gagvr::AdGroupAudienceViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAudienceView(new GetAdGroupAudienceViewRequest
{
ResourceNameAsAdGroupAudienceViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group audience view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAudienceView> GetAdGroupAudienceViewAsync(gagvr::AdGroupAudienceViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAudienceViewAsync(new GetAdGroupAudienceViewRequest
{
ResourceNameAsAdGroupAudienceViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group audience view to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAudienceView> GetAdGroupAudienceViewAsync(gagvr::AdGroupAudienceViewName resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAudienceViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupAudienceViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group audience views.
/// </remarks>
public sealed partial class AdGroupAudienceViewServiceClientImpl : AdGroupAudienceViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdGroupAudienceViewRequest, gagvr::AdGroupAudienceView> _callGetAdGroupAudienceView;
/// <summary>
/// Constructs a client wrapper for the AdGroupAudienceViewService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="AdGroupAudienceViewServiceSettings"/> used within this client.
/// </param>
public AdGroupAudienceViewServiceClientImpl(AdGroupAudienceViewService.AdGroupAudienceViewServiceClient grpcClient, AdGroupAudienceViewServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupAudienceViewServiceSettings effectiveSettings = settings ?? AdGroupAudienceViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdGroupAudienceView = clientHelper.BuildApiCall<GetAdGroupAudienceViewRequest, gagvr::AdGroupAudienceView>(grpcClient.GetAdGroupAudienceViewAsync, grpcClient.GetAdGroupAudienceView, effectiveSettings.GetAdGroupAudienceViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdGroupAudienceView);
Modify_GetAdGroupAudienceViewApiCall(ref _callGetAdGroupAudienceView);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAdGroupAudienceViewApiCall(ref gaxgrpc::ApiCall<GetAdGroupAudienceViewRequest, gagvr::AdGroupAudienceView> call);
partial void OnConstruction(AdGroupAudienceViewService.AdGroupAudienceViewServiceClient grpcClient, AdGroupAudienceViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupAudienceViewService client</summary>
public override AdGroupAudienceViewService.AdGroupAudienceViewServiceClient GrpcClient { get; }
partial void Modify_GetAdGroupAudienceViewRequest(ref GetAdGroupAudienceViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AdGroupAudienceView GetAdGroupAudienceView(GetAdGroupAudienceViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupAudienceViewRequest(ref request, ref callSettings);
return _callGetAdGroupAudienceView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested ad group audience view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AdGroupAudienceView> GetAdGroupAudienceViewAsync(GetAdGroupAudienceViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupAudienceViewRequest(ref request, ref callSettings);
return _callGetAdGroupAudienceView.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using LoginViewComponent.Data;
namespace LoginViewComponent.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc3")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("LoginViewComponent.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("LoginViewComponent.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("LoginViewComponent.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("LoginViewComponent.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Parameters;
namespace ChainUtils.BouncyCastle.Crypto.Engines
{
/**
* The specification for RC5 came from the <code>RC5 Encryption Algorithm</code>
* publication in RSA CryptoBytes, Spring of 1995.
* <em>http://www.rsasecurity.com/rsalabs/cryptobytes</em>.
* <p>
* This implementation is set to work with a 64 bit word size.</p>
*/
public class RC564Engine
: IBlockCipher
{
private static readonly int wordSize = 64;
private static readonly int bytesPerWord = wordSize / 8;
/*
* the number of rounds to perform
*/
private int _noRounds;
/*
* the expanded key array of size 2*(rounds + 1)
*/
private long [] _S;
/*
* our "magic constants" for wordSize 62
*
* Pw = Odd((e-2) * 2^wordsize)
* Qw = Odd((o-2) * 2^wordsize)
*
* where e is the base of natural logarithms (2.718281828...)
* and o is the golden ratio (1.61803398...)
*/
private static readonly long P64 = unchecked( (long) 0xb7e151628aed2a6bL);
private static readonly long Q64 = unchecked( (long) 0x9e3779b97f4a7c15L);
private bool forEncryption;
/**
* Create an instance of the RC5 encryption algorithm
* and set some defaults
*/
public RC564Engine()
{
_noRounds = 12;
// _S = null;
}
public string AlgorithmName
{
get { return "RC5-64"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return 2 * bytesPerWord;
}
/**
* initialise a RC5-64 cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(typeof(RC5Parameters).IsInstanceOfType(parameters)))
{
throw new ArgumentException("invalid parameter passed to RC564 init - " + parameters.GetType().ToString());
}
var p = (RC5Parameters)parameters;
this.forEncryption = forEncryption;
_noRounds = p.Rounds;
SetKey(p.GetKey());
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
return (forEncryption) ? EncryptBlock(input, inOff, output, outOff)
: DecryptBlock(input, inOff, output, outOff);
}
public void Reset()
{
}
/**
* Re-key the cipher.
*
* @param key the key to be used
*/
private void SetKey(
byte[] key)
{
//
// KEY EXPANSION:
//
// There are 3 phases to the key expansion.
//
// Phase 1:
// Copy the secret key K[0...b-1] into an array L[0..c-1] of
// c = ceil(b/u), where u = wordSize/8 in little-endian order.
// In other words, we fill up L using u consecutive key bytes
// of K. Any unfilled byte positions in L are zeroed. In the
// case that b = c = 0, set c = 1 and L[0] = 0.
//
var L = new long[(key.Length + (bytesPerWord - 1)) / bytesPerWord];
for (var i = 0; i != key.Length; i++)
{
L[i / bytesPerWord] += (long)(key[i] & 0xff) << (8 * (i % bytesPerWord));
}
//
// Phase 2:
// Initialize S to a particular fixed pseudo-random bit pattern
// using an arithmetic progression modulo 2^wordsize determined
// by the magic numbers, Pw & Qw.
//
_S = new long[2*(_noRounds + 1)];
_S[0] = P64;
for (var i=1; i < _S.Length; i++)
{
_S[i] = (_S[i-1] + Q64);
}
//
// Phase 3:
// Mix in the user's secret key in 3 passes over the arrays S & L.
// The max of the arrays sizes is used as the loop control
//
int iter;
if (L.Length > _S.Length)
{
iter = 3 * L.Length;
}
else
{
iter = 3 * _S.Length;
}
long A = 0, B = 0;
int ii = 0, jj = 0;
for (var k = 0; k < iter; k++)
{
A = _S[ii] = RotateLeft(_S[ii] + A + B, 3);
B = L[jj] = RotateLeft( L[jj] + A + B, A+B);
ii = (ii+1) % _S.Length;
jj = (jj+1) % L.Length;
}
}
/**
* Encrypt the given block starting at the given offset and place
* the result in the provided buffer starting at the given offset.
*
* @param in in byte buffer containing data to encrypt
* @param inOff offset into src buffer
* @param out out buffer where encrypted data is written
* @param outOff offset into out buffer
*/
private int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
var A = BytesToWord(input, inOff) + _S[0];
var B = BytesToWord(input, inOff + bytesPerWord) + _S[1];
for (var i = 1; i <= _noRounds; i++)
{
A = RotateLeft(A ^ B, B) + _S[2*i];
B = RotateLeft(B ^ A, A) + _S[2*i+1];
}
WordToBytes(A, outBytes, outOff);
WordToBytes(B, outBytes, outOff + bytesPerWord);
return 2 * bytesPerWord;
}
private int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
var A = BytesToWord(input, inOff);
var B = BytesToWord(input, inOff + bytesPerWord);
for (var i = _noRounds; i >= 1; i--)
{
B = RotateRight(B - _S[2*i+1], A) ^ A;
A = RotateRight(A - _S[2*i], B) ^ B;
}
WordToBytes(A - _S[0], outBytes, outOff);
WordToBytes(B - _S[1], outBytes, outOff + bytesPerWord);
return 2 * bytesPerWord;
}
//////////////////////////////////////////////////////////////
//
// PRIVATE Helper Methods
//
//////////////////////////////////////////////////////////////
/**
* Perform a left "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(wordSize)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % wordSize
*/
private long RotateLeft(long x, long y) {
return ((long) ( (ulong) (x << (int) (y & (wordSize-1))) |
((ulong) x >> (int) (wordSize - (y & (wordSize-1)))))
);
}
/**
* Perform a right "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(wordSize)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % wordSize
*/
private long RotateRight(long x, long y) {
return ((long) ( ((ulong) x >> (int) (y & (wordSize-1))) |
(ulong) (x << (int) (wordSize - (y & (wordSize-1)))))
);
}
private long BytesToWord(
byte[] src,
int srcOff)
{
long word = 0;
for (var i = bytesPerWord - 1; i >= 0; i--)
{
word = (word << 8) + (src[i + srcOff] & 0xff);
}
return word;
}
private void WordToBytes(
long word,
byte[] dst,
int dstOff)
{
for (var i = 0; i < bytesPerWord; i++)
{
dst[i + dstOff] = (byte)word;
word = (long) ((ulong) word >> 8);
}
}
}
}
| |
//
// assembly: System
// namespace: System.Text.RegularExpressions
// file: compiler.cs
//
// author: Dan Lewis ([email protected])
// (c) 2002
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
namespace System.Text.RegularExpressions {
abstract class LinkRef {
// empty
}
interface ICompiler {
void Reset ();
IMachineFactory GetMachineFactory ();
// instruction emission
void EmitFalse ();
void EmitTrue ();
// character matching
void EmitCharacter (char c, bool negate, bool ignore, bool reverse);
void EmitCategory (Category cat, bool negate, bool reverse);
void EmitRange (char lo, char hi, bool negate, bool ignore, bool reverse);
void EmitSet (char lo, BitArray set, bool negate, bool ignore, bool reverse);
// other operators
void EmitString (string str, bool ignore, bool reverse);
void EmitPosition (Position pos);
void EmitOpen (int gid);
void EmitClose (int gid);
void EmitBalanceStart(int gid, int balance, bool capture, LinkRef tail);
void EmitBalance ();
void EmitReference (int gid, bool ignore, bool reverse);
// constructs
void EmitIfDefined (int gid, LinkRef tail);
void EmitSub (LinkRef tail);
void EmitTest (LinkRef yes, LinkRef tail);
void EmitBranch (LinkRef next);
void EmitJump (LinkRef target);
void EmitRepeat (int min, int max, bool lazy, LinkRef until);
void EmitUntil (LinkRef repeat);
void EmitIn (LinkRef tail);
void EmitInfo (int count, int min, int max);
void EmitFastRepeat (int min, int max, bool lazy, LinkRef tail);
void EmitAnchor (bool reverse, int offset, LinkRef tail);
// event for the CILCompiler
void EmitBranchEnd();
void EmitAlternationEnd();
LinkRef NewLink ();
void ResolveLink (LinkRef link);
}
class InterpreterFactory : IMachineFactory {
public InterpreterFactory (ushort[] pattern) {
this.pattern = pattern;
}
public IMachine NewInstance () {
return new Interpreter (pattern);
}
public int GroupCount {
get { return pattern[1]; }
}
public IDictionary Mapping {
get { return mapping; }
set { mapping = value; }
}
private IDictionary mapping;
private ushort[] pattern;
}
class PatternCompiler : ICompiler {
public static ushort EncodeOp (OpCode op, OpFlags flags) {
return (ushort)((int)op | ((int)flags & 0xff00));
}
public static void DecodeOp (ushort word, out OpCode op, out OpFlags flags) {
op = (OpCode)(word & 0x00ff);
flags = (OpFlags)(word & 0xff00);
}
public PatternCompiler () {
pgm = new ArrayList ();
}
// ICompiler implementation
public void Reset () {
pgm.Clear ();
}
public IMachineFactory GetMachineFactory () {
ushort[] image = new ushort[pgm.Count];
pgm.CopyTo (image);
return new InterpreterFactory (image);
}
public void EmitFalse () {
Emit (OpCode.False);
}
public void EmitTrue () {
Emit (OpCode.True);
}
public void EmitCharacter (char c, bool negate, bool ignore, bool reverse) {
Emit (OpCode.Character, MakeFlags (negate, ignore, reverse, false));
if (ignore)
c = Char.ToLower (c);
Emit ((ushort)c);
}
public void EmitCategory (Category cat, bool negate, bool reverse) {
Emit (OpCode.Category, MakeFlags (negate, false, reverse, false));
Emit ((ushort)cat);
}
public void EmitRange (char lo, char hi, bool negate, bool ignore, bool reverse) {
Emit (OpCode.Range, MakeFlags (negate, ignore, reverse, false));
Emit ((ushort)lo);
Emit ((ushort)hi);
}
public void EmitSet (char lo, BitArray set, bool negate, bool ignore, bool reverse) {
Emit (OpCode.Set, MakeFlags (negate, ignore, reverse, false));
Emit ((ushort)lo);
int len = (set.Length + 0xf) >> 4;
Emit ((ushort)len);
int b = 0;
while (len -- != 0) {
ushort word = 0;
for (int i = 0; i < 16; ++ i) {
if (b >= set.Length)
break;
/* use BitArray.Get instead of indexer for speedup
if (set[b ++])
word |= (ushort)(1 << i);
*/
if (set.Get(b ++))
word |= (ushort)(1 << i);
}
Emit (word);
}
}
public void EmitString (string str, bool ignore, bool reverse) {
Emit (OpCode.String, MakeFlags (false, ignore, reverse, false));
int len = str.Length;
Emit ((ushort)len);
if (ignore)
str = str.ToLower ();
for (int i = 0; i < len; ++ i)
Emit ((ushort)str[i]);
}
public void EmitPosition (Position pos) {
Emit (OpCode.Position, 0);
Emit ((ushort)pos);
}
public void EmitOpen (int gid) {
Emit (OpCode.Open);
Emit ((ushort)gid);
}
public void EmitClose (int gid) {
Emit (OpCode.Close);
Emit ((ushort)gid);
}
public void EmitBalanceStart (int gid, int balance, bool capture, LinkRef tail) {
BeginLink (tail);
Emit (OpCode.BalanceStart);
Emit ((ushort)gid);
Emit ((ushort)balance);
Emit ((ushort)(capture ? 1 : 0));
EmitLink (tail);
}
public void EmitBalance () {
Emit (OpCode.Balance);
}
public void EmitReference (int gid, bool ignore, bool reverse) {
Emit (OpCode.Reference, MakeFlags (false, ignore, reverse, false));
Emit ((ushort)gid);
}
public void EmitIfDefined (int gid, LinkRef tail) {
BeginLink (tail);
Emit (OpCode.IfDefined);
EmitLink (tail);
Emit ((ushort)gid);
}
public void EmitSub (LinkRef tail) {
BeginLink (tail);
Emit (OpCode.Sub);
EmitLink (tail);
}
public void EmitTest (LinkRef yes, LinkRef tail) {
BeginLink (yes);
BeginLink (tail);
Emit (OpCode.Test);
EmitLink (yes);
EmitLink (tail);
}
public void EmitBranch (LinkRef next) {
BeginLink (next);
Emit (OpCode.Branch, 0);
EmitLink (next);
}
public void EmitJump (LinkRef target) {
BeginLink (target);
Emit (OpCode.Jump, 0);
EmitLink (target);
}
public void EmitRepeat (int min, int max, bool lazy, LinkRef until) {
BeginLink (until);
Emit (OpCode.Repeat, MakeFlags (false, false, false, lazy));
EmitLink (until);
Emit ((ushort)min);
Emit ((ushort)max);
}
public void EmitUntil (LinkRef repeat) {
ResolveLink (repeat);
Emit (OpCode.Until);
}
public void EmitFastRepeat (int min, int max, bool lazy, LinkRef tail) {
BeginLink (tail);
Emit (OpCode.FastRepeat, MakeFlags (false, false, false, lazy));
EmitLink (tail);
Emit ((ushort)min);
Emit ((ushort)max);
}
public void EmitIn (LinkRef tail) {
BeginLink (tail);
Emit (OpCode.In);
EmitLink (tail);
}
public void EmitAnchor (bool reverse, int offset, LinkRef tail) {
BeginLink (tail);
Emit (OpCode.Anchor, MakeFlags(false, false, reverse, false));
EmitLink (tail);
Emit ((ushort)offset);
}
public void EmitInfo (int count, int min, int max) {
Emit (OpCode.Info);
Emit ((ushort)count);
Emit ((ushort)min);
Emit ((ushort)max);
}
public LinkRef NewLink () {
return new PatternLinkStack ();
}
public void ResolveLink (LinkRef lref) {
PatternLinkStack stack = (PatternLinkStack)lref;
while (stack.Pop ())
pgm[stack.OffsetAddress] = (ushort)stack.GetOffset (CurrentAddress);
}
public void EmitBranchEnd(){}
public void EmitAlternationEnd(){}
// private members
private static OpFlags MakeFlags (bool negate, bool ignore, bool reverse, bool lazy) {
OpFlags flags = 0;
if (negate) flags |= OpFlags.Negate;
if (ignore) flags |= OpFlags.IgnoreCase;
if (reverse) flags |= OpFlags.RightToLeft;
if (lazy) flags |= OpFlags.Lazy;
return flags;
}
private void Emit (OpCode op) {
Emit (op, (OpFlags)0);
}
private void Emit (OpCode op, OpFlags flags) {
Emit (EncodeOp (op, flags));
}
private void Emit (ushort word) {
pgm.Add (word);
}
private int CurrentAddress {
get { return pgm.Count; }
}
private void BeginLink (LinkRef lref) {
PatternLinkStack stack = (PatternLinkStack)lref;
stack.BaseAddress = CurrentAddress;
}
private void EmitLink (LinkRef lref) {
PatternLinkStack stack = (PatternLinkStack)lref;
stack.OffsetAddress = CurrentAddress;
Emit ((ushort)0); // placeholder
stack.Push ();
}
private class PatternLinkStack : LinkStack {
public PatternLinkStack () {
}
public int BaseAddress {
set { link.base_addr = value; }
}
public int OffsetAddress {
get { return link.offset_addr; }
set { link.offset_addr = value; }
}
public int GetOffset (int target_addr) {
return target_addr - link.base_addr;
}
// LinkStack implementation
protected override object GetCurrent () { return link; }
protected override void SetCurrent (object l) { link = (Link)l; }
private struct Link {
public int base_addr;
public int offset_addr;
}
Link link;
}
private ArrayList pgm;
}
abstract class LinkStack : LinkRef {
public LinkStack () {
stack = new Stack ();
}
public void Push () {
stack.Push (GetCurrent ());
}
public bool Pop () {
if (stack.Count > 0) {
SetCurrent (stack.Pop ());
return true;
}
return false;
}
protected abstract object GetCurrent ();
protected abstract void SetCurrent (object l);
private Stack stack;
}
//Used by CILCompiler and Interpreter
internal struct Mark {
public int Start, End;
public int Previous;
public bool IsDefined {
get { return Start >= 0 && End >= 0; }
}
public int Index {
get { return Start < End ? Start : End; }
}
public int Length {
get { return Start < End ? End - Start : Start - End; }
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// This class implements a Finite State Machine (FSM) to control the remote connection on the server side.
/// There is a similar but not identical FSM on the client side for this connection.
///
/// The FSM's states and events are defined to be the same for both the client FSM and the server FSM.
/// This design allows the client and server FSM's to
/// be as similar as possible, so that the complexity of maintaining them is minimized.
///
/// This FSM only controls the remote connection state. States related to runspace and pipeline are managed by runspace
/// pipeline themselves.
///
/// This FSM defines an event handling matrix, which is filled by the event handlers.
/// The state transitions can only be performed by these event handlers, which are private
/// to this class. The event handling is done by a single thread, which makes this
/// implementation solid and thread safe.
///
/// This implementation of the FSM does not allow the remote session to be reused for a connection
/// after it is been closed. This design decision is made to simplify the implementation.
/// However, the design can be easily modified to allow the reuse of the remote session
/// to reconnect after the connection is closed.
/// </summary>
internal class ServerRemoteSessionDSHandlerStateMachine
{
[TraceSourceAttribute("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine")]
private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine");
private readonly ServerRemoteSession _session;
private readonly object _syncObject;
private readonly Queue<RemoteSessionStateMachineEventArgs> _processPendingEventsQueue
= new Queue<RemoteSessionStateMachineEventArgs>();
// whether some thread is actively processing events
// in a loop. If this is set then other threads
// should simply add to the queue and not attempt
// at processing the events in the queue. This will
// guarantee that events will always be serialized
// and processed
private bool _eventsInProcess = false;
private readonly EventHandler<RemoteSessionStateMachineEventArgs>[,] _stateMachineHandle;
private RemoteSessionState _state;
/// <summary>
/// Timer used for key exchange.
/// </summary>
private Timer _keyExchangeTimer;
#region Constructors
/// <summary>
/// This constructor instantiates a FSM object for the server side to control the remote connection.
/// It initializes the event handling matrix with event handlers.
/// It sets the initial state of the FSM to be Idle.
/// </summary>
/// <param name="session">
/// This is the remote session object.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
internal ServerRemoteSessionDSHandlerStateMachine(ServerRemoteSession session)
{
if (session == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(session));
}
_session = session;
_syncObject = new object();
_stateMachineHandle = new EventHandler<RemoteSessionStateMachineEventArgs>[(int)RemoteSessionState.MaxState, (int)RemoteSessionEvent.MaxEvent];
for (int i = 0; i < _stateMachineHandle.GetLength(0); i++)
{
_stateMachineHandle[i, (int)RemoteSessionEvent.FatalError] += DoFatalError;
_stateMachineHandle[i, (int)RemoteSessionEvent.Close] += DoClose;
_stateMachineHandle[i, (int)RemoteSessionEvent.CloseFailed] += DoCloseFailed;
_stateMachineHandle[i, (int)RemoteSessionEvent.CloseCompleted] += DoCloseCompleted;
_stateMachineHandle[i, (int)RemoteSessionEvent.NegotiationTimeout] += DoNegotiationTimeout;
_stateMachineHandle[i, (int)RemoteSessionEvent.SendFailed] += DoSendFailed;
_stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += DoReceiveFailed;
_stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnect;
}
_stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.CreateSession] += DoCreateSession;
_stateMachineHandle[(int)RemoteSessionState.NegotiationPending, (int)RemoteSessionEvent.NegotiationReceived] += DoNegotiationReceived;
_stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationSending] += DoNegotiationSending;
_stateMachineHandle[(int)RemoteSessionState.NegotiationSending, (int)RemoteSessionEvent.NegotiationSendCompleted] += DoNegotiationCompleted;
_stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationCompleted] += DoEstablished;
_stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationPending] += DoNegotiationPending;
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.MessageReceived] += DoMessageReceived;
_stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationFailed] += DoNegotiationFailed;
_stateMachineHandle[(int)RemoteSessionState.Connecting, (int)RemoteSessionEvent.ConnectFailed] += DoConnectFailed;
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySent] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyReceived, (int)RemoteSessionEvent.KeySendFailed] += DoKeyExchange;
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyReceived, (int)RemoteSessionEvent.KeySent] += DoKeyExchange;
// with connect, a new client can negotiate a key change to a server that has already negotiated key exchange with a previous client
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; //
for (int i = 0; i < _stateMachineHandle.GetLength(0); i++)
{
for (int j = 0; j < _stateMachineHandle.GetLength(1); j++)
{
if (_stateMachineHandle[i, j] == null)
{
_stateMachineHandle[i, j] += DoClose;
}
}
}
// Initially, set state to Idle
SetState(RemoteSessionState.Idle, null);
}
#endregion Constructors
/// <summary>
/// This is a readonly property available to all other classes. It gives the FSM state.
/// Other classes can query for this state. Only the FSM itself can change the state.
/// </summary>
internal RemoteSessionState State
{
get
{
return _state;
}
}
/// <summary>
/// Helper method used by dependents to figure out if the RaiseEvent
/// method can be short-circuited. This will be useful in cases where
/// the dependent code wants to take action immediately instead of
/// going through state machine.
/// </summary>
/// <param name="arg"></param>
internal bool CanByPassRaiseEvent(RemoteSessionStateMachineEventArgs arg)
{
if (arg.StateEvent == RemoteSessionEvent.MessageReceived)
{
if (_state == RemoteSessionState.Established ||
_state == RemoteSessionState.EstablishedAndKeySent || // server session will never be in this state.. TODO- remove this
_state == RemoteSessionState.EstablishedAndKeyReceived ||
_state == RemoteSessionState.EstablishedAndKeyExchanged)
{
return true;
}
}
return false;
}
/// <summary>
/// This method is used by all classes to raise a FSM event.
/// The method will queue the event. The event queue will be handled in
/// a thread safe manner by a single dedicated thread.
/// </summary>
/// <param name="fsmEventArg">
/// This parameter contains the event to be raised.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
internal void RaiseEvent(RemoteSessionStateMachineEventArgs fsmEventArg)
{
// make sure only one thread is processing events.
lock (_syncObject)
{
s_trace.WriteLine("Event received : {0}", fsmEventArg.StateEvent);
_processPendingEventsQueue.Enqueue(fsmEventArg);
if (_eventsInProcess)
{
return;
}
_eventsInProcess = true;
}
ProcessEvents();
// currently server state machine doesn't raise events
// this will allow server state machine to raise events.
// RaiseStateMachineEvents();
}
/// <summary>
/// Processes events in the queue. If there are no
/// more events to process, then sets eventsInProcess
/// variable to false. This will ensure that another
/// thread which raises an event can then take control
/// of processing the events.
/// </summary>
private void ProcessEvents()
{
RemoteSessionStateMachineEventArgs eventArgs = null;
do
{
lock (_syncObject)
{
if (_processPendingEventsQueue.Count == 0)
{
_eventsInProcess = false;
break;
}
eventArgs = _processPendingEventsQueue.Dequeue();
}
RaiseEventPrivate(eventArgs);
} while (_eventsInProcess);
}
/// <summary>
/// This is the private version of raising a FSM event.
/// It can only be called by the dedicated thread that processes the event queue.
/// It calls the event handler
/// in the right position of the event handling matrix.
/// </summary>
/// <param name="fsmEventArg">
/// The parameter contains the actual FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs fsmEventArg)
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
EventHandler<RemoteSessionStateMachineEventArgs> handler = _stateMachineHandle[(int)_state, (int)fsmEventArg.StateEvent];
if (handler != null)
{
s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent);
handler(this, fsmEventArg);
s_trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent);
}
}
#region Event Handlers
/// <summary>
/// This is the handler for Start event of the FSM. This is the beginning of everything
/// else. From this moment on, the FSM will proceeds step by step to eventually reach
/// Established state or Closed state.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CreateSession, "StateEvent must be CreateSession");
Dbg.Assert(_state == RemoteSessionState.Idle, "DoCreateSession cannot only be called in Idle state");
DoNegotiationPending(sender, fsmEventArg);
}
}
/// <summary>
/// This is the handler for NegotiationPending event.
/// NegotiationPending state can be in reached in the following cases
/// 1. From Idle to NegotiationPending (during startup)
/// 2. From Negotiation(Response)Sent to NegotiationPending.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationPending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert((_state == RemoteSessionState.Idle) || (_state == RemoteSessionState.NegotiationSent),
"DoNegotiationPending can only occur when the state is Idle or NegotiationSent.");
SetState(RemoteSessionState.NegotiationPending, null);
}
}
/// <summary>
/// This is the handler for the NegotiationReceived event.
/// It sets the new state to be NegotiationReceived.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the parameter <paramref name="fsmEventArg"/> is not NegotiationReceived event or it does not hold the
/// client negotiation packet.
/// </exception>
private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationReceived, "StateEvent must be NegotiationReceived");
Dbg.Assert(fsmEventArg.RemoteSessionCapability != null, "RemoteSessioncapability must be non-null");
Dbg.Assert(_state == RemoteSessionState.NegotiationPending, "state must be in NegotiationPending state");
if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationReceived)
{
throw PSTraceSource.NewArgumentException(nameof(fsmEventArg));
}
if (fsmEventArg.RemoteSessionCapability == null)
{
throw PSTraceSource.NewArgumentException(nameof(fsmEventArg));
}
SetState(RemoteSessionState.NegotiationReceived, null);
}
}
/// <summary>
/// This is the handler for NegotiationSending event.
/// It sets the new state to be NegotiationSending, and sends the server side
/// negotiation packet by queuing it on the output queue.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationSending, "Event must be NegotiationSending");
Dbg.Assert(_state == RemoteSessionState.NegotiationReceived, "State must be NegotiationReceived");
SetState(RemoteSessionState.NegotiationSending, null);
_session.SessionDataStructureHandler.SendNegotiationAsync();
}
/// <summary>
/// This is the handler for NegotiationSendCompleted event.
/// It sets the new state to be NegotiationSent.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationCompleted(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(_state == RemoteSessionState.NegotiationSending, "State must be NegotiationSending");
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationSendCompleted, "StateEvent must be NegotiationSendCompleted");
SetState(RemoteSessionState.NegotiationSent, null);
}
}
/// <summary>
/// This is the handler for the NegotiationCompleted event.
/// It sets the new state to be Established. It turns off the negotiation timeout timer.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoEstablished(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(_state == RemoteSessionState.NegotiationSent, "State must be NegotiationReceived");
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationCompleted, "StateEvent must be NegotiationCompleted");
if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationCompleted)
{
throw PSTraceSource.NewArgumentException(nameof(fsmEventArg));
}
if (_state != RemoteSessionState.NegotiationSent)
{
throw PSTraceSource.NewInvalidOperationException();
}
SetState(RemoteSessionState.Established, null);
}
}
/// <summary>
/// This is the handler for MessageReceived event. It dispatches the data to various components
/// that uses the data.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the parameter <paramref name="fsmEventArg"/> does not contain remote data.
/// </exception>
internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
if (fsmEventArg.RemoteData == null)
{
throw PSTraceSource.NewArgumentException(nameof(fsmEventArg));
}
Dbg.Assert(_state == RemoteSessionState.Established ||
_state == RemoteSessionState.EstablishedAndKeyExchanged ||
_state == RemoteSessionState.EstablishedAndKeyReceived ||
_state == RemoteSessionState.EstablishedAndKeySent, // server session will never be in this state.. TODO- remove this
"State must be Established or EstablishedAndKeySent or EstablishedAndKeyReceived or EstablishedAndKeyExchanged");
RemotingTargetInterface targetInterface = fsmEventArg.RemoteData.TargetInterface;
RemotingDataType dataType = fsmEventArg.RemoteData.DataType;
Guid clientRunspacePoolId;
ServerRunspacePoolDriver runspacePoolDriver;
// string errorMessage = null;
RemoteDataEventArgs remoteDataForSessionArg = null;
switch (targetInterface)
{
case RemotingTargetInterface.Session:
{
switch (dataType)
{
// GETBACK
case RemotingDataType.CreateRunspacePool:
remoteDataForSessionArg = new RemoteDataEventArgs(fsmEventArg.RemoteData);
_session.SessionDataStructureHandler.RaiseDataReceivedEvent(remoteDataForSessionArg);
break;
default:
Dbg.Assert(false, "Should never reach here");
break;
}
}
break;
case RemotingTargetInterface.RunspacePool:
// GETBACK
clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId;
runspacePoolDriver = _session.GetRunspacePoolDriver(clientRunspacePoolId);
if (runspacePoolDriver != null)
{
runspacePoolDriver.DataStructureHandler.ProcessReceivedData(fsmEventArg.RemoteData);
}
else
{
s_trace.WriteLine(@"Server received data for Runspace (id: {0}),
but the Runspace cannot be found", clientRunspacePoolId);
PSRemotingDataStructureException reasonOfFailure = new
PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceCannotBeFound,
clientRunspacePoolId);
RemoteSessionStateMachineEventArgs runspaceNotFoundArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure);
RaiseEvent(runspaceNotFoundArg);
}
break;
case RemotingTargetInterface.PowerShell:
clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId;
runspacePoolDriver = _session.GetRunspacePoolDriver(clientRunspacePoolId);
runspacePoolDriver.DataStructureHandler.DispatchMessageToPowerShell(fsmEventArg.RemoteData);
break;
default:
s_trace.WriteLine("Server received data unknown targetInterface: {0}", targetInterface);
PSRemotingDataStructureException reasonOfFailure2 = new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedRemotingTargetInterfaceType, targetInterface);
RemoteSessionStateMachineEventArgs unknownTargetArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure2);
RaiseEvent(unknownTargetArg);
break;
}
}
}
/// <summary>
/// This is the handler for ConnectFailed event. In this implementation, this should never
/// happen. This is because the IO channel is stdin/stdout/stderr redirection.
/// Therefore, the connection is a dummy operation.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the parameter <paramref name="fsmEventArg"/> does not contain ConnectFailed event.
/// </exception>
private void DoConnectFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ConnectFailed, "StateEvent must be ConnectFailed");
if (fsmEventArg.StateEvent != RemoteSessionEvent.ConnectFailed)
{
throw PSTraceSource.NewArgumentException(nameof(fsmEventArg));
}
Dbg.Assert(_state == RemoteSessionState.Connecting, "session State must be Connecting");
// This method should not be called in this implementation.
throw PSTraceSource.NewInvalidOperationException();
}
}
/// <summary>
/// This is the handler for FatalError event. It directly calls the DoClose, which
/// is the Close event handler.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> does not contains FatalError event.
/// </exception>
private void DoFatalError(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.FatalError, "StateEvent must be FatalError");
if (fsmEventArg.StateEvent != RemoteSessionEvent.FatalError)
{
throw PSTraceSource.NewArgumentException(nameof(fsmEventArg));
}
DoClose(this, fsmEventArg);
}
}
/// <summary>
/// Handle connect event - this is raised when a new client tries to connect to an existing session
/// No changes to state. Calls into the session to handle any post connect operations.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg"></param>
private void DoConnect(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
Dbg.Assert(_state != RemoteSessionState.Idle, "session should not be in idle state when SessionConnect event is queued");
if ((_state != RemoteSessionState.Closed) && (_state != RemoteSessionState.ClosingConnection))
{
_session.HandlePostConnect();
}
}
/// <summary>
/// This is the handler for Close event. It closes the connection.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
RemoteSessionState oldState = _state;
switch (oldState)
{
case RemoteSessionState.ClosingConnection:
case RemoteSessionState.Closed:
// do nothing
break;
case RemoteSessionState.Connecting:
case RemoteSessionState.Connected:
case RemoteSessionState.Established:
case RemoteSessionState.EstablishedAndKeySent: // server session will never be in this state.. TODO- remove this
case RemoteSessionState.EstablishedAndKeyReceived:
case RemoteSessionState.EstablishedAndKeyExchanged:
case RemoteSessionState.NegotiationReceived:
case RemoteSessionState.NegotiationSent:
case RemoteSessionState.NegotiationSending:
SetState(RemoteSessionState.ClosingConnection, fsmEventArg.Reason);
_session.SessionDataStructureHandler.CloseConnectionAsync(fsmEventArg.Reason);
break;
case RemoteSessionState.Idle:
case RemoteSessionState.UndefinedState:
default:
Exception forcedCloseException = new PSRemotingTransportException(fsmEventArg.Reason, RemotingErrorIdStrings.ForceClosed);
SetState(RemoteSessionState.Closed, forcedCloseException);
break;
}
CleanAll();
}
}
/// <summary>
/// This is the handler for CloseFailed event.
/// It simply force the new state to be Closed.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoCloseFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CloseFailed, "StateEvent must be CloseFailed");
RemoteSessionState stateBeforeTransition = _state;
SetState(RemoteSessionState.Closed, fsmEventArg.Reason);
// ignore
CleanAll();
}
}
/// <summary>
/// This is the handler for CloseCompleted event. It sets the new state to be Closed.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoCloseCompleted(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CloseCompleted, "StateEvent must be CloseCompleted");
SetState(RemoteSessionState.Closed, fsmEventArg.Reason);
// Close the session only after changing the state..this way
// state machine will not process anything.
_session.Close(fsmEventArg);
CleanAll();
}
}
/// <summary>
/// This is the handler for NegotiationFailed event.
/// It raises a Close event to trigger the connection to be shutdown.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationFailed, "StateEvent must be NegotiationFailed");
RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close);
RaiseEventPrivate(closeArg);
}
}
/// <summary>
/// This is the handler for NegotiationTimeout event.
/// If the connection is already Established, it ignores this event.
/// Otherwise, it raises a Close event to trigger a close of the connection.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoNegotiationTimeout(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationTimeout, "StateEvent must be NegotiationTimeout");
if (_state == RemoteSessionState.Established)
{
// ignore
return;
}
RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close);
RaiseEventPrivate(closeArg);
}
}
/// <summary>
/// This is the handler for SendFailed event.
/// This is an indication that the wire layer IO is no longer connected. So it raises
/// a Close event to trigger a connection shutdown.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoSendFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.SendFailed, "StateEvent must be SendFailed");
RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close);
RaiseEventPrivate(closeArg);
}
}
/// <summary>
/// This is the handler for ReceivedFailed event.
/// This is an indication that the wire layer IO is no longer connected. So it raises
/// a Close event to trigger a connection shutdown.
/// </summary>
/// <param name="sender"></param>
/// <param name="fsmEventArg">
/// This parameter contains the FSM event.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="fsmEventArg"/> is null.
/// </exception>
private void DoReceiveFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
{
using (s_trace.TraceEventHandlers())
{
if (fsmEventArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg));
}
Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ReceiveFailed, "StateEvent must be ReceivedFailed");
RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close);
RaiseEventPrivate(closeArg);
}
}
/// <summary>
/// This method contains all the logic for handling the state machine
/// for key exchange. All the different scenarios are covered in this.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Event args.</param>
private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eventArgs)
{
// There are corner cases with disconnect that can result in client receiving outdated key exchange packets
// ***TODO*** Deal with this on the client side. Key exchange packets should have additional information
// that identify the context of negotiation. Just like callId in SetMax and SetMinRunspaces messages
Dbg.Assert(_state >= RemoteSessionState.Established,
"Key Receiving can only be raised after reaching the Established state");
switch (eventArgs.StateEvent)
{
case RemoteSessionEvent.KeyReceived:
{
// does the server ever start key exchange process??? This may not be required
if (_state == RemoteSessionState.EstablishedAndKeyRequested)
{
// reset the timer
Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null);
if (tmp != null)
{
tmp.Dispose();
}
}
// the key import would have been done
// set state accordingly
SetState(RemoteSessionState.EstablishedAndKeyReceived, eventArgs.Reason);
// you need to send an encrypted session key to the client
_session.SendEncryptedSessionKey();
}
break;
case RemoteSessionEvent.KeySent:
{
if (_state == RemoteSessionState.EstablishedAndKeyReceived)
{
// key exchange is now complete
SetState(RemoteSessionState.EstablishedAndKeyExchanged, eventArgs.Reason);
}
}
break;
case RemoteSessionEvent.KeyRequested:
{
if ((_state == RemoteSessionState.Established) || (_state == RemoteSessionState.EstablishedAndKeyExchanged))
{
// the key has been sent set state accordingly
SetState(RemoteSessionState.EstablishedAndKeyRequested, eventArgs.Reason);
// start the timer
_keyExchangeTimer = new Timer(HandleKeyExchangeTimeout, null, BaseTransportManager.ServerDefaultKeepAliveTimeoutMs, Timeout.Infinite);
}
}
break;
case RemoteSessionEvent.KeyReceiveFailed:
{
if ((_state == RemoteSessionState.Established) || (_state == RemoteSessionState.EstablishedAndKeyExchanged))
{
return;
}
DoClose(this, eventArgs);
}
break;
case RemoteSessionEvent.KeySendFailed:
{
DoClose(this, eventArgs);
}
break;
}
}
/// <summary>
/// Handles the timeout for key exchange.
/// </summary>
/// <param name="sender">Sender of this event.</param>
private void HandleKeyExchangeTimeout(object sender)
{
Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeyRequested, "timeout should only happen when waiting for a key");
Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null);
if (tmp != null)
{
tmp.Dispose();
}
PSRemotingDataStructureException exception =
new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerKeyExchangeFailed);
RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed, exception));
}
#endregion Event Handlers
/// <summary>
/// This method is designed to be a cleanup routine after the connection is closed.
/// It can also be used for graceful shutdown of the server process, which is not currently
/// implemented.
/// </summary>
private static void CleanAll()
{
}
/// <summary>
/// Set the FSM state to a new state.
/// </summary>
/// <param name="newState">
/// The new state.
/// </param>
/// <param name="reason">
/// Optional parameter that can provide additional information. This is currently not used.
/// </param>
private void SetState(RemoteSessionState newState, Exception reason)
{
RemoteSessionState oldState = _state;
if (newState != oldState)
{
_state = newState;
s_trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state);
}
// TODO: else should we close the session here?
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
public class Driver<K, V>
where K : class
where V : class
{
public void BasicAdd(K[] keys, V[] values)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < keys.Length; i++)
{
V val;
// make sure TryGetValues return true, since the key should be in the table
Test.Eval(tbl.TryGetValue(keys[i], out val), "Err_001 Expected TryGetValue to return true");
if ( val == null && values[i] == null )
{
Test.Eval(true);
}
else if (val != null && values[i] != null && val.Equals(values[i]))
{
Test.Eval(true);
}
else
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_002 The value returned by TryGetValue doesn't match the expected value");
}
}
}
public void AddSameKey //Same Value - Different Value should not matter
(K[] keys, V[] values, int index, int repeat)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < repeat; i++)
{
try
{
tbl.Add(keys[index], values[index]);
Test.Eval(false, "Err_003 Expected to get ArgumentException when invoking Add() on an already existing key");
}
catch (ArgumentException)
{
Test.Eval(true);
}
}
}
public void AddValidations(K[] keys, V[] values, V value)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
//try to add null key
try
{
tbl.Add(null, value);
Test.Eval(false, "Err_004 Expected to get ArgumentNullException when invoking Add() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
}
public void RemoveValidations(K[] keys, V[] values, K key, V value)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
// Try to remove key from an empty dictionary
Random r = new Random();
// Remove should return false
Test.Eval(!tbl.Remove(keys[0]), "Err_005 Expected Remove to return false");
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
//try to remove null key
try
{
tbl.Remove(null);
Test.Eval(false, "Err_006 Expected to get ArgumentNullException when invoking Remove() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
// Remove non existing key
// Remove should return false
Test.Eval(!tbl.Remove(key), "Err_007 Expected Remove to return false");
}
public void TryGetValueValidations(K[] keys, V[] values, K key, V value)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
V val;
// Try to get key from an empty dictionary
// TryGetValue should return false and value should contian default(TValue)
Test.Eval(!tbl.TryGetValue(keys[0], out val), "Err_008 Expected TryGetValue to return false");
Test.Eval(val == null, "Err_009 Expected val to be null");
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
//try to get null key
try
{
tbl.TryGetValue(null, out val);
Test.Eval(false, "Err_010 Expected to get ArgumentNullException when invoking TryGetValue() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
// Try to get non existing key
// TryGetValue should return false and value should contian default(TValue)
Random r = new Random();
Test.Eval(!tbl.TryGetValue(key, out val), "Err_011 Expected TryGetValue to return false");
Test.Eval(val == null, "Err_012 Expected val to be null");
}
public Dictionary<string, string> g_stringDict = new Dictionary<string, string>();
public Dictionary<RefX1<int>, string> g_refIntDict = new Dictionary<RefX1<int>, string>();
public Dictionary<RefX1<string>, string> g_refStringDict = new Dictionary<RefX1<string>, string>();
public void GenerateValuesForStringKeys(string[] stringArr)
{
for (int i = 0; i < 100; ++i)
{
g_stringDict.Add(stringArr[i], stringArr[i]);
}
}
public void GenerateValuesForIntRefKeys(RefX1<int>[] refIntArr, string[] stringArr)
{
for (int i = 0; i < 100; ++i)
{
g_refIntDict.Add(refIntArr[i], stringArr[i]);
}
}
public void GenerateValuesForStringRefKeys(RefX1<string>[] refStringArr, string[] stringArr)
{
for (int i = 0; i < 100; ++i)
{
g_refStringDict.Add(refStringArr[i], stringArr[i]);
}
}
//This method is used for the mscorlib defined delegate
// public delegate V CreateValueCallback(K key);
public V CreateValue(K key)
{
if (key is string)
{
return g_stringDict[key as string] as V;
}
else if (key is RefX1<int>)
{
return g_refIntDict[key as RefX1<int>] as V;
}
else if (key is RefX1<string>)
{
return g_refStringDict[key as RefX1<string>] as V;
}
Test.Eval(false, "Err_12a Unknown type of key provided to CreateValue()");
return null;
}
public void VerifyValue(K key, V val)
{
V expectedVal;
if (key is string)
{
expectedVal = g_stringDict[key as string] as V;
}
else if (key is RefX1<int>)
{
expectedVal = g_refIntDict[key as RefX1<int>] as V;
}
else if (key is RefX1<string>)
{
expectedVal = g_refStringDict[key as RefX1<string>] as V;
}
else
{
Test.Eval(false, "Err_12e Incorrect key type supplied");
return;
}
if (!val.Equals(expectedVal))
{
Test.Eval(false, "Err_12b The value returned by TryGetValue doesn't match the expected value for key: " + key +
"\nExpected value: " + expectedVal + "; Actual: " + val);
}
}
public void GetValueValidations(K[] keys, V[] values)
{
ConditionalWeakTable<K,V>.CreateValueCallback valueCallBack =
new ConditionalWeakTable<K,V>.CreateValueCallback(CreateValue);
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
K key = keys[0];
// Get key from an empty dictionary
// GetValue should return the new value generated from CreateValue()
tbl.GetValue(key, valueCallBack);
// check that this opeartion added the (key,value) pair to the dictionary
V val;
Test.Eval(tbl.TryGetValue(key, out val));
VerifyValue(key, val);
// now add values to the table
for (int i = 1; i < keys.Length; i++)
{
try
{
tbl.Add(keys[i], values[i]);
}
catch (ArgumentException) { }
}
// try to get value for a key that already exists in the table
tbl.GetValue(keys[55], valueCallBack);
Test.Eval(tbl.TryGetValue(keys[55], out val));
VerifyValue(keys[55], val);
//try to get null key
try
{
tbl.GetValue(null, valueCallBack);
Test.Eval(false, "Err_010 Expected to get ArgumentNullException when invoking TryGetValue() on a null key");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
// try to use null callback
try
{
valueCallBack = null;
tbl.GetValue(key, valueCallBack);
Test.Eval(false, "Err_010 Expected to get ArgumentNullException when invoking TryGetValue() on a null callback");
}
catch (ArgumentNullException)
{
Test.Eval(true);
}
}
// The method first adds some keys to the table
// Then removes a key, checks that it was removed, adds the same key and verifies that it was added.
public void AddRemoveKeyValPair(K[] keys, V[] values, int index, int repeat)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < repeat; i++)
{
// remove existing key and ensure method return true
Test.Eval(tbl.Remove(keys[index]), "Err_013 Expected Remove to return true");
V val;
// since we removed the key, TryGetValue should return false
Test.Eval(!tbl.TryGetValue(keys[index], out val), "Err_014 Expected TryGetValue to return false");
Test.Eval(val == null, "Err_015 Expected val to be null");
// next add the same key
tbl.Add(keys[index], values[index]);
// since we added the key, TryGetValue should return true
Test.Eval(tbl.TryGetValue(keys[index], out val), "Err_016 Expected TryGetValue to return true");
if (val == null && values[i] == null)
{
Test.Eval(true);
}
else if (val != null && values[index] != null && val.Equals(values[index]))
{
Test.Eval(true);
}
else
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_017 The value returned by TryGetValue doesn't match the expected value");
}
}
}
public void BasicGetOrCreateValue(K[] keys)
{
V[] values = new V[keys.Length];
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
// assume additions for all values
for (int i = 0; i < keys.Length; i++)
{
values[i] = tbl.GetOrCreateValue(keys[i]);
}
for (int i = 0; i < keys.Length; i++)
{
V val;
// make sure TryGetValues return true, since the key should be in the table
Test.Eval(tbl.TryGetValue(keys[i], out val), "Err_018 Expected TryGetValue to return true");
if (val == null || !val.Equals(values[i]))
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_019 The value returned by TryGetValue doesn't match the object created via the default constructor");
}
}
}
public void BasicAddThenGetOrCreateValue(K[] keys, V[] values)
{
ConditionalWeakTable<K,V> tbl = new ConditionalWeakTable<K,V>();
// assume additions for all values
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
for (int i = 0; i < keys.Length; i++)
{
V val;
// make sure GetOrCreateValues the value added (and not a new object)
val = tbl.GetOrCreateValue(keys[i]);
if (val == null || !val.Equals(values[i]))
{
// only one of the values is null or the values don't match
Test.Eval(false, "Err_020 The value returned by GetOrCreateValue doesn't match the object added");
}
}
}
}
public class NoDefaultConstructor
{
public NoDefaultConstructor(string str)
{
}
}
public class WithDefaultConstructor
{
private string str;
public WithDefaultConstructor()
{
}
public WithDefaultConstructor(string s)
{
str = s;
}
public new bool Equals(object obj)
{
WithDefaultConstructor wdc = (WithDefaultConstructor)obj;
return (wdc.str.Equals(str));
}
}
public class NegativeTestCases
{
public static void NoDefaulConstructor()
{
ConditionalWeakTable<string,NoDefaultConstructor> tbl = new ConditionalWeakTable<string,NoDefaultConstructor>();
try
{
tbl.GetOrCreateValue("string1");
Test.Eval(false, "Err_021 MissingMethodException execpted");
}
catch (Exception e)
{
Test.Eval(typeof(MissingMethodException) == e.GetType(), "Err_022 Incorrect exception thrown: " + e);
}
}
}
public class TestAPIs
{
public static int Main()
{
Random r = new Random();
try
{
// test for ConditionalWeakTable<string>
Driver<string,string> stringDriver = new Driver<string,string>();
string[] stringArr = new string[100];
for (int i = 0; i < 100; i++)
{
stringArr[i] = "SomeTestString" + i.ToString();
}
// test with generic object
// test for ConditionalWeakTable<RefX1<int>>
Driver<string,RefX1<int>> refIntDriver = new Driver<string,RefX1<int>>();
RefX1<int>[] refIntArr = new RefX1<int>[100];
for (int i = 0; i < 100; i++)
{
refIntArr[i] = new RefX1<int>(i);
}
// test with generic object
// test for ConditionalWeakTable<RefX1<string>>
Driver<string, RefX1<string>> refStringDriver = new Driver<string,RefX1<string>>();
RefX1<string>[] refStringArr = new RefX1<string>[100];
for (int i = 0; i < 100; i++)
{
refStringArr[i] = new RefX1<string>("SomeTestString" + i.ToString());
}
stringDriver.BasicAdd(stringArr, stringArr);
refIntDriver.BasicAdd(stringArr, refIntArr);
refStringDriver.BasicAdd(stringArr, refStringArr);
//===============================================================
// test various boundary conditions
// - add/remove/lookup of null key
// - remove/lookup of non-existing key in an empty dictionary and a non-empty dictionary
stringDriver.AddValidations(stringArr, stringArr, stringArr[0]);
refIntDriver.AddValidations(stringArr, refIntArr, refIntArr[0]);
refStringDriver.AddValidations(stringArr, refStringArr, refStringArr[0]);
//===============================================================
stringDriver.RemoveValidations(stringArr, stringArr, r.Next().ToString(), stringArr[0]);
refIntDriver.RemoveValidations(stringArr, refIntArr, r.Next().ToString(), refIntArr[0]);
refStringDriver.RemoveValidations(stringArr, refStringArr, r.Next().ToString(), refStringArr[0]);
//===============================================================
stringDriver.TryGetValueValidations(stringArr, stringArr, r.Next().ToString(), stringArr[0]);
refIntDriver.TryGetValueValidations(stringArr, refIntArr, r.Next().ToString(), refIntArr[0]);
refStringDriver.TryGetValueValidations(stringArr, refStringArr, r.Next().ToString(), refStringArr[0]);
//===============================================================
// this method generates a dictionary with keys and values to be used for GetValue() method testing
stringDriver.GenerateValuesForStringKeys(stringArr);
stringDriver.GetValueValidations(stringArr, stringArr);
Driver<RefX1<int>, string> refIntDriver2 = new Driver<RefX1<int>, string>();
refIntDriver2.GenerateValuesForIntRefKeys(refIntArr, stringArr);
refIntDriver2.GetValueValidations(refIntArr,stringArr);
Driver<RefX1<string>, string> refStringDriver2 = new Driver<RefX1<string>, string>();
refStringDriver2.GenerateValuesForStringRefKeys(refStringArr, stringArr);
refStringDriver2.GetValueValidations(refStringArr, stringArr);
//===============================================================
stringDriver.AddSameKey(stringArr, stringArr, 0, 2);
stringDriver.AddSameKey(stringArr, stringArr, 99, 3);
stringDriver.AddSameKey(stringArr, stringArr, 50, 4);
stringDriver.AddSameKey(stringArr, stringArr, 1, 5);
stringDriver.AddSameKey(stringArr, stringArr, 98, 6);
refIntDriver.AddSameKey(stringArr, refIntArr, 0, 2);
refIntDriver.AddSameKey(stringArr, refIntArr, 99, 3);
refIntDriver.AddSameKey(stringArr, refIntArr, 50, 4);
refIntDriver.AddSameKey(stringArr, refIntArr, 1, 5);
refIntDriver.AddSameKey(stringArr, refIntArr, 98, 6);
refStringDriver.AddSameKey(stringArr, refStringArr, 0, 2);
refStringDriver.AddSameKey(stringArr, refStringArr, 99, 3);
refStringDriver.AddSameKey(stringArr, refStringArr, 50, 4);
refStringDriver.AddSameKey(stringArr, refStringArr, 1, 5);
refStringDriver.AddSameKey(stringArr, refStringArr, 98, 6);
//===============================================================
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 0, 2);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 99, 3);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 50, 4);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 1, 5);
stringDriver.AddRemoveKeyValPair(stringArr, stringArr, 98, 6);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 0, 2);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 99, 3);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 50, 4);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 1, 5);
refIntDriver.AddRemoveKeyValPair(stringArr, refIntArr, 98, 6);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 0, 2);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 99, 3);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 50, 4);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 1, 5);
refStringDriver.AddRemoveKeyValPair(stringArr, refStringArr, 98, 6);
//==============================================================
// new tests for GetOrCreateValue
(new Driver<string, WithDefaultConstructor>()).BasicGetOrCreateValue(stringArr);
WithDefaultConstructor[] wvalues = new WithDefaultConstructor[stringArr.Length];
for (int i=0; i<wvalues.Length; i++) wvalues[i] = new WithDefaultConstructor(stringArr[i]);
(new Driver<string, WithDefaultConstructor>()).BasicAddThenGetOrCreateValue(stringArr, wvalues);
NegativeTestCases.NoDefaulConstructor();
//===============================================================
if (Test.result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 101;
}
}
catch (Exception e)
{
Console.WriteLine("Test threw unexpected exception:\n{0}", e);
return 102;
}
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// 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 BuildAMation 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.
#endregion // License
using System.Linq;
namespace VSSolutionBuilder
{
/// <summary>
/// Class representing a group of settings with a given meaning
/// </summary>
sealed class VSSettingsGroup
{
/// <summary>
/// What type of group is represented
/// </summary>
public enum ESettingsGroup
{
Compiler, //<! Group of source files to compile
Header, //<! Group of header files
Librarian, //<! Archive a number of object files
Linker, //<! Link a number of object files and libraries
PreBuild, //<! Perform a prebuild step
PostBuild, //<! Perform a postbuild step
CustomBuild,//<! Customized build step
Resource, //<! Group of Windowsresource files
Assembler //<! Group of assembler files
}
/// <summary>
/// Construct a new group instance
/// </summary>
/// <param name="project">Belongs to this project</param>
/// <param name="module">Module associated with the group</param>
/// <param name="group">Type of the group to make</param>
/// <param name="path">The path to associate with the new settings group</param>
public VSSettingsGroup(
VSProject project,
Bam.Core.Module module,
ESettingsGroup group,
Bam.Core.TokenizedString path)
{
this.Project = project;
this.Module = module;
this.Group = group;
this.Path = path;
if (null != path)
{
this.RelativeDirectory = module.CreateTokenizedString(
"@isrelative(@trimstart(@relativeto(@dir($(0)),$(packagedir)),../),@dir($(0)))",
path
);
lock (this.RelativeDirectory)
{
if (!this.RelativeDirectory.IsParsed)
{
// may have been parsed already, e.g. a common header
this.RelativeDirectory.Parse();
}
// this can happen if the source file lies directly in the package directory
// rather than in subdirectories
// project filters called '.' look weird
if (this.RelativeDirectory.ToString().Equals(".", System.StringComparison.Ordinal))
{
this.RelativeDirectory = null;
}
}
}
this.Settings = new Bam.Core.Array<VSSetting>();
}
private VSProject Project { get; set; }
/// <summary>
/// Module associated with the group
/// </summary>
public Bam.Core.Module Module { get; private set; }
/// <summary>
/// Type of the group
/// </summary>
public ESettingsGroup Group { get; private set; }
/// <summary>
/// Path associated with the settings.
/// </summary>
public Bam.Core.TokenizedString Path { get; private set; }
/// <summary>
/// Relative directory of the group.
/// </summary>
public Bam.Core.TokenizedString RelativeDirectory { get; private set; }
private Bam.Core.Array<VSSetting> Settings { get; set; }
private VSProjectConfiguration Configuration => this.Project.GetConfiguration(this.Module);
/// <summary>
/// Add a new Boolean setting to the group.
/// </summary>
/// <param name="name">Name of the setting</param>
/// <param name="value">Bool value of the setting.</param>
/// <param name="condition">Optional condition for the setting. Default to null.</param>
public void
AddSetting(
string name,
bool value,
string condition = null)
{
lock (this.Settings)
{
var stringValue = value.ToString().ToLower();
if (this.Settings.Any(item =>
item.Name.Equals(name, System.StringComparison.Ordinal) &&
System.String.Equals(item.Condition, condition, System.StringComparison.Ordinal) &&
!item.Value.Equals(stringValue, System.StringComparison.Ordinal))
)
{
throw new Bam.Core.Exception($"Cannot change the value of existing boolean option {name} to {value}");
}
this.Settings.AddUnique(
new VSSetting(
name,
stringValue,
false,
inheritValue: false,
condition: condition
)
);
}
}
/// <summary>
/// Add a new string setting to the group.
/// </summary>
/// <param name="name">Name of the setting</param>
/// <param name="value">String value of the setting.</param>
/// <param name="condition">Optional condition for the setting. Default to null.</param>
public void
AddSetting(
string name,
string value,
string condition = null)
{
lock (this.Settings)
{
if (this.Settings.Any(item =>
item.Name.Equals(name, System.StringComparison.Ordinal) &&
System.String.Equals(item.Condition, condition, System.StringComparison.Ordinal) &&
!item.Value.Equals(value, System.StringComparison.Ordinal))
)
{
throw new Bam.Core.Exception($"Cannot change the value of existing string option {name} to {value}");
}
this.Settings.AddUnique(
new VSSetting(
name,
value,
false,
inheritValue: false,
condition: condition
)
);
}
}
/// <summary>
/// Add a path setting to the group.
/// </summary>
/// <param name="name">Name of the setting</param>
/// <param name="path">Path of the setting.</param>
/// <param name="condition">Optional condition for the setting. Default to null.</param>
/// <param name="inheritExisting">Optional whether the value inherits parent values. Default to false.</param>
public void
AddSetting(
string name,
Bam.Core.TokenizedString path,
string condition = null,
bool inheritExisting = false)
{
lock (this.Settings)
{
var stringValue = path.ToString();
if (this.Settings.Any(item =>
item.Name.Equals(name, System.StringComparison.Ordinal) &&
System.String.Equals(item.Condition, condition, System.StringComparison.Ordinal) &&
!item.Value.Equals(stringValue, System.StringComparison.Ordinal))
)
{
throw new Bam.Core.Exception($"Cannot change the value of existing tokenized path option {name} to {path.ToString()}");
}
this.Settings.AddUnique(
new VSSetting(
name,
stringValue,
isPath: true,
inheritValue: false,
condition: condition
)
);
}
}
/// <summary>
/// Add an array of strings setting to the group.
/// </summary>
/// <param name="name">Name of the setting</param>
/// <param name="value">Value of the setting.</param>
/// <param name="condition">Optional condition for the setting. Default to null.</param>
/// <param name="inheritExisting">Optional whether the value inherits parent values. Default to false.</param>
/// <param name="arePaths">Optional whether the value is an array of paths. Default to false.</param>
public void
AddSetting(
string name,
Bam.Core.TokenizedStringArray value,
string condition = null,
bool inheritExisting = false,
bool arePaths = false)
{
this.AddSetting(
name,
value.ToEnumerableWithoutDuplicates(),
condition,
inheritExisting,
arePaths
);
}
/// <summary>
/// Add an enumeration of strings setting to the group.
/// </summary>
/// <param name="name">Name of the setting</param>
/// <param name="value">Value of the setting.</param>
/// <param name="condition">Optional condition for the setting. Default to null.</param>
/// <param name="inheritExisting">Optional whether the value inherits parent values. Default to false.</param>
/// <param name="arePaths">Optional whether the value is an enumeration of paths. Default to false.</param>
public void
AddSetting(
string name,
System.Collections.Generic.IEnumerable<Bam.Core.TokenizedString> value,
string condition = null,
bool inheritExisting = false,
bool arePaths = false)
{
lock (this.Settings)
{
if (!value.Any())
{
return;
}
var linearized = new Bam.Core.TokenizedStringArray(value.Distinct()).ToString(';');
if (this.Settings.Any(item => item.Name.Equals(name, System.StringComparison.Ordinal) && System.String.Equals(item.Condition, condition, System.StringComparison.Ordinal)))
{
var settingOption = this.Settings.First(item => item.Name.Equals(name, System.StringComparison.Ordinal) && System.String.Equals(item.Condition, condition, System.StringComparison.Ordinal));
if (settingOption.Value.Contains(linearized))
{
return;
}
settingOption.Append(linearized, separator: ";");
return;
}
this.Settings.AddUnique(
new VSSetting(
name,
linearized,
arePaths,
inheritValue: inheritExisting,
condition
)
);
}
}
/// <summary>
/// Add an array of strings setting to the group.
/// </summary>
/// <param name="name">Name of the setting</param>
/// <param name="value">Value of the setting.</param>
/// <param name="condition">Optional condition for the setting. Default to null.</param>
/// <param name="inheritExisting">Optional whether the value inherits parent values. Default to false.</param>
public void
AddSetting(
string name,
Bam.Core.StringArray value,
string condition = null,
bool inheritExisting = false)
{
lock (this.Settings)
{
if (0 == value.Count)
{
return;
}
var linearized = value.ToString(';');
if (this.Settings.Any(item => item.Name.Equals(name, System.StringComparison.Ordinal) && System.String.Equals(item.Condition, condition, System.StringComparison.Ordinal)))
{
var settingOption = this.Settings.First(item => item.Name.Equals(name, System.StringComparison.Ordinal) && System.String.Equals(item.Condition, condition, System.StringComparison.Ordinal));
if (settingOption.Value.Contains(linearized))
{
return;
}
settingOption.Append(linearized, separator: ";");
return;
}
this.Settings.AddUnique(
new VSSetting(
name,
linearized,
false,
inheritValue: inheritExisting,
condition
)
);
}
}
/// <summary>
/// Add preprocessor definitions setting to the group.
/// </summary>
/// <param name="name">Name of the setting</param>
/// <param name="definitions">Value of the setting.</param>
/// <param name="condition">Optional condition for the setting. Default to null.</param>
/// <param name="inheritExisting">Optional whether the value inherits parent values. Default to false.</param>
public void
AddSetting(
string name,
C.PreprocessorDefinitions definitions,
string condition = null,
bool inheritExisting = false)
{
if (!definitions.Any())
{
return;
}
lock (this.Settings)
{
if (this.Settings.Any(item => item.Name.Equals(name) && System.String.Equals(item.Condition, condition, System.StringComparison.Ordinal)))
{
throw new Bam.Core.Exception($"Cannot append to the preprocessor define list {name}");
}
var defString = definitions.ToString();
this.Settings.AddUnique(
new VSSetting(
name,
defString,
false,
inheritValue: inheritExisting,
condition
)
);
}
}
private string
GetGroupName()
{
switch (this.Group)
{
case ESettingsGroup.Compiler:
return "ClCompile";
case ESettingsGroup.Header:
return "ClInclude";
case ESettingsGroup.Librarian:
return "Lib";
case ESettingsGroup.Linker:
return "Link";
case ESettingsGroup.PreBuild:
return "PreBuildEvent";
case ESettingsGroup.PostBuild:
return "PostBuildEvent";
case ESettingsGroup.CustomBuild:
return "CustomBuild";
case ESettingsGroup.Resource:
return "ResourceCompile";
case ESettingsGroup.Assembler:
return "MASM";
default:
throw new Bam.Core.Exception($"Unknown settings group, {this.Group.ToString()}");
}
}
/// <summary>
/// Serialize the settings group to an XML document.
/// </summary>
/// <param name="document">XML document to serialise to.</param>
/// <param name="parentEl">Parent XML element for this group.</param>
public void
Serialize(
System.Xml.XmlDocument document,
System.Xml.XmlElement parentEl)
{
if ((this.Settings.Count == 0) && (this.Path == null))
{
return;
}
var group = document.CreateVSElement(this.GetGroupName(), parentEl: parentEl);
if (null != this.Path)
{
// cannot use relative paths with macros here, see https://docs.microsoft.com/en-us/cpp/build/reference/vcxproj-file-structure?view=vs-2015
group.SetAttribute("Include", this.Path.ToString());
}
foreach (var setting in this.Settings.OrderBy(pair => pair.Name))
{
if (setting.IsPath)
{
document.CreateVSElement(
setting.Name,
value: this.Configuration.ToRelativePath(setting.Serialize()),
condition: setting.Condition,
parentEl: group
);
}
else
{
document.CreateVSElement(
setting.Name,
value: setting.Serialize(),
condition: setting.Condition,
parentEl: group
);
}
}
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseThrowExpression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.UseThrowExpression;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseThrowExpression
{
public partial class UseThrowExpressionTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseThrowExpressionDiagnosticAnalyzer(), new UseThrowExpressionCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task WithoutBraces()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestOnIf()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
[|if|] (s == null)
throw new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task WithBraces()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
}
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNotOnAssign()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
_s = [|s|];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task OnlyInCSharp7AndHigher()
{
await TestMissingAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s)) };
_s = s;
}
}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task WithIntermediaryStatements()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
}
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task NotWithIntermediaryWrite()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
};
s = ""something"";
_s = s;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task NotWithIntermediaryMemberAccess()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
};
s.ToString();
_s = s;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNullCheckOnLeft()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
if (null == s)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestWithLocal()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
string s = null;
if (null == s)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M()
{
string s = null;
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNotOnField()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
string s;
void M()
{
if (null == s)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestAssignBeforeCheck()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s)
{
_s = s;
if (s == null)
[|throw|] new ArgumentNullException(nameof(s));
}
}");
}
[WorkItem(16234, "https://github.com/dotnet/roslyn/issues/16234")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNotInExpressionTree()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Linq.Expressions;
class C
{
private string _s;
void Foo()
{
Expression<Action<string>> e = s =>
{
if (s == null)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
};
}
}");
}
[WorkItem(404142, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=404142")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNotWithAsCheck()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class BswParser3
{
private ParserSyntax m_syntax;
public BswParser3(ISyntax syntax)
{
if (syntax == null)
{
[|throw|] new ArgumentNullException(nameof(syntax));
}
m_syntax = syntax as ParserSyntax;
if (m_syntax == null)
throw new ArgumentException();
}
}
internal class ParserSyntax
{
}
public interface ISyntax
{
}");
}
}
}
| |
// 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.Linq.Tests
{
public class AverageTests
{
private struct NameNum<TNumeric>
{
public string name;
public TNumeric num;
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.Average(), q.Average());
}
[Fact]
public void SameResultsRepeatCallsNullableLongQuery()
{
var q = from x in new long?[] { Int32.MaxValue, 0, 255, 127, 128, 1, 33, 99, null, Int32.MinValue }
select x;
Assert.Equal(q.Average(), q.Average());
}
[Fact]
public void EmptyNullableFloatSource()
{
float?[] source = { };
float? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void SingleNullableFloatSource()
{
float?[] source = { float.MinValue };
float? expected = float.MinValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableFloatAllZeroSource()
{
float?[] source = { 0f, 0f, 0f, 0f, 0f };
float? expected = 0f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableFloatSource()
{
float?[] source = { 5.5f, 0, null, null, null, 15.5f, 40.5f, null, null, -23.5f };
float? expected = 7.6f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableFloatSourceOnlyOneNotNull()
{
float?[] source = { null, null, null, null, 45f };
float? expected = 45f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableFloatSourceAllNull()
{
float?[] source = { null, null, null, null, null };
float? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void NullableFloatFromSelector()
{
NameNum<float?>[] source = new NameNum<float?>[]
{
new NameNum<float?>{name="Tim", num=5.5f},
new NameNum<float?>{name="John", num=15.5f},
new NameNum<float?>{name="Bob", num=null}
};
float? expected = 10.5f;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyIntSource()
{
int[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void SingleElementIntSource()
{
int[] source = { 5 };
double expected = 5;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleIntValuesAllZero()
{
int[] source = { 0, 0, 0, 0, 0 };
double expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleIntSouce()
{
int[] source = { 5, -10, 15, 40, 28 };
double expected = 15.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleIntFromSelector()
{
NameNum<int>[] source = new NameNum<int>[]
{
new NameNum<int>{name="Tim", num=10},
new NameNum<int>{name="John", num=-10},
new NameNum<int>{name="Bob", num=15}
};
double expected = 5;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyNullableIntSource()
{
int?[] source = { };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void SingleNullableIntSource()
{
int?[] source = { -5 };
double? expected = -5;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableIntAllZeroSource()
{
int?[] source = { 0, 0, 0, 0, 0 };
double? expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableIntSource()
{
int?[] source = { 5, -10, null, null, null, 15, 40, 28, null, null };
double? expected = 15.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableIntSourceOnlyOneNotNull()
{
int?[] source = { null, null, null, null, 50 };
double? expected = 50;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableIntSourceAllNull()
{
int?[] source = { null, null, null, null, null };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void NullableIntFromSelector()
{
NameNum<int?>[] source = new NameNum<int?>[]
{
new NameNum<int?>{name="Tim", num=10},
new NameNum<int?>{name="John", num=null},
new NameNum<int?>{name="Bob", num=10}
};
double? expected = 10;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyLongSource()
{
long[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void SingleElementLongSource()
{
long[] source = { Int64.MaxValue };
double expected = Int64.MaxValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleLongValuesAllZero()
{
long[] source = { 0, 0, 0, 0, 0 };
double expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleLongValues()
{
long[] source = { 5, -10, 15, 40, 28 };
double expected = 15.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleLongFromSelector()
{
NameNum<long>[] source = new NameNum<long>[]
{
new NameNum<long>{name="Tim", num=40L},
new NameNum<long>{name="John", num=50L},
new NameNum<long>{name="Bob", num=60L}
};
double expected = 50;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void OverflowFromSummingLong()
{
long[] source = { Int64.MaxValue, Int64.MaxValue };
Assert.Throws<OverflowException>(() => source.Average());
}
[Fact]
public void EmptyNullableLongSource()
{
long?[] source = { };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void SingleNullableLongSource()
{
long?[] source = { Int64.MinValue };
double? expected = Int64.MinValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableLongAllZeroSource()
{
long?[] source = { 0, 0, 0, 0, 0 };
double? expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableLongSource()
{
long?[] source = { 5, -10, null, null, null, 15, 40, 28, null, null };
double? expected = 15.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableLongSourceOnlyOneNotNull()
{
long?[] source = { null, null, null, null, 50 };
double? expected = 50;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableLongSourceAllNull()
{
long?[] source = { null, null, null, null, null };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void NullableLongFromSelector()
{
NameNum<long?>[] source = new NameNum<long?>[]
{
new NameNum<long?>{name="Tim", num=40L},
new NameNum<long?>{name="John", num=null},
new NameNum<long?>{name="Bob", num=30L}
};
double? expected = 35;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyDoubleSource()
{
double[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void SingleElementDoubleSource()
{
double[] source = { Double.MaxValue };
double expected = Double.MaxValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDoubleValuesAllZero()
{
double[] source = { 0.0, 0.0, 0.0, 0.0, 0.0 };
double expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDoubleValues()
{
double[] source = { 5.5, -10, 15.5, 40.5, 28.5 };
double expected = 16;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDoubleValuesIncludingNaN()
{
double[] source = { 5.58, Double.NaN, 30, 4.55, 19.38 };
double expected = Double.NaN;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDoubleFromSelector()
{
NameNum<double>[] source = new NameNum<double>[]
{
new NameNum<double>{name="Tim", num=5.5},
new NameNum<double>{name="John", num=15.5},
new NameNum<double>{name="Bob", num=3.0}
};
double expected = 8.0;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyNullableDoubleSource()
{
double?[] source = { };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void SingleNullableDoubleSource()
{
double?[] source = { Double.MinValue };
double? expected = Double.MinValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleAllZeroSource()
{
double?[] source = { 0, 0, 0, 0, 0 };
double? expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleSource()
{
double?[] source = { 5.5, 0, null, null, null, 15.5, 40.5, null, null, -23.5 };
double? expected = 7.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleSourceOnlyOneNotNull()
{
double?[] source = { null, null, null, null, 45 };
double? expected = 45;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleSourceAllNull()
{
double?[] source = { null, null, null, null, null };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleSourceIncludingNaN()
{
double?[] source = { -23.5, 0, Double.NaN, 54.3, 0.56 };
double? expected = Double.NaN;
Assert.Equal(expected, source.Average());
}
[Fact]
public void NullableDoubleFromSelector()
{
NameNum<double?>[] source = new NameNum<double?>[]
{
new NameNum<double?>{name="Tim", num=5.5},
new NameNum<double?>{name="John", num=15.5},
new NameNum<double?>{name="Bob", num=null}
};
double? expected = 10.5;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyDecimalSource()
{
decimal[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void SingleElementDecimalSource()
{
decimal[] source = { Decimal.MaxValue };
decimal expected = Decimal.MaxValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDecimalValuesAllZero()
{
decimal[] source = { 0.0m, 0.0m, 0.0m, 0.0m, 0.0m };
decimal expected = 0m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDecimalValues()
{
decimal[] source = { 5.5m, -10m, 15.5m, 40.5m, 28.5m };
decimal expected = 16m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDecimalFromSelector()
{
NameNum<decimal>[] source = new NameNum<decimal>[]
{
new NameNum<decimal>{name="Tim", num=5.5m},
new NameNum<decimal>{name="John", num=15.5m},
new NameNum<decimal>{name="Bob", num=3.0m}
};
decimal expected = 8.0m;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyNullableDecimalSource()
{
decimal?[] source = { };
decimal? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void SingleNullableDecimalSource()
{
decimal?[] source = { Decimal.MinValue };
decimal? expected = Decimal.MinValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableeDecimalAllZeroSource()
{
decimal?[] source = { 0m, 0m, 0m, 0m, 0m };
decimal? expected = 0m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableeDecimalSource()
{
decimal?[] source = { 5.5m, 0, null, null, null, 15.5m, 40.5m, null, null, -23.5m };
decimal? expected = 7.6m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDecimalSourceOnlyOneNotNull()
{
decimal?[] source = { null, null, null, null, 45m };
decimal? expected = 45m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDecimalSourceAllNull()
{
decimal?[] source = { null, null, null, null, null };
decimal? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void NullableDecimalFromSelector()
{
NameNum<decimal?>[] source = new NameNum<decimal?>[]
{
new NameNum<decimal?>{name="Tim", num=5.5m},
new NameNum<decimal?>{name="John", num=15.5m},
new NameNum<decimal?>{name="Bob", num=null}
};
decimal? expected = 10.5m;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void OverflowFromSummingDecimal()
{
decimal?[] source = { decimal.MaxValue, decimal.MaxValue };
Assert.Throws<OverflowException>(() => source.Average());
}
[Fact]
public void EmptyFloatSource()
{
float[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void SingleElementFloatSource()
{
float[] source = { float.MaxValue };
float expected = float.MaxValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleFloatValuesAllZero()
{
float[] source = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float expected = 0f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleFloatValues()
{
float[] source = { 5.5f, -10f, 15.5f, 40.5f, 28.5f };
float expected = 16f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleFloatFromSelector()
{
NameNum<float>[] source = new NameNum<float>[]
{
new NameNum<float>{name="Tim", num=5.5f},
new NameNum<float>{name="John", num=15.5f},
new NameNum<float>{name="Bob", num=3.0f}
};
float expected = 8.0f;
Assert.Equal(expected, source.Average(e => e.num));
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Bigtable.V2.Snippets
{
using Google.Api.Gax.Grpc;
using Google.Cloud.Bigtable.Common.V2;
using Google.Protobuf;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedBigtableServiceApiClientSnippets
{
/// <summary>Snippet for ReadRows</summary>
public async Task ReadRowsRequestObject()
{
// Snippet: ReadRows(ReadRowsRequest, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
ReadRowsRequest request = new ReadRowsRequest
{
TableNameAsTableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"),
Rows = new RowSet(),
Filter = new RowFilter(),
RowsLimit = 0L,
AppProfileId = "",
};
// Make the request, returning a streaming response
BigtableServiceApiClient.ReadRowsStream response = bigtableServiceApiClient.ReadRows(request);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<ReadRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
ReadRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for ReadRows</summary>
public async Task ReadRows1()
{
// Snippet: ReadRows(string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
// Make the request, returning a streaming response
BigtableServiceApiClient.ReadRowsStream response = bigtableServiceApiClient.ReadRows(tableName);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<ReadRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
ReadRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for ReadRows</summary>
public async Task ReadRows1ResourceNames()
{
// Snippet: ReadRows(TableName, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
// Make the request, returning a streaming response
BigtableServiceApiClient.ReadRowsStream response = bigtableServiceApiClient.ReadRows(tableName);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<ReadRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
ReadRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for ReadRows</summary>
public async Task ReadRows2()
{
// Snippet: ReadRows(string, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
string appProfileId = "";
// Make the request, returning a streaming response
BigtableServiceApiClient.ReadRowsStream response = bigtableServiceApiClient.ReadRows(tableName, appProfileId);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<ReadRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
ReadRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for ReadRows</summary>
public async Task ReadRows2ResourceNames()
{
// Snippet: ReadRows(TableName, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
string appProfileId = "";
// Make the request, returning a streaming response
BigtableServiceApiClient.ReadRowsStream response = bigtableServiceApiClient.ReadRows(tableName, appProfileId);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<ReadRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
ReadRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for SampleRowKeys</summary>
public async Task SampleRowKeysRequestObject()
{
// Snippet: SampleRowKeys(SampleRowKeysRequest, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
SampleRowKeysRequest request = new SampleRowKeysRequest
{
TableNameAsTableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"),
AppProfileId = "",
};
// Make the request, returning a streaming response
BigtableServiceApiClient.SampleRowKeysStream response = bigtableServiceApiClient.SampleRowKeys(request);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<SampleRowKeysResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
SampleRowKeysResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for SampleRowKeys</summary>
public async Task SampleRowKeys1()
{
// Snippet: SampleRowKeys(string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
// Make the request, returning a streaming response
BigtableServiceApiClient.SampleRowKeysStream response = bigtableServiceApiClient.SampleRowKeys(tableName);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<SampleRowKeysResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
SampleRowKeysResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for SampleRowKeys</summary>
public async Task SampleRowKeys1ResourceNames()
{
// Snippet: SampleRowKeys(TableName, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
// Make the request, returning a streaming response
BigtableServiceApiClient.SampleRowKeysStream response = bigtableServiceApiClient.SampleRowKeys(tableName);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<SampleRowKeysResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
SampleRowKeysResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for SampleRowKeys</summary>
public async Task SampleRowKeys2()
{
// Snippet: SampleRowKeys(string, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
string appProfileId = "";
// Make the request, returning a streaming response
BigtableServiceApiClient.SampleRowKeysStream response = bigtableServiceApiClient.SampleRowKeys(tableName, appProfileId);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<SampleRowKeysResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
SampleRowKeysResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for SampleRowKeys</summary>
public async Task SampleRowKeys2ResourceNames()
{
// Snippet: SampleRowKeys(TableName, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
string appProfileId = "";
// Make the request, returning a streaming response
BigtableServiceApiClient.SampleRowKeysStream response = bigtableServiceApiClient.SampleRowKeys(tableName, appProfileId);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<SampleRowKeysResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
SampleRowKeysResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for MutateRow</summary>
public void MutateRowRequestObject()
{
// Snippet: MutateRow(MutateRowRequest, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
MutateRowRequest request = new MutateRowRequest
{
TableNameAsTableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.Empty,
Mutations = { new Mutation(), },
AppProfileId = "",
};
// Make the request
MutateRowResponse response = bigtableServiceApiClient.MutateRow(request);
// End snippet
}
/// <summary>Snippet for MutateRowAsync</summary>
public async Task MutateRowRequestObjectAsync()
{
// Snippet: MutateRowAsync(MutateRowRequest, CallSettings)
// Additional: MutateRowAsync(MutateRowRequest, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
MutateRowRequest request = new MutateRowRequest
{
TableNameAsTableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.Empty,
Mutations = { new Mutation(), },
AppProfileId = "",
};
// Make the request
MutateRowResponse response = await bigtableServiceApiClient.MutateRowAsync(request);
// End snippet
}
/// <summary>Snippet for MutateRow</summary>
public void MutateRow1()
{
// Snippet: MutateRow(string, ByteString, IEnumerable<Mutation>, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
MutateRowResponse response = bigtableServiceApiClient.MutateRow(tableName, rowKey, mutations);
// End snippet
}
/// <summary>Snippet for MutateRowAsync</summary>
public async Task MutateRow1Async()
{
// Snippet: MutateRowAsync(string, ByteString, IEnumerable<Mutation>, CallSettings)
// Additional: MutateRowAsync(string, ByteString, IEnumerable<Mutation>, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
MutateRowResponse response = await bigtableServiceApiClient.MutateRowAsync(tableName, rowKey, mutations);
// End snippet
}
/// <summary>Snippet for MutateRow</summary>
public void MutateRow1ResourceNames()
{
// Snippet: MutateRow(TableName, ByteString, IEnumerable<Mutation>, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
MutateRowResponse response = bigtableServiceApiClient.MutateRow(tableName, rowKey, mutations);
// End snippet
}
/// <summary>Snippet for MutateRowAsync</summary>
public async Task MutateRow1ResourceNamesAsync()
{
// Snippet: MutateRowAsync(TableName, ByteString, IEnumerable<Mutation>, CallSettings)
// Additional: MutateRowAsync(TableName, ByteString, IEnumerable<Mutation>, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
MutateRowResponse response = await bigtableServiceApiClient.MutateRowAsync(tableName, rowKey, mutations);
// End snippet
}
/// <summary>Snippet for MutateRow</summary>
public void MutateRow2()
{
// Snippet: MutateRow(string, ByteString, IEnumerable<Mutation>, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
string appProfileId = "";
// Make the request
MutateRowResponse response = bigtableServiceApiClient.MutateRow(tableName, rowKey, mutations, appProfileId);
// End snippet
}
/// <summary>Snippet for MutateRowAsync</summary>
public async Task MutateRow2Async()
{
// Snippet: MutateRowAsync(string, ByteString, IEnumerable<Mutation>, string, CallSettings)
// Additional: MutateRowAsync(string, ByteString, IEnumerable<Mutation>, string, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
string appProfileId = "";
// Make the request
MutateRowResponse response = await bigtableServiceApiClient.MutateRowAsync(tableName, rowKey, mutations, appProfileId);
// End snippet
}
/// <summary>Snippet for MutateRow</summary>
public void MutateRow2ResourceNames()
{
// Snippet: MutateRow(TableName, ByteString, IEnumerable<Mutation>, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
string appProfileId = "";
// Make the request
MutateRowResponse response = bigtableServiceApiClient.MutateRow(tableName, rowKey, mutations, appProfileId);
// End snippet
}
/// <summary>Snippet for MutateRowAsync</summary>
public async Task MutateRow2ResourceNamesAsync()
{
// Snippet: MutateRowAsync(TableName, ByteString, IEnumerable<Mutation>, string, CallSettings)
// Additional: MutateRowAsync(TableName, ByteString, IEnumerable<Mutation>, string, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
string appProfileId = "";
// Make the request
MutateRowResponse response = await bigtableServiceApiClient.MutateRowAsync(tableName, rowKey, mutations, appProfileId);
// End snippet
}
/// <summary>Snippet for MutateRows</summary>
public async Task MutateRowsRequestObject()
{
// Snippet: MutateRows(MutateRowsRequest, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
MutateRowsRequest request = new MutateRowsRequest
{
TableNameAsTableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"),
Entries =
{
new MutateRowsRequest.Types.Entry(),
},
AppProfileId = "",
};
// Make the request, returning a streaming response
BigtableServiceApiClient.MutateRowsStream response = bigtableServiceApiClient.MutateRows(request);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<MutateRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
MutateRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for MutateRows</summary>
public async Task MutateRows1()
{
// Snippet: MutateRows(string, IEnumerable<MutateRowsRequest.Types.Entry>, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
IEnumerable<MutateRowsRequest.Types.Entry> entries = new MutateRowsRequest.Types.Entry[]
{
new MutateRowsRequest.Types.Entry(),
};
// Make the request, returning a streaming response
BigtableServiceApiClient.MutateRowsStream response = bigtableServiceApiClient.MutateRows(tableName, entries);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<MutateRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
MutateRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for MutateRows</summary>
public async Task MutateRows1ResourceNames()
{
// Snippet: MutateRows(TableName, IEnumerable<MutateRowsRequest.Types.Entry>, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
IEnumerable<MutateRowsRequest.Types.Entry> entries = new MutateRowsRequest.Types.Entry[]
{
new MutateRowsRequest.Types.Entry(),
};
// Make the request, returning a streaming response
BigtableServiceApiClient.MutateRowsStream response = bigtableServiceApiClient.MutateRows(tableName, entries);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<MutateRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
MutateRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for MutateRows</summary>
public async Task MutateRows2()
{
// Snippet: MutateRows(string, IEnumerable<MutateRowsRequest.Types.Entry>, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
IEnumerable<MutateRowsRequest.Types.Entry> entries = new MutateRowsRequest.Types.Entry[]
{
new MutateRowsRequest.Types.Entry(),
};
string appProfileId = "";
// Make the request, returning a streaming response
BigtableServiceApiClient.MutateRowsStream response = bigtableServiceApiClient.MutateRows(tableName, entries, appProfileId);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<MutateRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
MutateRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for MutateRows</summary>
public async Task MutateRows2ResourceNames()
{
// Snippet: MutateRows(TableName, IEnumerable<MutateRowsRequest.Types.Entry>, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
IEnumerable<MutateRowsRequest.Types.Entry> entries = new MutateRowsRequest.Types.Entry[]
{
new MutateRowsRequest.Types.Entry(),
};
string appProfileId = "";
// Make the request, returning a streaming response
BigtableServiceApiClient.MutateRowsStream response = bigtableServiceApiClient.MutateRows(tableName, entries, appProfileId);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<MutateRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
MutateRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for CheckAndMutateRow</summary>
public void CheckAndMutateRowRequestObject()
{
// Snippet: CheckAndMutateRow(CheckAndMutateRowRequest, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
CheckAndMutateRowRequest request = new CheckAndMutateRowRequest
{
TableNameAsTableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.Empty,
TrueMutations = { new Mutation(), },
FalseMutations = { new Mutation(), },
PredicateFilter = new RowFilter(),
AppProfileId = "",
};
// Make the request
CheckAndMutateRowResponse response = bigtableServiceApiClient.CheckAndMutateRow(request);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRowAsync</summary>
public async Task CheckAndMutateRowRequestObjectAsync()
{
// Snippet: CheckAndMutateRowAsync(CheckAndMutateRowRequest, CallSettings)
// Additional: CheckAndMutateRowAsync(CheckAndMutateRowRequest, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
CheckAndMutateRowRequest request = new CheckAndMutateRowRequest
{
TableNameAsTableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.Empty,
TrueMutations = { new Mutation(), },
FalseMutations = { new Mutation(), },
PredicateFilter = new RowFilter(),
AppProfileId = "",
};
// Make the request
CheckAndMutateRowResponse response = await bigtableServiceApiClient.CheckAndMutateRowAsync(request);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRow</summary>
public void CheckAndMutateRow1()
{
// Snippet: CheckAndMutateRow(string, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new Mutation[] { new Mutation(), };
IEnumerable<Mutation> falseMutations = new Mutation[] { new Mutation(), };
// Make the request
CheckAndMutateRowResponse response = bigtableServiceApiClient.CheckAndMutateRow(tableName, rowKey, predicateFilter, trueMutations, falseMutations);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRowAsync</summary>
public async Task CheckAndMutateRow1Async()
{
// Snippet: CheckAndMutateRowAsync(string, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CallSettings)
// Additional: CheckAndMutateRowAsync(string, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new Mutation[] { new Mutation(), };
IEnumerable<Mutation> falseMutations = new Mutation[] { new Mutation(), };
// Make the request
CheckAndMutateRowResponse response = await bigtableServiceApiClient.CheckAndMutateRowAsync(tableName, rowKey, predicateFilter, trueMutations, falseMutations);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRow</summary>
public void CheckAndMutateRow1ResourceNames()
{
// Snippet: CheckAndMutateRow(TableName, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new Mutation[] { new Mutation(), };
IEnumerable<Mutation> falseMutations = new Mutation[] { new Mutation(), };
// Make the request
CheckAndMutateRowResponse response = bigtableServiceApiClient.CheckAndMutateRow(tableName, rowKey, predicateFilter, trueMutations, falseMutations);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRowAsync</summary>
public async Task CheckAndMutateRow1ResourceNamesAsync()
{
// Snippet: CheckAndMutateRowAsync(TableName, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CallSettings)
// Additional: CheckAndMutateRowAsync(TableName, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new Mutation[] { new Mutation(), };
IEnumerable<Mutation> falseMutations = new Mutation[] { new Mutation(), };
// Make the request
CheckAndMutateRowResponse response = await bigtableServiceApiClient.CheckAndMutateRowAsync(tableName, rowKey, predicateFilter, trueMutations, falseMutations);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRow</summary>
public void CheckAndMutateRow2()
{
// Snippet: CheckAndMutateRow(string, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new Mutation[] { new Mutation(), };
IEnumerable<Mutation> falseMutations = new Mutation[] { new Mutation(), };
string appProfileId = "";
// Make the request
CheckAndMutateRowResponse response = bigtableServiceApiClient.CheckAndMutateRow(tableName, rowKey, predicateFilter, trueMutations, falseMutations, appProfileId);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRowAsync</summary>
public async Task CheckAndMutateRow2Async()
{
// Snippet: CheckAndMutateRowAsync(string, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, string, CallSettings)
// Additional: CheckAndMutateRowAsync(string, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, string, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new Mutation[] { new Mutation(), };
IEnumerable<Mutation> falseMutations = new Mutation[] { new Mutation(), };
string appProfileId = "";
// Make the request
CheckAndMutateRowResponse response = await bigtableServiceApiClient.CheckAndMutateRowAsync(tableName, rowKey, predicateFilter, trueMutations, falseMutations, appProfileId);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRow</summary>
public void CheckAndMutateRow2ResourceNames()
{
// Snippet: CheckAndMutateRow(TableName, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new Mutation[] { new Mutation(), };
IEnumerable<Mutation> falseMutations = new Mutation[] { new Mutation(), };
string appProfileId = "";
// Make the request
CheckAndMutateRowResponse response = bigtableServiceApiClient.CheckAndMutateRow(tableName, rowKey, predicateFilter, trueMutations, falseMutations, appProfileId);
// End snippet
}
/// <summary>Snippet for CheckAndMutateRowAsync</summary>
public async Task CheckAndMutateRow2ResourceNamesAsync()
{
// Snippet: CheckAndMutateRowAsync(TableName, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, string, CallSettings)
// Additional: CheckAndMutateRowAsync(TableName, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, string, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
RowFilter predicateFilter = new RowFilter();
IEnumerable<Mutation> trueMutations = new Mutation[] { new Mutation(), };
IEnumerable<Mutation> falseMutations = new Mutation[] { new Mutation(), };
string appProfileId = "";
// Make the request
CheckAndMutateRowResponse response = await bigtableServiceApiClient.CheckAndMutateRowAsync(tableName, rowKey, predicateFilter, trueMutations, falseMutations, appProfileId);
// End snippet
}
/// <summary>Snippet for PingAndWarm</summary>
public void PingAndWarmRequestObject()
{
// Snippet: PingAndWarm(PingAndWarmRequest, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
PingAndWarmRequest request = new PingAndWarmRequest
{
InstanceName = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
AppProfileId = "",
};
// Make the request
PingAndWarmResponse response = bigtableServiceApiClient.PingAndWarm(request);
// End snippet
}
/// <summary>Snippet for PingAndWarmAsync</summary>
public async Task PingAndWarmRequestObjectAsync()
{
// Snippet: PingAndWarmAsync(PingAndWarmRequest, CallSettings)
// Additional: PingAndWarmAsync(PingAndWarmRequest, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
PingAndWarmRequest request = new PingAndWarmRequest
{
InstanceName = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
AppProfileId = "",
};
// Make the request
PingAndWarmResponse response = await bigtableServiceApiClient.PingAndWarmAsync(request);
// End snippet
}
/// <summary>Snippet for PingAndWarm</summary>
public void PingAndWarm1()
{
// Snippet: PingAndWarm(string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/instances/[INSTANCE]";
// Make the request
PingAndWarmResponse response = bigtableServiceApiClient.PingAndWarm(name);
// End snippet
}
/// <summary>Snippet for PingAndWarmAsync</summary>
public async Task PingAndWarm1Async()
{
// Snippet: PingAndWarmAsync(string, CallSettings)
// Additional: PingAndWarmAsync(string, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/instances/[INSTANCE]";
// Make the request
PingAndWarmResponse response = await bigtableServiceApiClient.PingAndWarmAsync(name);
// End snippet
}
/// <summary>Snippet for PingAndWarm</summary>
public void PingAndWarm1ResourceNames()
{
// Snippet: PingAndWarm(InstanceName, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
InstanceName name = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
// Make the request
PingAndWarmResponse response = bigtableServiceApiClient.PingAndWarm(name);
// End snippet
}
/// <summary>Snippet for PingAndWarmAsync</summary>
public async Task PingAndWarm1ResourceNamesAsync()
{
// Snippet: PingAndWarmAsync(InstanceName, CallSettings)
// Additional: PingAndWarmAsync(InstanceName, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
InstanceName name = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
// Make the request
PingAndWarmResponse response = await bigtableServiceApiClient.PingAndWarmAsync(name);
// End snippet
}
/// <summary>Snippet for PingAndWarm</summary>
public void PingAndWarm2()
{
// Snippet: PingAndWarm(string, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/instances/[INSTANCE]";
string appProfileId = "";
// Make the request
PingAndWarmResponse response = bigtableServiceApiClient.PingAndWarm(name, appProfileId);
// End snippet
}
/// <summary>Snippet for PingAndWarmAsync</summary>
public async Task PingAndWarm2Async()
{
// Snippet: PingAndWarmAsync(string, string, CallSettings)
// Additional: PingAndWarmAsync(string, string, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/instances/[INSTANCE]";
string appProfileId = "";
// Make the request
PingAndWarmResponse response = await bigtableServiceApiClient.PingAndWarmAsync(name, appProfileId);
// End snippet
}
/// <summary>Snippet for PingAndWarm</summary>
public void PingAndWarm2ResourceNames()
{
// Snippet: PingAndWarm(InstanceName, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
InstanceName name = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
string appProfileId = "";
// Make the request
PingAndWarmResponse response = bigtableServiceApiClient.PingAndWarm(name, appProfileId);
// End snippet
}
/// <summary>Snippet for PingAndWarmAsync</summary>
public async Task PingAndWarm2ResourceNamesAsync()
{
// Snippet: PingAndWarmAsync(InstanceName, string, CallSettings)
// Additional: PingAndWarmAsync(InstanceName, string, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
InstanceName name = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
string appProfileId = "";
// Make the request
PingAndWarmResponse response = await bigtableServiceApiClient.PingAndWarmAsync(name, appProfileId);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRow</summary>
public void ReadModifyWriteRowRequestObject()
{
// Snippet: ReadModifyWriteRow(ReadModifyWriteRowRequest, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
ReadModifyWriteRowRequest request = new ReadModifyWriteRowRequest
{
TableNameAsTableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.Empty,
Rules =
{
new ReadModifyWriteRule(),
},
AppProfileId = "",
};
// Make the request
ReadModifyWriteRowResponse response = bigtableServiceApiClient.ReadModifyWriteRow(request);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRowAsync</summary>
public async Task ReadModifyWriteRowRequestObjectAsync()
{
// Snippet: ReadModifyWriteRowAsync(ReadModifyWriteRowRequest, CallSettings)
// Additional: ReadModifyWriteRowAsync(ReadModifyWriteRowRequest, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
ReadModifyWriteRowRequest request = new ReadModifyWriteRowRequest
{
TableNameAsTableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"),
RowKey = ByteString.Empty,
Rules =
{
new ReadModifyWriteRule(),
},
AppProfileId = "",
};
// Make the request
ReadModifyWriteRowResponse response = await bigtableServiceApiClient.ReadModifyWriteRowAsync(request);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRow</summary>
public void ReadModifyWriteRow1()
{
// Snippet: ReadModifyWriteRow(string, ByteString, IEnumerable<ReadModifyWriteRule>, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
IEnumerable<ReadModifyWriteRule> rules = new ReadModifyWriteRule[]
{
new ReadModifyWriteRule(),
};
// Make the request
ReadModifyWriteRowResponse response = bigtableServiceApiClient.ReadModifyWriteRow(tableName, rowKey, rules);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRowAsync</summary>
public async Task ReadModifyWriteRow1Async()
{
// Snippet: ReadModifyWriteRowAsync(string, ByteString, IEnumerable<ReadModifyWriteRule>, CallSettings)
// Additional: ReadModifyWriteRowAsync(string, ByteString, IEnumerable<ReadModifyWriteRule>, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
IEnumerable<ReadModifyWriteRule> rules = new ReadModifyWriteRule[]
{
new ReadModifyWriteRule(),
};
// Make the request
ReadModifyWriteRowResponse response = await bigtableServiceApiClient.ReadModifyWriteRowAsync(tableName, rowKey, rules);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRow</summary>
public void ReadModifyWriteRow1ResourceNames()
{
// Snippet: ReadModifyWriteRow(TableName, ByteString, IEnumerable<ReadModifyWriteRule>, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
IEnumerable<ReadModifyWriteRule> rules = new ReadModifyWriteRule[]
{
new ReadModifyWriteRule(),
};
// Make the request
ReadModifyWriteRowResponse response = bigtableServiceApiClient.ReadModifyWriteRow(tableName, rowKey, rules);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRowAsync</summary>
public async Task ReadModifyWriteRow1ResourceNamesAsync()
{
// Snippet: ReadModifyWriteRowAsync(TableName, ByteString, IEnumerable<ReadModifyWriteRule>, CallSettings)
// Additional: ReadModifyWriteRowAsync(TableName, ByteString, IEnumerable<ReadModifyWriteRule>, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
IEnumerable<ReadModifyWriteRule> rules = new ReadModifyWriteRule[]
{
new ReadModifyWriteRule(),
};
// Make the request
ReadModifyWriteRowResponse response = await bigtableServiceApiClient.ReadModifyWriteRowAsync(tableName, rowKey, rules);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRow</summary>
public void ReadModifyWriteRow2()
{
// Snippet: ReadModifyWriteRow(string, ByteString, IEnumerable<ReadModifyWriteRule>, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
IEnumerable<ReadModifyWriteRule> rules = new ReadModifyWriteRule[]
{
new ReadModifyWriteRule(),
};
string appProfileId = "";
// Make the request
ReadModifyWriteRowResponse response = bigtableServiceApiClient.ReadModifyWriteRow(tableName, rowKey, rules, appProfileId);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRowAsync</summary>
public async Task ReadModifyWriteRow2Async()
{
// Snippet: ReadModifyWriteRowAsync(string, ByteString, IEnumerable<ReadModifyWriteRule>, string, CallSettings)
// Additional: ReadModifyWriteRowAsync(string, ByteString, IEnumerable<ReadModifyWriteRule>, string, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]";
ByteString rowKey = ByteString.Empty;
IEnumerable<ReadModifyWriteRule> rules = new ReadModifyWriteRule[]
{
new ReadModifyWriteRule(),
};
string appProfileId = "";
// Make the request
ReadModifyWriteRowResponse response = await bigtableServiceApiClient.ReadModifyWriteRowAsync(tableName, rowKey, rules, appProfileId);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRow</summary>
public void ReadModifyWriteRow2ResourceNames()
{
// Snippet: ReadModifyWriteRow(TableName, ByteString, IEnumerable<ReadModifyWriteRule>, string, CallSettings)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
IEnumerable<ReadModifyWriteRule> rules = new ReadModifyWriteRule[]
{
new ReadModifyWriteRule(),
};
string appProfileId = "";
// Make the request
ReadModifyWriteRowResponse response = bigtableServiceApiClient.ReadModifyWriteRow(tableName, rowKey, rules, appProfileId);
// End snippet
}
/// <summary>Snippet for ReadModifyWriteRowAsync</summary>
public async Task ReadModifyWriteRow2ResourceNamesAsync()
{
// Snippet: ReadModifyWriteRowAsync(TableName, ByteString, IEnumerable<ReadModifyWriteRule>, string, CallSettings)
// Additional: ReadModifyWriteRowAsync(TableName, ByteString, IEnumerable<ReadModifyWriteRule>, string, CancellationToken)
// Create client
BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync();
// Initialize request argument(s)
TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]");
ByteString rowKey = ByteString.Empty;
IEnumerable<ReadModifyWriteRule> rules = new ReadModifyWriteRule[]
{
new ReadModifyWriteRule(),
};
string appProfileId = "";
// Make the request
ReadModifyWriteRowResponse response = await bigtableServiceApiClient.ReadModifyWriteRowAsync(tableName, rowKey, rules, appProfileId);
// End snippet
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: operations/note_requests_room_types/note_request_room_types.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 HOLMS.Types.Operations.NoteRequestsRoomTypes {
/// <summary>Holder for reflection information generated from operations/note_requests_room_types/note_request_room_types.proto</summary>
public static partial class NoteRequestRoomTypesReflection {
#region Descriptor
/// <summary>File descriptor for operations/note_requests_room_types/note_request_room_types.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static NoteRequestRoomTypesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkFvcGVyYXRpb25zL25vdGVfcmVxdWVzdHNfcm9vbV90eXBlcy9ub3RlX3Jl",
"cXVlc3Rfcm9vbV90eXBlcy5wcm90bxIvaG9sbXMudHlwZXMub3BlcmF0aW9u",
"cy5ub3RlX3JlcXVlc3RzX3Jvb21fdHlwZXMaSm9wZXJhdGlvbnMvbm90ZV9y",
"ZXF1ZXN0c19yb29tX3R5cGVzL25vdGVfcmVxdWVzdF9yb29tX3R5cGVfaW5k",
"aWNhdG9yLnByb3RvGjVvcGVyYXRpb25zL25vdGVfcmVxdWVzdHMvbm90ZV9y",
"ZXF1ZXN0X2luZGljYXRvci5wcm90bxorc3VwcGx5L3Jvb21fdHlwZXMvcm9v",
"bV90eXBlX2luZGljYXRvci5wcm90byKVAgoUTm90ZVJlcXVlc3RSb29tVHlw",
"ZXMSYAoJZW50aXR5X2lkGAEgASgLMk0uaG9sbXMudHlwZXMub3BlcmF0aW9u",
"cy5ub3RlX3JlcXVlc3RzX3Jvb21fdHlwZXMuTm90ZVJlcXVlc3RSb29tVHlw",
"ZUluZGljYXRvchJTCg9ub3RlX3JlcXVlc3RfaWQYAiABKAsyOi5ob2xtcy50",
"eXBlcy5vcGVyYXRpb25zLm5vdGVfcmVxdWVzdHMuTm90ZVJlcXVlc3RJbmRp",
"Y2F0b3ISRgoMcm9vbV90eXBlX2lkGAMgASgLMjAuaG9sbXMudHlwZXMuc3Vw",
"cGx5LnJvb21fdHlwZXMuUm9vbVR5cGVJbmRpY2F0b3JCUVogb3BlcmF0aW9u",
"cy9ub3RlcmVxdWVzdHNyb29tdHlwZXOqAixIT0xNUy5UeXBlcy5PcGVyYXRp",
"b25zLk5vdGVSZXF1ZXN0c1Jvb21UeXBlc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Operations.NoteRequestsRoomTypes.NoteRequestRoomTypeIndicatorReflection.Descriptor, global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicatorReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.NoteRequestsRoomTypes.NoteRequestRoomTypes), global::HOLMS.Types.Operations.NoteRequestsRoomTypes.NoteRequestRoomTypes.Parser, new[]{ "EntityId", "NoteRequestId", "RoomTypeId" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class NoteRequestRoomTypes : pb::IMessage<NoteRequestRoomTypes> {
private static readonly pb::MessageParser<NoteRequestRoomTypes> _parser = new pb::MessageParser<NoteRequestRoomTypes>(() => new NoteRequestRoomTypes());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<NoteRequestRoomTypes> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.NoteRequestsRoomTypes.NoteRequestRoomTypesReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NoteRequestRoomTypes() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NoteRequestRoomTypes(NoteRequestRoomTypes other) : this() {
EntityId = other.entityId_ != null ? other.EntityId.Clone() : null;
NoteRequestId = other.noteRequestId_ != null ? other.NoteRequestId.Clone() : null;
RoomTypeId = other.roomTypeId_ != null ? other.RoomTypeId.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NoteRequestRoomTypes Clone() {
return new NoteRequestRoomTypes(this);
}
/// <summary>Field number for the "entity_id" field.</summary>
public const int EntityIdFieldNumber = 1;
private global::HOLMS.Types.Operations.NoteRequestsRoomTypes.NoteRequestRoomTypeIndicator entityId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.NoteRequestsRoomTypes.NoteRequestRoomTypeIndicator EntityId {
get { return entityId_; }
set {
entityId_ = value;
}
}
/// <summary>Field number for the "note_request_id" field.</summary>
public const int NoteRequestIdFieldNumber = 2;
private global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator noteRequestId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator NoteRequestId {
get { return noteRequestId_; }
set {
noteRequestId_ = value;
}
}
/// <summary>Field number for the "room_type_id" field.</summary>
public const int RoomTypeIdFieldNumber = 3;
private global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator roomTypeId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator RoomTypeId {
get { return roomTypeId_; }
set {
roomTypeId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as NoteRequestRoomTypes);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(NoteRequestRoomTypes other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(EntityId, other.EntityId)) return false;
if (!object.Equals(NoteRequestId, other.NoteRequestId)) return false;
if (!object.Equals(RoomTypeId, other.RoomTypeId)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (entityId_ != null) hash ^= EntityId.GetHashCode();
if (noteRequestId_ != null) hash ^= NoteRequestId.GetHashCode();
if (roomTypeId_ != null) hash ^= RoomTypeId.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 (entityId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(EntityId);
}
if (noteRequestId_ != null) {
output.WriteRawTag(18);
output.WriteMessage(NoteRequestId);
}
if (roomTypeId_ != null) {
output.WriteRawTag(26);
output.WriteMessage(RoomTypeId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (entityId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId);
}
if (noteRequestId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(NoteRequestId);
}
if (roomTypeId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomTypeId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(NoteRequestRoomTypes other) {
if (other == null) {
return;
}
if (other.entityId_ != null) {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Operations.NoteRequestsRoomTypes.NoteRequestRoomTypeIndicator();
}
EntityId.MergeFrom(other.EntityId);
}
if (other.noteRequestId_ != null) {
if (noteRequestId_ == null) {
noteRequestId_ = new global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator();
}
NoteRequestId.MergeFrom(other.NoteRequestId);
}
if (other.roomTypeId_ != null) {
if (roomTypeId_ == null) {
roomTypeId_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator();
}
RoomTypeId.MergeFrom(other.RoomTypeId);
}
}
[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: {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Operations.NoteRequestsRoomTypes.NoteRequestRoomTypeIndicator();
}
input.ReadMessage(entityId_);
break;
}
case 18: {
if (noteRequestId_ == null) {
noteRequestId_ = new global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator();
}
input.ReadMessage(noteRequestId_);
break;
}
case 26: {
if (roomTypeId_ == null) {
roomTypeId_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator();
}
input.ReadMessage(roomTypeId_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
* 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 System;
using System.Collections.Generic;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Statistics;
using OpenSim.Services.Connectors;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
public class RemoteInventoryServicesConnector : BaseInventoryConnector, ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private bool m_Initialized = false;
private Scene m_Scene;
private InventoryServicesConnector m_RemoteConnector;
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "RemoteInventoryServicesConnector"; }
}
public RemoteInventoryServicesConnector()
{
}
public RemoteInventoryServicesConnector(IConfigSource source)
{
Init(source);
}
protected override void Init(IConfigSource source)
{
m_RemoteConnector = new InventoryServicesConnector(source);
base.Init(source);
}
#region ISharedRegionModule
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
Init(source);
m_Enabled = true;
m_log.Info("[INVENTORY CONNECTOR]: Remote inventory enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
m_Scene = scene;
//m_log.Debug("[XXXX] Adding scene " + m_Scene.RegionInfo.RegionName);
if (!m_Enabled)
return;
if (!m_Initialized)
{
m_Initialized = true;
}
scene.RegisterModuleInterface<IInventoryService>(this);
m_cache.AddRegion(scene);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_cache.RemoveRegion(scene);
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[INVENTORY CONNECTOR]: Enabled remote inventory for region {0}", scene.RegionInfo.RegionName);
}
#endregion ISharedRegionModule
#region IInventoryService
public override bool CreateUserInventory(UUID user)
{
return false;
}
public override List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
return new List<InventoryFolderBase>();
}
public override InventoryCollection GetUserInventory(UUID userID)
{
return null;
}
public override void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
{
UUID sessionID = GetSessionID(userID);
try
{
m_RemoteConnector.GetUserInventory(userID.ToString(), sessionID, callback);
}
catch (Exception e)
{
if (StatsManager.SimExtraStats != null)
StatsManager.SimExtraStats.AddInventoryServiceRetrievalFailure();
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Request inventory operation failed, {0} {1}",
e.Source, e.Message);
}
}
// inherited. See base class
// public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
public override Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID)
{
UUID sessionID = GetSessionID(userID);
return m_RemoteConnector.GetSystemFolders(userID.ToString(), sessionID);
}
public override InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
UUID sessionID = GetSessionID(userID);
try
{
return m_RemoteConnector.GetFolderContent(userID.ToString(), folderID, sessionID);
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetFolderContent operation failed, {0} {1}",
e.Source, e.Message);
}
InventoryCollection nullCollection = new InventoryCollection();
nullCollection.Folders = new List<InventoryFolderBase>();
nullCollection.Items = new List<InventoryItemBase>();
nullCollection.UserID = userID;
return nullCollection;
}
public override List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
UUID sessionID = GetSessionID(userID);
return m_RemoteConnector.GetFolderItems(userID.ToString(), folderID, sessionID);
}
public override bool AddFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
UUID sessionID = GetSessionID(folder.Owner);
return m_RemoteConnector.AddFolder(folder.Owner.ToString(), folder, sessionID);
}
public override bool UpdateFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
UUID sessionID = GetSessionID(folder.Owner);
return m_RemoteConnector.UpdateFolder(folder.Owner.ToString(), folder, sessionID);
}
public override bool MoveFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
UUID sessionID = GetSessionID(folder.Owner);
return m_RemoteConnector.MoveFolder(folder.Owner.ToString(), folder, sessionID);
}
public override bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
if (folderIDs == null)
return false;
if (folderIDs.Count == 0)
return false;
UUID sessionID = GetSessionID(ownerID);
return m_RemoteConnector.DeleteFolders(ownerID.ToString(), folderIDs, sessionID);
}
public override bool PurgeFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
UUID sessionID = GetSessionID(folder.Owner);
return m_RemoteConnector.PurgeFolder(folder.Owner.ToString(), folder, sessionID);
}
// public bool AddItem(InventoryItemBase item) inherited
// Uses AddItemPlain
protected override bool AddItemPlain(InventoryItemBase item)
{
if (item == null)
return false;
UUID sessionID = GetSessionID(item.Owner);
return m_RemoteConnector.AddItem(item.Owner.ToString(), item, sessionID);
}
public override bool UpdateItem(InventoryItemBase item)
{
if (item == null)
return false;
UUID sessionID = GetSessionID(item.Owner);
return m_RemoteConnector.UpdateItem(item.Owner.ToString(), item, sessionID);
}
public override bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
if (items == null)
return false;
UUID sessionID = GetSessionID(ownerID);
return m_RemoteConnector.MoveItems(ownerID.ToString(), items, sessionID);
}
public override bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
if (itemIDs == null)
return false;
if (itemIDs.Count == 0)
return true;
UUID sessionID = GetSessionID(ownerID);
return m_RemoteConnector.DeleteItems(ownerID.ToString(), itemIDs, sessionID);
}
public override InventoryItemBase GetItem(InventoryItemBase item)
{
if (item == null)
return null;
UUID sessionID = GetSessionID(item.Owner);
return m_RemoteConnector.QueryItem(item.Owner.ToString(), item, sessionID);
}
public override InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
if (folder == null)
return null;
UUID sessionID = GetSessionID(folder.Owner);
return m_RemoteConnector.QueryFolder(folder.Owner.ToString(), folder, sessionID);
}
public override bool HasInventoryForUser(UUID userID)
{
return false;
}
public override List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return new List<InventoryItemBase>();
}
public override int GetAssetPermissions(UUID userID, UUID assetID)
{
UUID sessionID = GetSessionID(userID);
return m_RemoteConnector.GetAssetPermissions(userID.ToString(), assetID, sessionID);
}
#endregion
private UUID GetSessionID(UUID userID)
{
return UUID.Zero;
}
}
}
| |
/* ====================================================================
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 TestCases.SS.Formula.Functions
{
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using System;
using NUnit.Framework;
using TestCases.HSSF;
using NPOI.HSSF.UserModel;
using System.Text;
using NPOI.SS.Util;
using System.IO;
using NPOI.Util;
/**
* Tests INDEX() as loaded from a Test data spreadsheet.<p/>
*
* @author Josh Micich
*/
[TestFixture]
public abstract class BaseTestFunctionsFromSpreadsheet
{
private static class Result
{
public const int SOME_EVALUATIONS_FAILED = -1;
public const int ALL_EVALUATIONS_SUCCEEDED = +1;
public const int NO_EVALUATIONS_FOUND = 0;
}
/**
* This class defines constants for navigating around the Test data spreadsheet used for these Tests.
*/
private static class SS
{
/** Name of the first sheet in the spreadsheet (contains comments) */
public const String README_SHEET_NAME = "Read Me";
/** Row (zero-based) in each sheet where the evaluation cases start. */
public const int START_TEST_CASES_ROW_INDEX = 4; // Row '5'
/** Index of the column that contains the function names */
public const int COLUMN_INDEX_MARKER = 0; // Column 'A'
public const int COLUMN_INDEX_EVALUATION = 1; // Column 'B'
public const int COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C'
public const int COLUMN_ROW_COMMENT = 3; // Column 'D'
/** Used to indicate when there are no more test cases on the current sheet */
public const String TEST_CASES_END_MARKER = "<end>";
/** Used to indicate that the test on the current row should be ignored */
public const String SKIP_CURRENT_TEST_CASE_MARKER = "<skip>";
}
private int _sheetFailureCount;
private int _sheetSuccessCount;
// Note - multiple failures are aggregated before ending.
// If one or more functions fail, a single AssertionException is thrown at the end
private int _evaluationFailureCount;
private int _evaluationSuccessCount;
private static void ConfirmExpectedResult(String msg, ICell expected, CellValue actual)
{
if (expected == null)
{
throw new AssertionException(msg + " - Bad Setup data expected value is null");
}
if (actual == null)
{
throw new AssertionException(msg + " - actual value was null");
}
if (expected.CellType == CellType.Error)
{
ConfirmErrorResult(msg, expected.ErrorCellValue, actual);
return;
}
if (actual.CellType == CellType.Error)
{
throw unexpectedError(msg, expected, actual.ErrorValue);
}
if (actual.CellType != expected.CellType)
{
throw wrongTypeError(msg, expected, actual);
}
switch (expected.CellType)
{
case CellType.Boolean:
Assert.AreEqual(expected.BooleanCellValue, actual.BooleanValue, msg);
break;
case CellType.Formula: // will never be used, since we will call method After formula Evaluation
throw new AssertionException("Cannot expect formula as result of formula Evaluation: " + msg);
case CellType.Numeric:
Assert.AreEqual(expected.NumericCellValue, actual.NumberValue, 0.0, msg);
break;
case CellType.String:
Assert.AreEqual(expected.RichStringCellValue.String, actual.StringValue, msg);
break;
}
}
private static AssertionException wrongTypeError(String msgPrefix, ICell expectedCell, CellValue actualValue)
{
return new AssertionException(msgPrefix + " Result type mismatch. Evaluated result was "
+ actualValue.FormatAsString()
+ " but the expected result was "
+ formatValue(expectedCell)
);
}
private static AssertionException unexpectedError(String msgPrefix, ICell expected, int actualErrorCode)
{
return new AssertionException(msgPrefix + " Error code ("
+ ErrorEval.GetText(actualErrorCode)
+ ") was Evaluated, but the expected result was "
+ formatValue(expected)
);
}
private static void ConfirmErrorResult(String msgPrefix, int expectedErrorCode, CellValue actual)
{
if (actual.CellType != CellType.Error)
{
throw new AssertionException(msgPrefix + " Expected cell error ("
+ ErrorEval.GetText(expectedErrorCode) + ") but actual value was "
+ actual.FormatAsString());
}
if (expectedErrorCode != actual.ErrorValue)
{
throw new AssertionException(msgPrefix + " Expected cell error code ("
+ ErrorEval.GetText(expectedErrorCode)
+ ") but actual error code was ("
+ ErrorEval.GetText(actual.ErrorValue)
+ ")");
}
}
private static String formatValue(ICell expecedCell)
{
switch (expecedCell.CellType)
{
case CellType.Blank: return "<blank>";
case CellType.Boolean: return expecedCell.BooleanCellValue.ToString();
case CellType.Numeric: return expecedCell.NumericCellValue.ToString();
case CellType.String: return expecedCell.RichStringCellValue.String;
}
throw new Exception("Unexpected cell type of expected value (" + expecedCell.CellType + ")");
}
[SetUp]
public void SetUp()
{
_sheetFailureCount = 0;
_sheetSuccessCount = 0;
_evaluationFailureCount = 0;
_evaluationSuccessCount = 0;
}
[Test]
public void TestFunctionsFromTestSpreadsheet()
{
HSSFWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook(this.Filename);
confirmReadMeSheet(workbook);
int nSheets = workbook.NumberOfSheets;
for (int i = 1; i < nSheets; i++)
{
int sheetResult = ProcessTestSheet(workbook, i, workbook.GetSheetName(i));
switch (sheetResult)
{
case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount++; break;
case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount++; break;
}
}
// confirm results
String successMsg = "There were "
+ _sheetSuccessCount + " successful sheets(s) and "
+ _evaluationSuccessCount + " function(s) without error";
if (_sheetFailureCount > 0)
{
String msg = _sheetFailureCount + " sheets(s) failed with "
+ _evaluationFailureCount + " evaluation(s). " + successMsg;
throw new AssertionException(msg);
}
#if !HIDE_UNREACHABLE_CODE
if (false)
{ // normally no output for successful Tests
Console.WriteLine(this.GetType().Name + ": " + successMsg);
}
#endif
}
private int ProcessTestSheet(HSSFWorkbook workbook, int sheetIndex, String sheetName)
{
ISheet sheet = workbook.GetSheetAt(sheetIndex);
HSSFFormulaEvaluator Evaluator = new HSSFFormulaEvaluator(workbook);
int maxRows = sheet.LastRowNum + 1;
int result = Result.NO_EVALUATIONS_FOUND; // so far
String currentGroupComment = null;
for (int rowIndex = SS.START_TEST_CASES_ROW_INDEX; rowIndex < maxRows; rowIndex++)
{
IRow r = sheet.GetRow(rowIndex);
String newMarkerValue = GetMarkerColumnValue(r);
if (r == null)
{
continue;
}
if (SS.TEST_CASES_END_MARKER.Equals(newMarkerValue, StringComparison.InvariantCultureIgnoreCase))
{
// normal exit point
return result;
}
if (SS.SKIP_CURRENT_TEST_CASE_MARKER.Equals(newMarkerValue, StringComparison.InvariantCultureIgnoreCase))
{
// currently disabled test case row
continue;
}
if (newMarkerValue != null)
{
currentGroupComment = newMarkerValue;
}
ICell c = r.GetCell(SS.COLUMN_INDEX_EVALUATION);
if (c == null || c.CellType != CellType.Formula)
{
continue;
}
ICell expectedValueCell = r.GetCell(SS.COLUMN_INDEX_EXPECTED_RESULT);
String rowComment = GetRowCommentColumnValue(r);
String msgPrefix = formatTestCaseDetails(this.Filename,sheetName, r.RowNum, c, currentGroupComment, rowComment);
try
{
CellValue actualValue = Evaluator.Evaluate(c);
ConfirmExpectedResult(msgPrefix, expectedValueCell, actualValue);
_evaluationSuccessCount++;
if (result != Result.SOME_EVALUATIONS_FAILED)
{
result = Result.ALL_EVALUATIONS_SUCCEEDED;
}
}
catch (RuntimeException e)
{
_evaluationFailureCount++;
printshortStackTrace(System.Console.Error, e);
result = Result.SOME_EVALUATIONS_FAILED;
}
catch (AssertionException e)
{
_evaluationFailureCount++;
printshortStackTrace(System.Console.Error, e);
result = Result.SOME_EVALUATIONS_FAILED;
}
}
throw new Exception("Missing end marker '" + SS.TEST_CASES_END_MARKER
+ "' on sheet '" + sheetName + "'");
}
protected abstract String Filename
{
get;
}
private static String formatTestCaseDetails(String filename, String sheetName, int rowIndex, ICell c, String currentGroupComment,
String rowComment)
{
StringBuilder sb = new StringBuilder();
sb.Append("In ").Append(filename).Append(" ");
CellReference cr = new CellReference(sheetName, rowIndex, c.ColumnIndex, false, false);
sb.Append(cr.FormatAsString());
sb.Append(" {=").Append(c.CellFormula).Append("}");
if (currentGroupComment != null)
{
sb.Append(" '");
sb.Append(currentGroupComment);
if (rowComment != null)
{
sb.Append(" - ");
sb.Append(rowComment);
}
sb.Append("' ");
}
else
{
if (rowComment != null)
{
sb.Append(" '");
sb.Append(rowComment);
sb.Append("' ");
}
}
return sb.ToString();
}
/**
* Asserts that the 'read me' comment page exists, and has this class' name in one of the
* cells. This back-link is to make it easy to find this class if a reader encounters the
* spreadsheet first.
*/
private void confirmReadMeSheet(HSSFWorkbook workbook)
{
String firstSheetName = workbook.GetSheetName(0);
if (!firstSheetName.Equals(SS.README_SHEET_NAME, StringComparison.InvariantCultureIgnoreCase))
{
throw new Exception("First sheet's name was '" + firstSheetName + "' but expected '" + SS.README_SHEET_NAME + "'");
}
//ISheet sheet = workbook.GetSheetAt(0);
//String specifiedClassName = sheet.GetRow(2).GetCell(0).RichStringCellValue.String;
//Assert.AreEqual(this.GetType().FullName, specifiedClassName, "Test class name in spreadsheet comment");
}
/**
* Useful to keep output concise when expecting many failures to be reported by this Test case
*/
private static void printshortStackTrace(TextWriter ps, Exception e)
{
ps.WriteLine(e.Message);
ps.WriteLine(e.StackTrace);
//StackTraceElement[] stes = e.GetStackTrace();
//int startIx = 0;
//// skip any top frames inside junit.framework.Assert
//while(startIx<stes.Length) {
// if(!stes[startIx].GetClassName().Equals(typeof(Assert).Name)) {
// break;
// }
// startIx++;
//}
//// skip bottom frames (part of junit framework)
//int endIx = startIx+1;
//while(endIx < stes.Length) {
// if(stes[endIx].GetClassName().Equals(TestCase.class.GetName())) {
// break;
// }
// endIx++;
//}
//if(startIx >= endIx) {
// // something went wrong. just print the whole stack trace
// e.printStackTrace(ps);
//}
//endIx -= 4; // skip 4 frames of reflection invocation
//ps.println(e.ToString());
//for(int i=startIx; i<endIx; i++) {
// ps.println("\tat " + stes[i].ToString());
//}
}
private static String GetRowCommentColumnValue(IRow r)
{
return GetCellTextValue(r, SS.COLUMN_ROW_COMMENT, "row comment");
}
private static String GetMarkerColumnValue(IRow r)
{
return GetCellTextValue(r, SS.COLUMN_INDEX_MARKER, "marker");
}
/**
* @return <code>null</code> if cell is missing, empty or blank
*/
private static String GetCellTextValue(IRow r, int colIndex, String columnName)
{
if (r == null)
{
return null;
}
ICell cell = r.GetCell(colIndex);
if (cell == null)
{
return null;
}
if (cell.CellType == CellType.Blank)
{
return null;
}
if (cell.CellType == CellType.String)
{
return cell.RichStringCellValue.String;
}
throw new Exception("Bad cell type for '" + columnName + "' column: ("
+ cell.CellType + ") row (" + (r.RowNum + 1) + ")");
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// 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.
//
namespace NLog.Internal.NetworkSenders
{
using System;
using System.IO;
using System.Net.Sockets;
using NLog.Common;
/// <summary>
/// Sends messages over a TCP network connection.
/// </summary>
internal class TcpNetworkSender : QueuedNetworkSender
{
private static bool? EnableKeepAliveSuccessful;
private ISocket _socket;
private readonly EventHandler<SocketAsyncEventArgs> _socketOperationCompletedAsync;
private AsyncHelpersTask? _asyncBeginRequest;
/// <summary>
/// Initializes a new instance of the <see cref="TcpNetworkSender"/> class.
/// </summary>
/// <param name="url">URL. Must start with tcp://.</param>
/// <param name="addressFamily">The address family.</param>
public TcpNetworkSender(string url, AddressFamily addressFamily)
: base(url)
{
AddressFamily = addressFamily;
_socketOperationCompletedAsync = SocketOperationCompletedAsync;
}
internal AddressFamily AddressFamily { get; set; }
internal System.Security.Authentication.SslProtocols SslProtocols { get; set; }
internal TimeSpan KeepAliveTime { get; set; }
/// <summary>
/// Creates the socket with given parameters.
/// </summary>
/// <param name="host">The host address.</param>
/// <param name="addressFamily">The address family.</param>
/// <param name="socketType">Type of the socket.</param>
/// <param name="protocolType">Type of the protocol.</param>
/// <returns>Instance of <see cref="ISocket" /> which represents the socket.</returns>
protected internal virtual ISocket CreateSocket(string host, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
var socketProxy = new SocketProxy(addressFamily, socketType, protocolType);
if (KeepAliveTime.TotalSeconds >= 1.0 && EnableKeepAliveSuccessful != false)
{
EnableKeepAliveSuccessful = TryEnableKeepAlive(socketProxy.UnderlyingSocket, (int)KeepAliveTime.TotalSeconds);
}
#if !NETSTANDARD1_3 && !NETSTANDARD1_5
if (SslProtocols != System.Security.Authentication.SslProtocols.None)
{
return new SslSocketProxy(host, SslProtocols, socketProxy);
}
#endif
return socketProxy;
}
private static bool TryEnableKeepAlive(Socket underlyingSocket, int keepAliveTimeSeconds)
{
if (TrySetSocketOption(underlyingSocket, SocketOptionName.KeepAlive, true))
{
// SOCKET OPTION NAME CONSTANT
// Ws2ipdef.h (Windows SDK)
// #define TCP_KEEPALIVE 3
// #define TCP_KEEPINTVL 17
SocketOptionName TcpKeepAliveTime = (SocketOptionName)0x3;
SocketOptionName TcpKeepAliveInterval = (SocketOptionName)0x11;
if (PlatformDetector.CurrentOS == RuntimeOS.Linux)
{
// https://github.com/torvalds/linux/blob/v4.16/include/net/tcp.h
// #define TCP_KEEPIDLE 4 /* Start keepalives after this period */
// #define TCP_KEEPINTVL 5 /* Interval between keepalives */
TcpKeepAliveTime = (SocketOptionName)0x4;
TcpKeepAliveInterval = (SocketOptionName)0x5;
}
else if (PlatformDetector.CurrentOS == RuntimeOS.MacOSX)
{
// https://opensource.apple.com/source/xnu/xnu-4570.41.2/bsd/netinet/tcp.h.auto.html
// #define TCP_KEEPALIVE 0x10 /* idle time used when SO_KEEPALIVE is enabled */
// #define TCP_KEEPINTVL 0x101 /* interval between keepalives */
TcpKeepAliveTime = (SocketOptionName)0x10;
TcpKeepAliveInterval = (SocketOptionName)0x101;
}
if (TrySetTcpOption(underlyingSocket, TcpKeepAliveTime, keepAliveTimeSeconds))
{
// Configure retransmission interval when missing acknowledge of keep-alive-probe
TrySetTcpOption(underlyingSocket, TcpKeepAliveInterval, 1); // Default 1 sec on Windows (75 sec on Linux)
return true;
}
}
return false;
}
private static bool TrySetSocketOption(Socket underlyingSocket, SocketOptionName socketOption, bool value)
{
try
{
underlyingSocket.SetSocketOption(SocketOptionLevel.Socket, socketOption, value);
return true;
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "NetworkTarget: Failed to configure Socket-option {0} = {1}", socketOption, value);
return false;
}
}
private static bool TrySetTcpOption(Socket underlyingSocket, SocketOptionName socketOption, int value)
{
try
{
underlyingSocket.SetSocketOption(SocketOptionLevel.Tcp, socketOption, value);
return true;
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "NetworkTarget: Failed to configure TCP-option {0} = {1}", socketOption, value);
return false;
}
}
protected override void DoInitialize()
{
var uri = new Uri(Address);
var args = new MySocketAsyncEventArgs();
args.RemoteEndPoint = ParseEndpointAddress(uri, AddressFamily);
args.Completed += _socketOperationCompletedAsync;
args.UserToken = null;
_socket = CreateSocket(uri.Host, args.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
base.BeginInitialize();
bool asyncOperation = false;
try
{
asyncOperation = _socket.ConnectAsync(args);
}
catch (SocketException ex)
{
args.SocketError = ex.SocketErrorCode;
}
catch (Exception ex)
{
if (ex.InnerException is SocketException socketException)
args.SocketError = socketException.SocketErrorCode;
else
args.SocketError = SocketError.OperationAborted;
}
if (!asyncOperation)
{
SocketOperationCompletedAsync(_socket, args);
}
}
protected override void DoClose(AsyncContinuation continuation)
{
base.DoClose(ex => CloseSocket(continuation, ex));
}
private void CloseSocket(AsyncContinuation continuation, Exception pendingException)
{
try
{
var sock = _socket;
_socket = null;
sock?.Close();
continuation(pendingException);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
continuation(exception);
}
}
protected override void BeginRequest(NetworkRequestArgs eventArgs)
{
var socketEventArgs = new MySocketAsyncEventArgs();
socketEventArgs.Completed += _socketOperationCompletedAsync;
SetSocketNetworkRequest(socketEventArgs, eventArgs);
// Schedule async network operation to avoid blocking socket-operation (Allow adding more request)
if (_asyncBeginRequest is null)
_asyncBeginRequest = new AsyncHelpersTask(BeginRequestAsync);
AsyncHelpers.StartAsyncTask(_asyncBeginRequest.Value, socketEventArgs);
}
private void BeginRequestAsync(object state)
{
BeginSocketRequest((SocketAsyncEventArgs)state);
}
private void BeginSocketRequest(SocketAsyncEventArgs args)
{
bool asyncOperation = false;
do
{
try
{
asyncOperation = _socket.SendAsync(args);
}
catch (SocketException ex)
{
InternalLogger.Error(ex, "NetworkTarget: Error sending tcp request");
args.SocketError = ex.SocketErrorCode;
}
catch (Exception ex)
{
InternalLogger.Error(ex, "NetworkTarget: Error sending tcp request");
if (ex.InnerException is SocketException socketException)
args.SocketError = socketException.SocketErrorCode;
else
args.SocketError = SocketError.OperationAborted;
}
args = asyncOperation ? null : SocketOperationCompleted(args);
}
while (args != null);
}
private void SetSocketNetworkRequest(SocketAsyncEventArgs socketEventArgs, NetworkRequestArgs networkRequest)
{
socketEventArgs.SetBuffer(networkRequest.RequestBuffer, networkRequest.RequestBufferOffset, networkRequest.RequestBufferLength);
socketEventArgs.UserToken = networkRequest.AsyncContinuation;
}
private void SocketOperationCompletedAsync(object sender, SocketAsyncEventArgs args)
{
var nextRequest = SocketOperationCompleted(args);
if (nextRequest != null)
{
BeginSocketRequest(nextRequest);
}
}
private SocketAsyncEventArgs SocketOperationCompleted(SocketAsyncEventArgs args)
{
Exception socketException = null;
if (args.SocketError != SocketError.Success)
{
socketException = new IOException($"Error: {args.SocketError.ToString()}, Address: {Address}");
}
var asyncContinuation = args.UserToken as AsyncContinuation;
var nextRequest = EndRequest(asyncContinuation, socketException);
if (nextRequest.HasValue)
{
SetSocketNetworkRequest(args, nextRequest.Value);
return args;
}
else
{
args.Completed -= _socketOperationCompletedAsync;
args.Dispose();
return null;
}
}
public override void CheckSocket()
{
if (_socket is null)
{
DoInitialize();
}
}
/// <summary>
/// Facilitates mocking of <see cref="SocketAsyncEventArgs"/> class.
/// </summary>
internal class MySocketAsyncEventArgs : SocketAsyncEventArgs
{
/// <summary>
/// Raises the Completed event.
/// </summary>
public void RaiseCompleted()
{
OnCompleted(this);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Xml;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Epi.Windows.Dialogs
{
/// <summary>
/// Class UserDialog
/// </summary>
/// <remarks>The dialog that is created when the pgm invokes the DIALOG command</remarks>
public partial class UserDialog : DialogBase
{
#region Private Attributes
private String _value = string.Empty;
private XmlDocument _doc = null;
private String title = String.Empty;
#endregion Private Attributes
#region Constructors
/// <summary>
/// Default constructor - NOT TO BE USED FOR INSTANTIATION
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public UserDialog()
{
InitializeComponent();
}
/// <summary>
/// UserDialog Constructor
/// </summary>
/// <param name="frm">Analysis module parent form</param>
/// <param name="doc">UserDialog.xml template</param>
public UserDialog(MainForm frm, XmlDocument doc)
: base(frm)
{
_doc = doc;
InitializeComponent();
title = frm.Text;
Construct(doc);
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Public property value
/// </summary>
/// <remarks>The value (if any) that the user entered/selected</remarks>
public string Value
{
get
{
return _value;
}
}
#endregion Public Properties
#region Private Methods
/// <summary>
/// UI Setup Code for UserDialog Constructor
/// </summary>
/// <param name="controls">UserDialog.xml UserDialog/Controls node</param>
private void SetControls(XmlNode controls)
{
foreach (XmlElement control in controls)
{
string controlName = control.Name;
bool isVisible = (control.Attributes["Visible"].Value.ToString() != "0");
// DEFECT #238
if (controlName.StartsWith("btn"))
{
panel2.Controls[controlName].Visible = isVisible;
}
else
{
panel1.Controls[controlName].Visible = isVisible;
if (controlName == "txt1")
{
int maxLen;
if (int.TryParse(StripQuotes(control.Attributes["MaxLength"].Value), out maxLen))
{
((TextBox)panel1.Controls[controlName]).MaxLength = maxLen;
}
}
}
}
}
private void FillList(ComboBox cmb, XmlNode node)
{
cmb.Items.Clear();
foreach (XmlElement element in node.ChildNodes)
{
// cmb.Items.Add(element.Name);
cmb.Items.Add(element.Attributes["Value"].Value.ToString());
}
}
/// <summary>
/// StripQuotes
/// </summary>
/// <remarks>Just to make it more understandable</remarks>
/// <param name="quotedString"></param>
/// <returns>Literal minus Epi.StringLiterals.DOUBLEQUOTES</returns>
private string StripQuotes(string quotedString)
{
return quotedString.Replace(StringLiterals.DOUBLEQUOTES, string.Empty);
}
/// <summary>
/// UI Setup Code for UserDialog Constructor
/// </summary>
/// <param name="doc">UserDialog.xml template</param>
private void Construct(XmlDocument doc)
{
//DEFECT #238
XmlElement xmlDocElement = doc.DocumentElement;
if (xmlDocElement != null)
{
this.Text = StripQuotes(xmlDocElement.GetAttribute("Title"));
if (String.IsNullOrEmpty(Text))
//dcs0 9/25 use a default title.
{
Text = title;
}
Prompt.Text = StripQuotes(xmlDocElement.GetAttribute("Prompt"));
string mask = StripQuotes(xmlDocElement.GetAttribute("Mask"));
dtp1.Format = (string.IsNullOrEmpty(mask)) ? DateTimePickerFormat.Short : DateTimePickerFormat.Custom;
dtp1.CustomFormat = mask;
mtb1.Mask = mask;
XmlNode controls = doc.SelectSingleNode("/UserDialog/Controls");
SetControls(controls);
if (xmlDocElement.GetAttribute("DialogType") == "Simple")
{
Prompt.Dock = DockStyle.Fill;
}
else
{
// dcs0 don't check the visible attribute (it's not valid at this time), just fill 'er up
FillList(cmb1, doc.SelectSingleNode("/UserDialog/ListItems"));
}
}
}
#endregion Private Methods
#region Event handlers
private void btnOk_Click(object sender, EventArgs e)
{
if (this.mtb1.Visible)
{
_value = mtb1.Text;
}
else if (this.cmb1.Visible)
{
_value = cmb1.Text;
}
else if (this.dtp1.Visible)
{
_value = dtp1.Text;
// Parser will not handle the AM/PM indicator, so convert it to 24 hr time
DateTime aDate = DateTime.Now;
if (DateTime.TryParse(_value, out aDate))
{
string fmt = dtp1.CustomFormat.Replace(" tt", "").Replace("h", "H");
_value = aDate.ToString(fmt);
}
}
else if (this.txt1.Visible)
{
_value = txt1.Text;
}
_doc.DocumentElement.SetAttribute("VarValue", _value);
Close();
}
private void btnYes_Click(object sender, EventArgs e)
{
_value = "(+)";
_doc.DocumentElement.SetAttribute("VarValue", _value);
Close();
}
private void btnNo_Click(object sender, EventArgs e)
{
_value = "(-)";
_doc.DocumentElement.SetAttribute("VarValue", _value);
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
#endregion Event handlers
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryShiftTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckByteShiftTest(bool useInterpreter)
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyByteShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableByteShiftTest(bool useInterpreter)
{
byte?[] array = { 0, 1, byte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableByteShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckSByteShiftTest(bool useInterpreter)
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifySByteShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableSByteShiftTest(bool useInterpreter)
{
sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableSByteShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortShiftTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyUShortShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortShiftTest(bool useInterpreter)
{
ushort?[] array = { 0, 1, ushort.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableUShortShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortShiftTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyShortShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortShiftTest(bool useInterpreter)
{
short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableShortShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntShiftTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyUIntShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntShiftTest(bool useInterpreter)
{
uint?[] array = { 0, 1, uint.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableUIntShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntShiftTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyIntShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntShiftTest(bool useInterpreter)
{
int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableIntShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongShiftTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyULongShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongShiftTest(bool useInterpreter)
{
ulong?[] array = { 0, 1, ulong.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableULongShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongShiftTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyLongShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongShiftTest(bool useInterpreter)
{
long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableLongShift(array[i], useInterpreter);
}
}
#endregion
#region Test verifiers
private static int[] s_shifts = new[] { int.MinValue, -1, 0, 1, 2, 31, 32, 63, 64, int.MaxValue };
private static void VerifyByteShift(byte a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyByteShift(a, b, true, useInterpreter);
VerifyByteShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyByteShift(byte a, int b, bool left, bool useInterpreter)
{
Expression<Func<byte>> e =
Expression.Lambda<Func<byte>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(int)))
);
Func<byte> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((byte)(left ? a << b : a >> b)), f());
Expression<Func<byte?>> en =
Expression.Lambda<Func<byte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(int?)))
);
Func<byte?> fn = en.Compile(useInterpreter);
Assert.Equal(unchecked((byte)(left ? a << b : a >> b)), fn());
}
private static void VerifyNullableByteShift(byte? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableByteShift(a, b, true, useInterpreter);
VerifyNullableByteShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableByteShift(byte? a, int b, bool left, bool useInterpreter)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(int)))
);
Func<byte?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((byte?)(left ? a << b : a >> b)), f());
e =
Expression.Lambda<Func<byte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(unchecked((byte?)(left ? a << b : a >> b)), f());
}
private static void VerifySByteShift(sbyte a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifySByteShift(a, b, true, useInterpreter);
VerifySByteShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifySByteShift(sbyte a, int b, bool left, bool useInterpreter)
{
Expression<Func<sbyte>> e =
Expression.Lambda<Func<sbyte>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(int)))
);
Func<sbyte> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((sbyte)(left ? a << b : a >> b)), f());
Expression<Func<sbyte?>> en =
Expression.Lambda<Func<sbyte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(int?)))
);
Func<sbyte?> fn = en.Compile(useInterpreter);
Assert.Equal(unchecked((sbyte)(left ? a << b : a >> b)), fn());
}
private static void VerifyNullableSByteShift(sbyte? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableSByteShift(a, b, true, useInterpreter);
VerifyNullableSByteShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableSByteShift(sbyte? a, int b, bool left, bool useInterpreter)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(int)))
);
Func<sbyte?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((sbyte?)(left ? a << b : a >> b)), f());
e =
Expression.Lambda<Func<sbyte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(unchecked((sbyte?)(left ? a << b : a >> b)), f());
}
private static void VerifyUShortShift(ushort a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyUShortShift(a, b, true, useInterpreter);
VerifyUShortShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyUShortShift(ushort a, int b, bool left, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(int)))
);
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort)(left ? a << b : a >> b)), f());
Expression<Func<ushort?>> en =
Expression.Lambda<Func<ushort?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(int?)))
);
Func<ushort?> fn = en.Compile(useInterpreter);
Assert.Equal(unchecked((ushort)(left ? a << b : a >> b)), fn());
}
private static void VerifyNullableUShortShift(ushort? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableUShortShift(a, b, true, useInterpreter);
VerifyNullableUShortShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableUShortShift(ushort? a, int b, bool left, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(int)))
);
Func<ushort?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort?)(left ? a << b : a >> b)), f());
e =
Expression.Lambda<Func<ushort?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort?)(left ? a << b : a >> b)), f());
}
private static void VerifyShortShift(short a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyShortShift(a, b, true, useInterpreter);
VerifyShortShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyShortShift(short a, int b, bool left, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(int)))
);
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short)(left ? a << b : a >> b)), f());
Expression<Func<short?>> en =
Expression.Lambda<Func<short?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(int?)))
);
Func<short?> fn = en.Compile(useInterpreter);
Assert.Equal(unchecked((short)(left ? a << b : a >> b)), fn());
}
private static void VerifyNullableShortShift(short? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableShortShift(a, b, true, useInterpreter);
VerifyNullableShortShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableShortShift(short? a, int b, bool left, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(int)))
);
Func<short?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short?)(left ? a << b : a >> b)), f());
e =
Expression.Lambda<Func<short?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short?)(left ? a << b : a >> b)), f());
}
private static void VerifyUIntShift(uint a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyUIntShift(a, b, true, useInterpreter);
VerifyUIntShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyUIntShift(uint a, int b, bool left, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(int)))
);
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
Expression<Func<uint?>> en =
Expression.Lambda<Func<uint?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(int?)))
);
Func<uint?> fn = en.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, fn());
}
private static void VerifyNullableUIntShift(uint? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableUIntShift(a, b, true, useInterpreter);
VerifyNullableUIntShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableUIntShift(uint? a, int b, bool left, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(int)))
);
Func<uint?> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
e =
Expression.Lambda<Func<uint?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
}
private static void VerifyIntShift(int a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyIntShift(a, b, true, useInterpreter);
VerifyIntShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyIntShift(int a, int b, bool left, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int)))
);
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
Expression<Func<int?>> en =
Expression.Lambda<Func<int?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int?)))
);
Func<int?> fn = en.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, fn());
}
private static void VerifyNullableIntShift(int? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableIntShift(a, b, true, useInterpreter);
VerifyNullableIntShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableIntShift(int? a, int b, bool left, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int)))
);
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
e =
Expression.Lambda<Func<int?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
}
private static void VerifyULongShift(ulong a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyULongShift(a, b, true, useInterpreter);
VerifyULongShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyULongShift(ulong a, int b, bool left, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(int)))
);
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
Expression<Func<ulong?>> en =
Expression.Lambda<Func<ulong?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(int?)))
);
Func<ulong?> fn = en.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, fn());
}
private static void VerifyNullableULongShift(ulong? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableULongShift(a, b, true, useInterpreter);
VerifyNullableULongShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableULongShift(ulong? a, int b, bool left, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(int)))
);
Func<ulong?> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
e =
Expression.Lambda<Func<ulong?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
}
private static void VerifyLongShift(long a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyLongShift(a, b, true, useInterpreter);
VerifyLongShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyLongShift(long a, int b, bool left, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(int)))
);
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
Expression<Func<long?>> en =
Expression.Lambda<Func<long?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(int?)))
);
Func<long?> fn = en.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, fn());
}
private static void VerifyNullableLongShift(long? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableLongShift(a, b, true, useInterpreter);
VerifyNullableLongShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableLongShift(long? a, int b, bool left, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(int)))
);
Func<long?> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
e =
Expression.Lambda<Func<long?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
}
private static void VerifyNullShift<T>(T a, bool left, bool useInterpreter) where T : struct
{
Expression<Func<T?>> e =
Expression.Lambda<Func<T?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(T)),
Expression.Default(typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(T)),
Expression.Default(typeof(int?)))
);
Func<T?> f = e.Compile(useInterpreter);
Assert.Null(f());
}
private static void VerifyNullableNullShift<T>(T a, bool left, bool useInterpreter)
{
Expression<Func<T>> e =
Expression.Lambda<Func<T>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(T)),
Expression.Default(typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(T)),
Expression.Default(typeof(int?)))
);
Func<T> f = e.Compile(useInterpreter);
Assert.Null(f());
}
#endregion
[Fact]
public static void CannotReduceLeft()
{
Expression exp = Expression.LeftShift(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void CannotReduceRight()
{
Expression exp = Expression.RightShift(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void LeftThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.LeftShift(null, Expression.Constant("")));
}
[Fact]
public static void LeftThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.LeftShift(Expression.Constant(""), null));
}
[Fact]
public static void RightThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.RightShift(null, Expression.Constant("")));
}
[Fact]
public static void RightThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.RightShift(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void LeftThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.LeftShift(value, Expression.Constant(1)));
}
[Fact]
public static void LeftThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.LeftShift(Expression.Constant(1), value));
}
[Fact]
public static void RightThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.RightShift(value, Expression.Constant(1)));
}
[Fact]
public static void RightThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.RightShift(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e1 = Expression.LeftShift(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a << b)", e1.ToString());
BinaryExpression e2 = Expression.RightShift(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a >> b)", e2.ToString());
}
[Theory, InlineData(typeof(E)), InlineData(typeof(El)), InlineData(typeof(string))]
public static void IncorrectLHSTypes(Type type)
{
DefaultExpression lhs = Expression.Default(type);
ConstantExpression rhs = Expression.Constant(0);
Assert.Throws<InvalidOperationException>(() => Expression.LeftShift(lhs, rhs));
Assert.Throws<InvalidOperationException>(() => Expression.RightShift(lhs, rhs));
}
[Theory, InlineData(typeof(E)), InlineData(typeof(El)), InlineData(typeof(string)), InlineData(typeof(long)),
InlineData(typeof(short)), InlineData(typeof(uint))]
public static void IncorrectRHSTypes(Type type)
{
ConstantExpression lhs = Expression.Constant(0);
DefaultExpression rhs = Expression.Default(type);
Assert.Throws<InvalidOperationException>(() => Expression.LeftShift(lhs, rhs));
Assert.Throws<InvalidOperationException>(() => Expression.RightShift(lhs, rhs));
}
}
}
| |
// 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;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Xml;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.ServiceModel;
namespace System.Runtime.Diagnostics
{
internal sealed class EtwDiagnosticTrace : DiagnosticTraceBase
{
private const int XmlBracketsLength = 5; // "<></>".Length;
private const int MaxExceptionStringLength = 28 * 1024;
private const int MaxExceptionDepth = 64;
private static Guid s_defaultEtwProviderId = Guid.Empty;
//Compiler will add all static initializers into the static constructor. Adding an explicit one to mark SecurityCritical.
[Fx.Tag.SecurityNote(Critical = "setting critical field defaultEtwProviderId")]
[SecurityCritical]
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.InitializeReferenceTypeStaticFieldsInline,
Justification = "SecurityCriticial method")]
static EtwDiagnosticTrace()
{
// In Partial Trust, initialize to Guid.Empty to disable ETW Tracing.
s_defaultEtwProviderId = Guid.Empty;
}
[Fx.Tag.SecurityNote(Critical = "Access critical etwProvider, eventSourceName field")]
[SecurityCritical]
public EtwDiagnosticTrace(string traceSourceName, Guid etwProviderId)
: base(traceSourceName)
{
}
static public Guid DefaultEtwProviderId
{
[Fx.Tag.SecurityNote(Critical = "reading critical field defaultEtwProviderId", Safe = "Doesn't leak info\\resources")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecuritySafeCriticial method")]
get
{
return EtwDiagnosticTrace.s_defaultEtwProviderId;
}
[Fx.Tag.SecurityNote(Critical = "setting critical field defaultEtwProviderId")]
[SecurityCritical]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecurityCriticial method")]
set
{
EtwDiagnosticTrace.s_defaultEtwProviderId = value;
}
}
public bool IsEtwProviderEnabled
{
[Fx.Tag.SecurityNote(Critical = "Access critical etwProvider field",
Safe = "Doesn't leak info\\resources")]
[SecuritySafeCritical]
get
{
return false;
}
}
public bool IsEnd2EndActivityTracingEnabled
{
[Fx.Tag.SecurityNote(Critical = "Access critical etwProvider field",
Safe = "Doesn't leak resources or information")]
[SecuritySafeCritical]
get
{
return false;
}
}
private bool EtwTracingEnabled
{
[Fx.Tag.SecurityNote(Critical = "Access critical etwProvider field",
Safe = "Doesn't leak info\\resources")]
[SecuritySafeCritical]
get
{
return false;
}
}
[Fx.Tag.SecurityNote(Critical = "Accesses the security critical etwProvider field", Safe = "Doesn't leak info\\resources")]
[SecuritySafeCritical]
public void SetEnd2EndActivityTracingEnabled(bool isEnd2EndTracingEnabled)
{
}
[Fx.Tag.SecurityNote(Critical = "Usage of EventDescriptor, which is protected by a LinkDemand")]
[SecurityCritical]
public void Event(ref EventDescriptor eventDescriptor, string description)
{
if (this.TracingEnabled)
{
TracePayload tracePayload = this.GetSerializedPayload(null, null, null);
this.WriteTraceSource(ref eventDescriptor, description, tracePayload);
}
}
public void SetAndTraceTransfer(Guid newId, bool emitTransfer)
{
if (emitTransfer)
{
TraceTransfer(newId);
}
EtwDiagnosticTrace.ActivityId = newId;
}
[Fx.Tag.SecurityNote(Critical = "Access critical transferEventDescriptor field, as well as other critical methods",
Safe = "Doesn't leak information or resources")]
[SecuritySafeCritical]
public void TraceTransfer(Guid newId)
{
}
[Fx.Tag.SecurityNote(Critical = "Usage of EventDescriptor, which is protected by a LinkDemand")]
[SecurityCritical]
public void WriteTraceSource(ref EventDescriptor eventDescriptor, string description, TracePayload payload)
{
}
private static string LookupChannel(TraceChannel traceChannel)
{
string channelName;
switch (traceChannel)
{
case TraceChannel.Admin:
channelName = "Admin";
break;
case TraceChannel.Analytic:
channelName = "Analytic";
break;
case TraceChannel.Application:
channelName = "Application";
break;
case TraceChannel.Debug:
channelName = "Debug";
break;
case TraceChannel.Operational:
channelName = "Operational";
break;
case TraceChannel.Perf:
channelName = "Perf";
break;
default:
channelName = traceChannel.ToString();
break;
}
return channelName;
}
public TracePayload GetSerializedPayload(object source, TraceRecord traceRecord, Exception exception)
{
return this.GetSerializedPayload(source, traceRecord, exception, false);
}
public TracePayload GetSerializedPayload(object source, TraceRecord traceRecord, Exception exception, bool getServiceReference)
{
throw ExceptionHelper.PlatformNotSupported();
}
[Fx.Tag.SecurityNote(Critical = "Usage of EventDescriptor, which is protected by a LinkDemand",
Safe = "Only queries the status of the provider - does not modify the state")]
[SecuritySafeCritical]
public bool IsEtwEventEnabled(ref EventDescriptor eventDescriptor)
{
return IsEtwEventEnabled(ref eventDescriptor, true);
}
[Fx.Tag.SecurityNote(Critical = "Usage of EventDescriptor, which is protected by a LinkDemand",
Safe = "Only queries the status of the provider - does not modify the state")]
[SecuritySafeCritical]
public bool IsEtwEventEnabled(ref EventDescriptor eventDescriptor, bool fullCheck)
{
return false;
}
public override bool IsEnabled()
{
return false;
}
internal static string ExceptionToTraceString(Exception exception, int maxTraceStringLength)
{
StringBuilder sb = StringBuilderPool.Take();
try
{
using (StringWriter stringWriter = new StringWriter(sb, CultureInfo.CurrentCulture))
{
using (XmlWriter xml = XmlWriter.Create(stringWriter))
{
WriteExceptionToTraceString(xml, exception, maxTraceStringLength, MaxExceptionDepth);
xml.Flush();
stringWriter.Flush();
return sb.ToString();
}
}
}
finally
{
StringBuilderPool.Return(sb);
}
}
private static void WriteExceptionToTraceString(XmlWriter xml, Exception exception, int remainingLength, int remainingAllowedRecursionDepth)
{
if (remainingAllowedRecursionDepth < 1)
{
return;
}
if (!WriteStartElement(xml, DiagnosticStrings.ExceptionTag, ref remainingLength))
{
return;
}
try
{
IList<Tuple<string, string>> exceptionInfo = new List<Tuple<string, string>>()
{
new Tuple<string, string> (DiagnosticStrings.ExceptionTypeTag, XmlEncode(exception.GetType().AssemblyQualifiedName)),
new Tuple<string, string> (DiagnosticStrings.MessageTag, XmlEncode(exception.Message)),
new Tuple<string, string> (DiagnosticStrings.StackTraceTag, XmlEncode(StackTraceString(exception))), // Stack trace is sometimes null
new Tuple<string, string> (DiagnosticStrings.ExceptionStringTag, XmlEncode(exception.ToString())),
};
foreach (Tuple<string, string> item in exceptionInfo)
{
if (!WriteXmlElementString(xml, item.Item1, item.Item2, ref remainingLength))
{
return;
}
}
if (exception.Data != null && exception.Data.Count > 0)
{
string exceptionData = GetExceptionData(exception);
if (exceptionData.Length < remainingLength)
{
xml.WriteRaw(exceptionData);
remainingLength -= exceptionData.Length;
}
}
if (exception.InnerException != null)
{
string innerException = GetInnerException(exception, remainingLength, remainingAllowedRecursionDepth - 1);
if (!string.IsNullOrEmpty(innerException) && innerException.Length < remainingLength)
{
xml.WriteRaw(innerException);
}
}
}
finally
{
xml.WriteEndElement();
}
}
private static string GetInnerException(Exception exception, int remainingLength, int remainingAllowedRecursionDepth)
{
if (remainingAllowedRecursionDepth < 1)
{
return null;
}
StringBuilder sb = StringBuilderPool.Take();
try
{
using (StringWriter stringWriter = new StringWriter(sb, CultureInfo.CurrentCulture))
{
using (XmlWriter xml = XmlWriter.Create(stringWriter))
{
if (!WriteStartElement(xml, DiagnosticStrings.InnerExceptionTag, ref remainingLength))
{
return null;
}
WriteExceptionToTraceString(xml, exception.InnerException, remainingLength, remainingAllowedRecursionDepth);
xml.WriteEndElement();
xml.Flush();
stringWriter.Flush();
return sb.ToString();
}
}
}
finally
{
StringBuilderPool.Return(sb);
}
}
private static string GetExceptionData(Exception exception)
{
StringBuilder sb = StringBuilderPool.Take();
try
{
using (StringWriter stringWriter = new StringWriter(sb, CultureInfo.CurrentCulture))
{
using (XmlWriter xml = XmlWriter.Create(stringWriter))
{
xml.WriteStartElement(DiagnosticStrings.DataItemsTag);
foreach (object dataItem in exception.Data.Keys)
{
xml.WriteStartElement(DiagnosticStrings.DataTag);
xml.WriteElementString(DiagnosticStrings.KeyTag, XmlEncode(dataItem.ToString()));
if (exception.Data[dataItem] == null)
{
xml.WriteElementString(DiagnosticStrings.ValueTag, string.Empty);
}
else
{
xml.WriteElementString(DiagnosticStrings.ValueTag, XmlEncode(exception.Data[dataItem].ToString()));
}
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.Flush();
stringWriter.Flush();
return sb.ToString();
}
}
}
finally
{
StringBuilderPool.Return(sb);
}
}
private static bool WriteStartElement(XmlWriter xml, string localName, ref int remainingLength)
{
int minXmlLength = (localName.Length * 2) + EtwDiagnosticTrace.XmlBracketsLength;
if (minXmlLength <= remainingLength)
{
xml.WriteStartElement(localName);
remainingLength -= minXmlLength;
return true;
}
return false;
}
private static bool WriteXmlElementString(XmlWriter xml, string localName, string value, ref int remainingLength)
{
int xmlElementLength = (localName.Length * 2) + EtwDiagnosticTrace.XmlBracketsLength + (value != null ? value.Length : 0);
if (xmlElementLength <= remainingLength)
{
xml.WriteElementString(localName, value);
remainingLength -= xmlElementLength;
return true;
}
return false;
}
private static class TraceCodes
{
public const string AppDomainUnload = "AppDomainUnload";
public const string TraceHandledException = "TraceHandledException";
public const string ThrowingException = "ThrowingException";
public const string UnhandledException = "UnhandledException";
}
private static class EventIdsWithMsdnTraceCode
{
// EventIds for which we need to translate the traceCode and the eventId
// when system.diagnostics tracing is enabled.
public const int AppDomainUnload = 57393;
public const int ThrowingExceptionWarning = 57396;
public const int ThrowingExceptionVerbose = 57407;
public const int HandledExceptionInfo = 57394;
public const int HandledExceptionWarning = 57404;
public const int HandledExceptionError = 57405;
public const int HandledExceptionVerbose = 57406;
public const int UnhandledException = 57397;
}
private static class LegacyTraceEventIds
{
// Diagnostic trace codes
public const int Diagnostics = 0X20000;
public const int AppDomainUnload = LegacyTraceEventIds.Diagnostics | 0X0001;
public const int EventLog = LegacyTraceEventIds.Diagnostics | 0X0002;
public const int ThrowingException = LegacyTraceEventIds.Diagnostics | 0X0003;
public const int TraceHandledException = LegacyTraceEventIds.Diagnostics | 0X0004;
public const int UnhandledException = LegacyTraceEventIds.Diagnostics | 0X0005;
}
internal static class StringBuilderPool
{
private const int maxPooledStringBuilders = 64;
private static readonly ConcurrentQueue<StringBuilder> s_freeStringBuilders = new ConcurrentQueue<StringBuilder>();
public static StringBuilder Take()
{
StringBuilder sb = null;
if (s_freeStringBuilders.TryDequeue(out sb))
{
return sb;
}
return new StringBuilder();
}
public static void Return(StringBuilder sb)
{
Fx.Assert(sb != null, "'sb' MUST NOT be NULL.");
if (s_freeStringBuilders.Count <= maxPooledStringBuilders)
{
// There is a race condition here so the count could be off a little bit (but insignificantly)
sb.Clear();
s_freeStringBuilders.Enqueue(sb);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Contracts;
using BTCPayServer.Client.Models;
using BTCPayServer.Configuration;
using BTCPayServer.Controllers;
using BTCPayServer.Data;
using BTCPayServer.Fido2;
using BTCPayServer.Fido2.Models;
using BTCPayServer.Logging;
using BTCPayServer.Models.AppViewModels;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Services;
using BTCPayServer.Services.Apps;
using BTCPayServer.Services.Stores;
using ExchangeSharp;
using Fido2NetLib.Objects;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NBXplorer;
using Newtonsoft.Json.Linq;
using PeterO.Cbor;
namespace BTCPayServer.Hosting
{
public class MigrationStartupTask : IStartupTask
{
public Logs Logs { get; }
private readonly ApplicationDbContextFactory _DBContextFactory;
private readonly StoreRepository _StoreRepository;
private readonly BTCPayNetworkProvider _NetworkProvider;
private readonly SettingsRepository _Settings;
private readonly AppService _appService;
private readonly IEnumerable<IPayoutHandler> _payoutHandlers;
private readonly BTCPayNetworkJsonSerializerSettings _btcPayNetworkJsonSerializerSettings;
private readonly UserManager<ApplicationUser> _userManager;
public IOptions<LightningNetworkOptions> LightningOptions { get; }
public MigrationStartupTask(
BTCPayNetworkProvider networkProvider,
StoreRepository storeRepository,
ApplicationDbContextFactory dbContextFactory,
UserManager<ApplicationUser> userManager,
IOptions<LightningNetworkOptions> lightningOptions,
SettingsRepository settingsRepository,
AppService appService,
IEnumerable<IPayoutHandler> payoutHandlers,
BTCPayNetworkJsonSerializerSettings btcPayNetworkJsonSerializerSettings,
Logs logs)
{
Logs = logs;
_DBContextFactory = dbContextFactory;
_StoreRepository = storeRepository;
_NetworkProvider = networkProvider;
_Settings = settingsRepository;
_appService = appService;
_payoutHandlers = payoutHandlers;
_btcPayNetworkJsonSerializerSettings = btcPayNetworkJsonSerializerSettings;
_userManager = userManager;
LightningOptions = lightningOptions;
}
public async Task ExecuteAsync(CancellationToken cancellationToken = default)
{
try
{
await Migrate(cancellationToken);
var settings = (await _Settings.GetSettingAsync<MigrationSettings>()) ?? new MigrationSettings();
if (!settings.PaymentMethodCriteria)
{
await MigratePaymentMethodCriteria();
settings.PaymentMethodCriteria = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.DeprecatedLightningConnectionStringCheck)
{
await DeprecatedLightningConnectionStringCheck();
settings.DeprecatedLightningConnectionStringCheck = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.UnreachableStoreCheck)
{
await UnreachableStoreCheck();
settings.UnreachableStoreCheck = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.ConvertMultiplierToSpread)
{
await ConvertMultiplierToSpread();
settings.ConvertMultiplierToSpread = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.ConvertNetworkFeeProperty)
{
await ConvertNetworkFeeProperty();
settings.ConvertNetworkFeeProperty = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.ConvertCrowdfundOldSettings)
{
await ConvertCrowdfundOldSettings();
settings.ConvertCrowdfundOldSettings = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.ConvertWalletKeyPathRoots)
{
await ConvertConvertWalletKeyPathRoots();
settings.ConvertWalletKeyPathRoots = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.CheckedFirstRun)
{
var themeSettings = await _Settings.GetSettingAsync<ThemeSettings>() ?? new ThemeSettings();
var admin = await _userManager.GetUsersInRoleAsync(Roles.ServerAdmin);
themeSettings.FirstRun = admin.Count == 0;
await _Settings.UpdateSetting(themeSettings);
settings.CheckedFirstRun = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.TransitionToStoreBlobAdditionalData)
{
await TransitionToStoreBlobAdditionalData();
settings.TransitionToStoreBlobAdditionalData = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.TransitionInternalNodeConnectionString)
{
await TransitionInternalNodeConnectionString();
settings.TransitionInternalNodeConnectionString = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.MigrateU2FToFIDO2)
{
await MigrateU2FToFIDO2();
settings.MigrateU2FToFIDO2 = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.MigrateHotwalletProperty)
{
await MigrateHotwalletProperty();
settings.MigrateHotwalletProperty = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.MigrateAppCustomOption)
{
await MigrateAppCustomOption();
settings.MigrateAppCustomOption = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.MigratePayoutDestinationId)
{
await MigratePayoutDestinationId();
settings.MigratePayoutDestinationId = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.AddInitialUserBlob)
{
await AddInitialUserBlob();
settings.AddInitialUserBlob = true;
await _Settings.UpdateSetting(settings);
}
if (!settings.LighingAddressSettingRename)
{
await MigrateLighingAddressSettingRename();
settings.LighingAddressSettingRename = true;
await _Settings.UpdateSetting(settings);
}
}
catch (Exception ex)
{
Logs.PayServer.LogError(ex, "Error on the MigrationStartupTask");
throw;
}
}
private async Task MigrateLighingAddressSettingRename()
{
var old = await _Settings.GetSettingAsync<UILNURLController.LightningAddressSettings>("BTCPayServer.LNURLController+LightningAddressSettings");
if (old is not null)
{
await _Settings.UpdateSetting(old, nameof(UILNURLController.LightningAddressSettings));
}
}
private async Task AddInitialUserBlob()
{
await using var ctx = _DBContextFactory.CreateContext();
foreach (var user in await ctx.Users.AsQueryable().ToArrayAsync())
{
user.SetBlob(new UserBlob() { ShowInvoiceStatusChangeHint = true });
}
await ctx.SaveChangesAsync();
}
private async Task MigratePayoutDestinationId()
{
await using var ctx = _DBContextFactory.CreateContext();
foreach (var payoutData in await ctx.Payouts.AsQueryable().ToArrayAsync())
{
var pmi = payoutData.GetPaymentMethodId();
if (pmi is null)
{
continue;
}
var handler = _payoutHandlers
.FindPayoutHandler(pmi);
if (handler is null)
{
continue;
}
var claim = await handler?.ParseClaimDestination(pmi, payoutData.GetBlob(_btcPayNetworkJsonSerializerSettings).Destination);
payoutData.Destination = claim.destination?.Id;
}
await ctx.SaveChangesAsync();
}
private async Task MigrateAppCustomOption()
{
await using var ctx = _DBContextFactory.CreateContext();
foreach (var app in await ctx.Apps.Include(data => data.StoreData).AsQueryable().ToArrayAsync())
{
ViewPointOfSaleViewModel.Item[] items;
string newTemplate;
switch (app.AppType)
{
case nameof(AppType.Crowdfund):
var settings1 = app.GetSettings<CrowdfundSettings>();
if (string.IsNullOrEmpty(settings1.TargetCurrency))
{
settings1.TargetCurrency = app.StoreData.GetStoreBlob().DefaultCurrency;
app.SetSettings(settings1);
}
items = _appService.Parse(settings1.PerksTemplate, settings1.TargetCurrency);
newTemplate = _appService.SerializeTemplate(items);
if (settings1.PerksTemplate != newTemplate)
{
settings1.PerksTemplate = newTemplate;
app.SetSettings(settings1);
};
break;
case nameof(AppType.PointOfSale):
var settings2 = app.GetSettings<UIAppsController.PointOfSaleSettings>();
if (string.IsNullOrEmpty(settings2.Currency))
{
settings2.Currency = app.StoreData.GetStoreBlob().DefaultCurrency;
app.SetSettings(settings2);
}
items = _appService.Parse(settings2.Template, settings2.Currency);
newTemplate = _appService.SerializeTemplate(items);
if (settings2.Template != newTemplate)
{
settings2.Template = newTemplate;
app.SetSettings(settings2);
};
break;
}
}
await ctx.SaveChangesAsync();
}
private async Task MigrateHotwalletProperty()
{
await using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
foreach (var paymentMethod in store.GetSupportedPaymentMethods(_NetworkProvider).OfType<DerivationSchemeSettings>())
{
paymentMethod.IsHotWallet = paymentMethod.Source == "NBXplorer";
if (paymentMethod.IsHotWallet)
{
paymentMethod.Source = "NBXplorerGenerated";
store.SetSupportedPaymentMethod(paymentMethod);
}
}
}
await ctx.SaveChangesAsync();
}
private async Task MigrateU2FToFIDO2()
{
await using var ctx = _DBContextFactory.CreateContext();
var u2fDevices = await ctx.U2FDevices.ToListAsync();
foreach (U2FDevice u2FDevice in u2fDevices)
{
var fido2 = new Fido2Credential()
{
ApplicationUserId = u2FDevice.ApplicationUserId,
Name = u2FDevice.Name,
Type = Fido2Credential.CredentialType.FIDO2
};
fido2.SetBlob(new Fido2CredentialBlob()
{
SignatureCounter = (uint)u2FDevice.Counter,
PublicKey = CreatePublicKeyFromU2fRegistrationData(u2FDevice.PublicKey).EncodeToBytes(),
UserHandle = u2FDevice.KeyHandle,
Descriptor = new PublicKeyCredentialDescriptor(u2FDevice.KeyHandle),
CredType = "u2f"
});
await ctx.AddAsync(fido2);
ctx.Remove(u2FDevice);
}
await ctx.SaveChangesAsync();
}
//from https://github.com/abergs/fido2-net-lib/blob/0fa7bb4b4a1f33f46c5f7ca4ee489b47680d579b/Test/ExistingU2fRegistrationDataTests.cs#L70
private static CBORObject CreatePublicKeyFromU2fRegistrationData(byte[] publicKeyData)
{
if (publicKeyData.Length != 65)
{
throw new ArgumentException("u2f public key must be 65 bytes", nameof(publicKeyData));
}
var x = new byte[32];
var y = new byte[32];
Buffer.BlockCopy(publicKeyData, 1, x, 0, 32);
Buffer.BlockCopy(publicKeyData, 33, y, 0, 32);
var coseKey = CBORObject.NewMap();
coseKey.Add(COSE.KeyCommonParameter.KeyType, COSE.KeyType.EC2);
coseKey.Add(COSE.KeyCommonParameter.Alg, -7);
coseKey.Add(COSE.KeyTypeParameter.Crv, COSE.EllipticCurve.P256);
coseKey.Add(COSE.KeyTypeParameter.X, x);
coseKey.Add(COSE.KeyTypeParameter.Y, y);
return coseKey;
}
private async Task TransitionInternalNodeConnectionString()
{
var nodes = LightningOptions.Value.InternalLightningByCryptoCode.Values.Select(c => c.ToString()).ToHashSet();
await using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
#pragma warning disable CS0618 // Type or member is obsolete
if (!string.IsNullOrEmpty(store.DerivationStrategy))
{
var noLabel = store.DerivationStrategy.Split('-')[0];
JObject jObject = new JObject();
jObject.Add("BTC", new JObject()
{
new JProperty("signingKey", noLabel),
new JProperty("accountDerivation", store.DerivationStrategy),
new JProperty("accountOriginal", store.DerivationStrategy),
new JProperty("accountKeySettings", new JArray()
{
new JObject()
{
new JProperty("accountKey", noLabel)
}
})
});
store.DerivationStrategies = jObject.ToString();
store.DerivationStrategy = null;
}
if (string.IsNullOrEmpty(store.DerivationStrategies))
continue;
var strats = JObject.Parse(store.DerivationStrategies);
bool updated = false;
foreach (var prop in strats.Properties().Where(p => p.Name.EndsWith("LightningLike", StringComparison.OrdinalIgnoreCase)))
{
var method = ((JObject)prop.Value);
var lightningCharge = method.Property("LightningChargeUrl", StringComparison.OrdinalIgnoreCase);
var ln = method.Property("LightningConnectionString", StringComparison.OrdinalIgnoreCase);
if (lightningCharge != null)
{
var chargeUrl = lightningCharge.Value.Value<string>();
var usr = method.Property("Username", StringComparison.OrdinalIgnoreCase)?.Value.Value<string>();
var pass = method.Property("Password", StringComparison.OrdinalIgnoreCase)?.Value.Value<string>();
updated = true;
if (chargeUrl != null)
{
var fullUri = new UriBuilder(chargeUrl)
{
UserName = usr,
Password = pass
}.Uri.AbsoluteUri;
var newStr = $"type=charge;server={fullUri};allowinsecure=true";
if (ln is null)
{
ln = new JProperty("LightningConnectionString", newStr);
method.Add(ln);
}
else
{
ln.Value = newStr;
}
}
foreach (var p in new[] { "Username", "Password", "LightningChargeUrl" })
method.Property(p, StringComparison.OrdinalIgnoreCase)?.Remove();
}
var paymentId = method.Property("PaymentId", StringComparison.OrdinalIgnoreCase);
if (paymentId != null)
{
paymentId.Remove();
updated = true;
}
if (ln is null)
continue;
if (nodes.Contains(ln.Value.Value<string>()))
{
updated = true;
ln.Value = null;
if (!(method.Property("InternalNodeRef", StringComparison.OrdinalIgnoreCase) is JProperty internalNode))
{
internalNode = new JProperty("InternalNodeRef", null);
method.Add(internalNode);
}
internalNode.Value = new JValue(LightningSupportedPaymentMethod.InternalNode);
}
}
if (updated)
store.DerivationStrategies = strats.ToString();
#pragma warning restore CS0618 // Type or member is obsolete
}
await ctx.SaveChangesAsync();
}
private async Task TransitionToStoreBlobAdditionalData()
{
await using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
var blob = store.GetStoreBlob();
blob.AdditionalData.Remove("walletKeyPathRoots");
blob.AdditionalData.Remove("onChainMinValue");
blob.AdditionalData.Remove("lightningMaxValue");
blob.AdditionalData.Remove("networkFeeDisabled");
blob.AdditionalData.Remove("rateRules");
store.SetStoreBlob(blob);
}
await ctx.SaveChangesAsync();
}
private async Task Migrate(CancellationToken cancellationToken)
{
using (CancellationTokenSource timeout = new CancellationTokenSource(10_000))
using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, cancellationToken))
{
retry:
try
{
await _DBContextFactory.CreateContext().Database.MigrateAsync();
}
// Starting up
catch when (!cts.Token.IsCancellationRequested)
{
try
{
await Task.Delay(1000, cts.Token);
}
catch { }
goto retry;
}
}
}
private async Task ConvertConvertWalletKeyPathRoots()
{
bool save = false;
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
#pragma warning disable CS0618 // Type or member is obsolete
var blob = store.GetStoreBlob();
if (blob.AdditionalData.TryGetValue("walletKeyPathRoots", out var walletKeyPathRootsJToken))
{
var walletKeyPathRoots = walletKeyPathRootsJToken.ToObject<Dictionary<string, string>>();
if (!(walletKeyPathRoots?.Any() is true))
continue;
foreach (var scheme in store.GetSupportedPaymentMethods(_NetworkProvider)
.OfType<DerivationSchemeSettings>())
{
if (walletKeyPathRoots.TryGetValue(scheme.PaymentId.ToString().ToLowerInvariant(),
out var root))
{
scheme.AccountKeyPath = new NBitcoin.KeyPath(root);
store.SetSupportedPaymentMethod(scheme);
save = true;
}
}
blob.AdditionalData.Remove("walletKeyPathRoots");
store.SetStoreBlob(blob);
}
#pragma warning restore CS0618 // Type or member is obsolete
}
if (save)
await ctx.SaveChangesAsync();
}
private async Task ConvertCrowdfundOldSettings()
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var app in await ctx.Apps.Where(a => a.AppType == "Crowdfund").ToArrayAsync())
{
var settings = app.GetSettings<Services.Apps.CrowdfundSettings>();
#pragma warning disable CS0618 // Type or member is obsolete
if (settings.UseAllStoreInvoices)
#pragma warning restore CS0618 // Type or member is obsolete
{
app.TagAllInvoices = true;
}
}
await ctx.SaveChangesAsync();
}
private async Task MigratePaymentMethodCriteria()
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
var blob = store.GetStoreBlob();
CurrencyValue onChainMinValue = null;
CurrencyValue lightningMaxValue = null;
if (blob.AdditionalData.TryGetValue("onChainMinValue", out var onChainMinValueJToken))
{
CurrencyValue.TryParse(onChainMinValueJToken.Value<string>(), out onChainMinValue);
blob.AdditionalData.Remove("onChainMinValue");
}
if (blob.AdditionalData.TryGetValue("lightningMaxValue", out var lightningMaxValueJToken))
{
CurrencyValue.TryParse(lightningMaxValueJToken.Value<string>(), out lightningMaxValue);
blob.AdditionalData.Remove("lightningMaxValue");
}
blob.PaymentMethodCriteria = store.GetEnabledPaymentIds(_NetworkProvider).Select(paymentMethodId =>
{
var matchedFromBlob =
blob.PaymentMethodCriteria?.SingleOrDefault(criteria => criteria.PaymentMethod == paymentMethodId && criteria.Value != null);
return matchedFromBlob switch
{
null when paymentMethodId.PaymentType == LightningPaymentType.Instance &&
lightningMaxValue != null => new PaymentMethodCriteria()
{
Above = false,
PaymentMethod = paymentMethodId,
Value = lightningMaxValue
},
null when paymentMethodId.PaymentType == BitcoinPaymentType.Instance &&
onChainMinValue != null => new PaymentMethodCriteria()
{
Above = true,
PaymentMethod = paymentMethodId,
Value = onChainMinValue
},
_ => new PaymentMethodCriteria()
{
PaymentMethod = paymentMethodId,
Above = matchedFromBlob?.Above ?? true,
Value = matchedFromBlob?.Value
}
};
}).ToList();
store.SetStoreBlob(blob);
}
await ctx.SaveChangesAsync();
}
private async Task ConvertNetworkFeeProperty()
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
var blob = store.GetStoreBlob();
if (blob.AdditionalData.TryGetValue("networkFeeDisabled", out var networkFeeModeJToken))
{
var networkFeeMode = networkFeeModeJToken.ToObject<bool?>();
if (networkFeeMode != null)
{
blob.NetworkFeeMode = networkFeeMode.Value ? NetworkFeeMode.Never : NetworkFeeMode.Always;
}
blob.AdditionalData.Remove("networkFeeDisabled");
store.SetStoreBlob(blob);
}
}
await ctx.SaveChangesAsync();
}
private async Task ConvertMultiplierToSpread()
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
var blob = store.GetStoreBlob();
decimal multiplier = 1.0m;
if (blob.AdditionalData.TryGetValue("rateRules", out var rateRulesJToken))
{
var rateRules = new Serializer(null).ToObject<List<RateRule_Obsolete>>(rateRulesJToken.ToString());
if (rateRules != null && rateRules.Count != 0)
{
foreach (var rule in rateRules)
{
multiplier = rule.Apply(null, multiplier);
}
}
blob.AdditionalData.Remove("rateRules");
blob.Spread = Math.Min(1.0m, Math.Max(0m, -(multiplier - 1.0m)));
store.SetStoreBlob(blob);
}
}
await ctx.SaveChangesAsync();
}
public class RateRule_Obsolete
{
public RateRule_Obsolete()
{
RuleName = "Multiplier";
}
public string RuleName { get; set; }
public double Multiplier { get; set; }
public decimal Apply(BTCPayNetworkBase network, decimal rate)
{
return rate * (decimal)Multiplier;
}
}
private Task UnreachableStoreCheck()
{
return _StoreRepository.CleanUnreachableStores();
}
private async Task DeprecatedLightningConnectionStringCheck()
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
foreach (var method in store.GetSupportedPaymentMethods(_NetworkProvider).OfType<Payments.Lightning.LightningSupportedPaymentMethod>())
{
var lightning = method.GetExternalLightningUrl();
if (lightning?.IsLegacy is true)
{
method.SetLightningUrl(lightning);
store.SetSupportedPaymentMethod(method);
}
}
}
await ctx.SaveChangesAsync();
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Gdal
// Description: This is a data extension for the System.Spatial framework.
// ********************************************************************************************************
// The contents of this file are subject to the Gnu Lesser General Public License (LGPL)
// 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 a plugin for MapWindow version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/1/2009 11:42:01 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// | Name | Date | Comments
// |-------------------|-------------|-------------------------------------------------------------------
// |Ben tidyup Tombs |18/11/2010 | Modified to add GDAL Helper class GdalHelper.Configure use for initialization of the GDAL Environment
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using DotSpatial.Projections;
using OSGeo.GDAL;
namespace DotSpatial.Data.Rasters.GdalExtension
{
/// <summary>
///
/// </summary>
internal class GdalRaster<T> : Raster<T> where T : IEquatable<T>, IComparable<T>
{
#region Private Variables
readonly Band _band;
readonly Dataset _dataset;
#endregion
#region Constructors
/// <summary>
/// This can be a raster with multiple bands.
/// </summary>
/// <param name="name"></param>
/// <param name="fromDataset"></param>
public GdalRaster(string name, Dataset fromDataset)
: base(fromDataset.RasterYSize, fromDataset.RasterXSize)
{
_dataset = fromDataset;
base.Filename = name;
base.Name = Path.GetFileNameWithoutExtension(name);
ReadHeader();
int numBands = _dataset.RasterCount;
if (numBands == 1)
_band = _dataset.GetRasterBand(1);
else
{
for (int i = 1; i <= numBands; i++)
{
base.Bands.Add(new GdalRaster<T>(name, fromDataset, _dataset.GetRasterBand(i)));
}
}
}
/// <summary>
/// creates a new raster from the specified band
/// </summary>
/// <param name="fileName">The string path of the file if any.</param>
/// <param name="fromDataset"></param>
/// <param name="fromBand"></param>
public GdalRaster(string fileName, Dataset fromDataset, Band fromBand)
: base(fromDataset.RasterYSize, fromDataset.RasterXSize)
{
_dataset = fromDataset;
_band = fromBand;
base.Filename = fileName;
base.Name = Path.GetFileNameWithoutExtension(fileName);
ReadHeader();
}
#endregion
#region Methods
/// <summary>
/// This is the GDAL data type
/// </summary>
public DataType GdalDataType
{
get { return _band.DataType; }
}
/// <summary>
/// Reads values from the raster to the jagged array of values
/// </summary>
/// <param name="xOff">The horizontal offset from the left to start reading from</param>
/// <param name="yOff">The vertical offset from the top to start reading from</param>
/// <param name="sizeX">The number of cells to read horizontally</param>
/// <param name="sizeY">The number of cells ot read vertically</param>
/// <returns>A jagged array of values from the raster</returns>
public override T[][] ReadRaster(int xOff, int yOff, int sizeX, int sizeY)
{
T[][] result = new T[sizeY][];
T[] rawData = new T[sizeY * sizeX];
if (_band == null)
{
Raster<T> ri = Bands[CurrentBand] as Raster<T>;
if (ri != null)
{
return ri.ReadRaster(xOff, yOff, sizeX, sizeY);
}
}
else
{
GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
try
{
IntPtr ptr = handle.AddrOfPinnedObject();
_band.ReadRaster(xOff, yOff, sizeX, sizeY, ptr, sizeX, sizeY, GdalDataType, PixelSpace, LineSpace);
}
finally
{
if (handle.IsAllocated)
{
handle.Free();
}
}
for (int row = 0; row < sizeY; row++)
{
result[row] = new T[sizeX];
Array.Copy(rawData, row * sizeX, result[row], 0, sizeX);
}
return result;
}
return null;
}
/// <summary>
/// Most reading is optimized to read in a block at a time and process it. This method is designed
/// for seeking through the file. It should work faster than the buffered methods in cases where
/// an unusually arranged collection of values are required. Sorting the list before calling
/// this should significantly improve performance.
/// </summary>
/// <param name="indices">A list or array of long values that are (Row * NumRowsInFile + Column)</param>
public override List<T> GetValuesT(IEnumerable<long> indices)
{
if (IsInRam) return base.GetValuesT(indices);
if (_band == null)
{
Raster<T> ri = Bands[CurrentBand] as Raster<T>;
if (ri != null)
{
return ri.GetValuesT(indices);
}
return null;
}
else
{
#if DEBUG
var sw = new Stopwatch();
sw.Start();
#endif
List<T> result = new List<T>();
foreach (long index in indices)
{
int row = (int)(index / NumColumnsInFile);
int col = (int)(index % NumColumnsInFile);
T[] data = new T[1];
//http://trac.osgeo.org/gdal/wiki/GdalOgrCsharpRaster
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
IntPtr ptr = handle.AddrOfPinnedObject();
_band.ReadRaster(col, row, 1, 1, ptr, 1, 1, GdalDataType, PixelSpace, LineSpace);
}
finally
{
if (handle.IsAllocated)
{
handle.Free();
}
}
result.Add(data[0]);
}
#if DEBUG
sw.Stop();
Debug.WriteLine("Time to read values from file:" + sw.ElapsedMilliseconds);
#endif
return result;
}
}
/// <summary>
/// Writes values from the jagged array to the raster at the specified location
/// </summary>
/// <param name="buffer">A jagged array of values to write to the raster</param>
/// <param name="xOff">The horizontal offset from the left to start reading from</param>
/// <param name="yOff">The vertical offset from the top to start reading from</param>
/// <param name="xSize">The number of cells to write horizontally</param>
/// <param name="ySize">The number of cells ot write vertically</param>
public override void WriteRaster(T[][] buffer, int xOff, int yOff, int xSize, int ySize)
{
if (_band == null)
{
Raster<T> ri = Bands[CurrentBand] as Raster<T>;
if (ri != null)
{
ri.NoDataValue = NoDataValue;
ri.WriteRaster(buffer, xOff, yOff, xSize, ySize);
}
}
else
{
T[] rawValues = new T[xSize * ySize];
for (int row = 0; row < ySize; row++)
{
Array.Copy(buffer[row], 0, rawValues, row * xSize, xSize);
}
GCHandle handle = GCHandle.Alloc(rawValues, GCHandleType.Pinned);
try
{
IntPtr ptr = handle.AddrOfPinnedObject();
// int stride = ((xSize * sizeof(T) + 7) / 8);
_band.WriteRaster(xOff, yOff, xSize, ySize, ptr, xSize, ySize, GdalDataType, PixelSpace, 0);
_band.FlushCache();
_dataset.FlushCache();
}
finally
{
if (handle.IsAllocated)
{
handle.Free();
}
}
}
}
public override void Close()
{
base.Close();
if (_band != null)
_band.Dispose();
else
foreach (IRaster raster in Bands)
{
raster.Close();
raster.Dispose();
}
if (_dataset != null)
{
_dataset.FlushCache();
_dataset.Dispose();
}
}
/// <summary>
/// Copies the fileName
/// </summary>
/// <param name="fileName"></param>
/// <param name="copyValues"></param>
public override void Copy(string fileName, bool copyValues)
{
using (Driver d = _dataset.GetDriver())
{
DataType myType = OSGeo.GDAL.DataType.GDT_Int32;
if (_band != null)
{
myType = _band.DataType;
}
else
{
GdalRaster<T> r = Bands[0] as GdalRaster<T>;
if (r != null)
{
myType = r.GdalDataType;
}
}
if (copyValues)
{
d.CreateCopy(fileName, _dataset, 1, Options, GdalProgressFunc, "Copy Progress");
}
else
{
d.Create(fileName, NumColumnsInFile, NumRowsInFile, NumBands, myType, Options);
}
}
}
/// <summary>
/// Handles the callback progress content
/// </summary>
/// <param name="complete"></param>
/// <param name="message"></param>
/// <param name="data"></param>
/// <returns></returns>
private int GdalProgressFunc(double complete, IntPtr message, IntPtr data)
{
ProgressHandler.Progress("Copy Progress", Convert.ToInt32(complete), "Copy Progress");
return 0;
}
/// <summary>
/// Gets the mean, standard deviation, minimum and maximum
/// </summary>
public override void GetStatistics()
{
if (IsInRam && this.IsFullyWindowed())
{
base.GetStatistics();
return;
}
if (_band != null)
{
double min, max, mean, std;
CPLErr err;
try
{
if (base.Value.Updated)
err = _band.ComputeStatistics(false, out min, out max, out mean, out std, null, null);
else
err = _band.GetStatistics(0, 1, out min, out max, out mean, out std);
Value.Updated = false;
Minimum = min;
Maximum = max;
Mean = mean;
StdDeviation = std;
}
catch (Exception ex)
{
err = CPLErr.CE_Failure;
max = min = std = mean = 0;
Trace.WriteLine(ex);
}
base.Value.Updated = false;
// http://dotspatial.codeplex.com/workitem/22221
// GetStatistics didn't return anything, so try use the raster default method.
if (err != CPLErr.CE_None || (max == 0 && min == 0 && std == 0 && mean == 0))
base.GetStatistics();
}
else
{
// ?? doesn't this mean the stats get overwritten several times.
foreach (IRaster raster in Bands)
{
raster.GetStatistics();
}
}
}
/// <summary>
/// Updates the header information about the projection and the affine coefficients
/// </summary>
protected override void UpdateHeader()
{
_dataset.SetGeoTransform(Bounds.AffineCoefficients);
if (Projection != null)
{
_dataset.SetProjection(Projection.ToEsriString());
}
}
#endregion
#region Properties
public override double NoDataValue
{
get
{
return base.NoDataValue;
}
set
{
base.NoDataValue = value;
if (_band != null)
{
_band.SetNoDataValue(value);
}
else
{
foreach (var raster in Bands)
{
raster.NoDataValue = value;
}
}
}
}
public override double Mean
{
get
{
return base.Mean;
}
protected set
{
base.Mean = value;
if (_band != null)
{
_band.SetStatistics(Minimum, Maximum, value, StdDeviation);
_band.SetMetadataItem("STATISTICS_MEAN", Mean.ToString(), "");
}
else
{
foreach (GdalRaster<T> raster in Bands)
{
raster.Mean = value;
}
}
}
}
public override double StdDeviation
{
get { return base.StdDeviation; }
protected set
{
base.StdDeviation = value;
if (_band != null)
{
_band.SetStatistics(Minimum, Maximum, Mean, value);
_band.SetMetadataItem("STATISTICS_STDDEV", StdDeviation.ToString(), "");
}
else
{
foreach (GdalRaster<T> raster in Bands)
{
raster.StdDeviation = value;
}
}
}
}
public override double Minimum
{
get
{
return base.Minimum;
}
protected set
{
base.Minimum = value;
if (_band != null)
{
_band.SetStatistics(value, Maximum, Mean, StdDeviation);
_band.SetMetadataItem("STATISTICS_MINIMUM", Minimum.ToString(), "");
}
else
{
foreach (GdalRaster<T> raster in Bands)
{
raster.Minimum = value;
}
}
}
}
public override double Maximum
{
get
{
return base.Maximum;
}
protected set
{
base.Maximum = value;
if (_band != null)
{
_band.SetStatistics(Minimum, value, Mean, StdDeviation);
_band.SetMetadataItem("STATISTICS_MAXIMUM", Maximum.ToString(), "");
}
else
{
foreach (GdalRaster<T> raster in Bands)
{
raster.Maximum = value;
}
}
}
}
public override String[] CategoryNames()
{
if (_band != null)
{
return _band.GetCategoryNames();
}
else
{
foreach (GdalRaster<T> raster in Bands)
{
return raster._band.GetCategoryNames();
}
}
return null;
}
public override Color[] CategoryColors()
{
Color[] Colors = null;
ColorTable table = GetColorTable();
if (table != null)
{
int ColorCount = table.GetCount();
if (ColorCount > 0)
{
Colors = new Color[ColorCount];
for (int ColorIndex = 0; ColorIndex < ColorCount; ColorIndex += 1)
{
Colors[ColorIndex] = Color.DimGray;
ColorEntry entry = table.GetColorEntry(ColorIndex);
switch (table.GetPaletteInterpretation())
{
case PaletteInterp.GPI_RGB: Colors[ColorIndex] = Color.FromArgb(entry.c4, entry.c1, entry.c2, entry.c3); break;
case PaletteInterp.GPI_Gray: Colors[ColorIndex] = Color.FromArgb(255, entry.c1, entry.c1, entry.c1); break;
//TODO: do any files use these types?
//case PaletteInterp.GPI_HLS
//case PaletteInterp.GPI_CMYK
}
}
}
}
return Colors;
}
#endregion
private ColorTable GetColorTable()
{
if (_band != null)
{
return _band.GetColorTable();
}
else
{
foreach (GdalRaster<T> raster in Bands)
{
return raster._band.GetColorTable();
}
}
return null;
}
private void ReadHeader()
{
DataType = typeof(T);
base.NumColumnsInFile = _dataset.RasterXSize;
base.NumColumns = base.NumColumnsInFile;
base.NumRowsInFile = _dataset.RasterYSize;
base.NumRows = base.NumRowsInFile;
// Todo: look for prj file if GetProjection returns null.
// Do we need to read this as an Esri string if we don't get a proj4 string?
string projString = _dataset.GetProjection();
Projection = ProjectionInfo.FromProj4String(projString);
if (_band != null)
{
double val;
int hasInterval;
_band.GetNoDataValue(out val, out hasInterval);
base.NoDataValue = val;
}
double[] affine = new double[6];
_dataset.GetGeoTransform(affine);
// in gdal (row,col) coordinates are defined relative to the top-left corner of the top-left cell
// shift them by half a cell to give coordinates relative to the center of the top-left cell
affine = (new AffineTransform(affine)).TransfromToCorner(0.5, 0.5);
ProjectionString = projString;
Bounds = new RasterBounds(base.NumRows, base.NumColumns, affine);
PixelSpace = Marshal.SizeOf(typeof(T));
}
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.DynamicProxy
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using Castle.Core.Internal;
using Castle.DynamicProxy.Generators;
using Castle.DynamicProxy.Serialization;
/// <summary>
/// Summary description for ModuleScope.
/// </summary>
public class ModuleScope
{
/// <summary>
/// The default file name used when the assembly is saved using <see cref = "DEFAULT_FILE_NAME" />.
/// </summary>
public static readonly String DEFAULT_FILE_NAME = "CastleDynProxy2.dll";
/// <summary>
/// The default assembly (simple) name used for the assemblies generated by a <see cref = "ModuleScope" /> instance.
/// </summary>
public static readonly String DEFAULT_ASSEMBLY_NAME = "DynamicProxyGenAssembly2";
private ModuleBuilder moduleBuilderWithStrongName;
private ModuleBuilder moduleBuilder;
// The names to use for the generated assemblies and the paths (including the names) of their manifest modules
private readonly string strongAssemblyName;
private readonly string weakAssemblyName;
private readonly string strongModulePath;
private readonly string weakModulePath;
// Keeps track of generated types
private readonly Dictionary<CacheKey, Type> typeCache = new Dictionary<CacheKey, Type>();
// Users of ModuleScope should use this lock when accessing the cache
private readonly Lock cacheLock = Lock.Create();
// Used to lock the module builder creation
private readonly object moduleLocker = new object();
// Specified whether the generated assemblies are intended to be saved
private readonly bool savePhysicalAssembly;
private readonly bool disableSignedModule;
private readonly INamingScope namingScope;
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class; assemblies created by this instance will not be saved.
/// </summary>
public ModuleScope() : this(false, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
/// should be saved.
/// </summary>
/// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
public ModuleScope(bool savePhysicalAssembly)
: this(savePhysicalAssembly, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
/// should be saved.
/// </summary>
/// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
/// <param name = "disableSignedModule">If set to <c>true</c> disables ability to generate signed module. This should be used in cases where ran under constrained permissions.</param>
public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule)
: this(
savePhysicalAssembly, disableSignedModule, DEFAULT_ASSEMBLY_NAME, DEFAULT_FILE_NAME, DEFAULT_ASSEMBLY_NAME,
DEFAULT_FILE_NAME)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
/// should be saved and what simple names are to be assigned to them.
/// </summary>
/// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
/// <param name = "disableSignedModule">If set to <c>true</c> disables ability to generate signed module. This should be used in cases where ran under constrained permissions.</param>
/// <param name = "strongAssemblyName">The simple name of the strong-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
/// <param name = "strongModulePath">The path and file name of the manifest module of the strong-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
/// <param name = "weakAssemblyName">The simple name of the weak-named assembly generated by this <see cref = "ModuleScope" />.</param>
/// <param name = "weakModulePath">The path and file name of the manifest module of the weak-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, string strongAssemblyName,
string strongModulePath,
string weakAssemblyName, string weakModulePath)
: this(
savePhysicalAssembly, disableSignedModule, new NamingScope(), strongAssemblyName, strongModulePath, weakAssemblyName,
weakModulePath)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
/// should be saved and what simple names are to be assigned to them.
/// </summary>
/// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
/// <param name = "disableSignedModule">If set to <c>true</c> disables ability to generate signed module. This should be used in cases where ran under constrained permissions.</param>
/// <param name = "namingScope">Naming scope used to provide unique names to generated types and their members (usually via sub-scopes).</param>
/// <param name = "strongAssemblyName">The simple name of the strong-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
/// <param name = "strongModulePath">The path and file name of the manifest module of the strong-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
/// <param name = "weakAssemblyName">The simple name of the weak-named assembly generated by this <see cref = "ModuleScope" />.</param>
/// <param name = "weakModulePath">The path and file name of the manifest module of the weak-named assembly generated by this <see
/// cref = "ModuleScope" />.</param>
public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, INamingScope namingScope,
string strongAssemblyName, string strongModulePath,
string weakAssemblyName, string weakModulePath)
{
this.savePhysicalAssembly = savePhysicalAssembly;
this.disableSignedModule = disableSignedModule;
this.namingScope = namingScope;
this.strongAssemblyName = strongAssemblyName;
this.strongModulePath = strongModulePath;
this.weakAssemblyName = weakAssemblyName;
this.weakModulePath = weakModulePath;
}
public INamingScope NamingScope
{
get { return namingScope; }
}
/// <summary>
/// Users of this <see cref = "ModuleScope" /> should use this lock when accessing the cache.
/// </summary>
public Lock Lock
{
get { return cacheLock; }
}
/// <summary>
/// Returns a type from this scope's type cache, or null if the key cannot be found.
/// </summary>
/// <param name = "key">The key to be looked up in the cache.</param>
/// <returns>The type from this scope's type cache matching the key, or null if the key cannot be found</returns>
public Type GetFromCache(CacheKey key)
{
Type type;
typeCache.TryGetValue(key, out type);
return type;
}
/// <summary>
/// Registers a type in this scope's type cache.
/// </summary>
/// <param name = "key">The key to be associated with the type.</param>
/// <param name = "type">The type to be stored in the cache.</param>
public void RegisterInCache(CacheKey key, Type type)
{
typeCache[key] = type;
}
/// <summary>
/// Gets the key pair used to sign the strong-named assembly generated by this <see cref = "ModuleScope" />.
/// </summary>
/// <returns></returns>
public static byte[] GetKeyPair()
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SharepointCommon.Castle.DynamicProxy.DynProxy.snk"))
{
if (stream == null)
{
throw new MissingManifestResourceException(
"Should have a Castle.DynamicProxy.DynProxy.snk as an embedded resource, so Dynamic Proxy could sign generated assembly");
}
var length = (int)stream.Length;
var keyPair = new byte[length];
stream.Read(keyPair, 0, length);
return keyPair;
}
}
/// <summary>
/// Gets the strong-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.
/// </summary>
/// <value>The strong-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.</value>
public ModuleBuilder StrongNamedModule
{
get { return moduleBuilderWithStrongName; }
}
/// <summary>
/// Gets the file name of the strongly named module generated by this scope.
/// </summary>
/// <value>The file name of the strongly named module generated by this scope.</value>
public string StrongNamedModuleName
{
get { return Path.GetFileName(strongModulePath); }
}
#if !SILVERLIGHT
/// <summary>
/// Gets the directory where the strongly named module generated by this scope will be saved, or <see langword = "null" /> if the current directory
/// is used.
/// </summary>
/// <value>The directory where the strongly named module generated by this scope will be saved when <see
/// cref = "SaveAssembly()" /> is called
/// (if this scope was created to save modules).</value>
public string StrongNamedModuleDirectory
{
get
{
var directory = Path.GetDirectoryName(strongModulePath);
if (string.IsNullOrEmpty(directory))
{
return null;
}
return directory;
}
}
#endif
/// <summary>
/// Gets the weak-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.
/// </summary>
/// <value>The weak-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.</value>
public ModuleBuilder WeakNamedModule
{
get { return moduleBuilder; }
}
/// <summary>
/// Gets the file name of the weakly named module generated by this scope.
/// </summary>
/// <value>The file name of the weakly named module generated by this scope.</value>
public string WeakNamedModuleName
{
get { return Path.GetFileName(weakModulePath); }
}
#if !SILVERLIGHT
/// <summary>
/// Gets the directory where the weakly named module generated by this scope will be saved, or <see langword = "null" /> if the current directory
/// is used.
/// </summary>
/// <value>The directory where the weakly named module generated by this scope will be saved when <see
/// cref = "SaveAssembly()" /> is called
/// (if this scope was created to save modules).</value>
public string WeakNamedModuleDirectory
{
get
{
var directory = Path.GetDirectoryName(weakModulePath);
if (directory == string.Empty)
{
return null;
}
return directory;
}
}
#endif
/// <summary>
/// Gets the specified module generated by this scope, creating a new one if none has yet been generated.
/// </summary>
/// <param name = "isStrongNamed">If set to true, a strong-named module is returned; otherwise, a weak-named module is returned.</param>
/// <returns>A strong-named or weak-named module generated by this scope, as specified by the <paramref
/// name = "isStrongNamed" /> parameter.</returns>
public ModuleBuilder ObtainDynamicModule(bool isStrongNamed)
{
if (isStrongNamed)
{
return ObtainDynamicModuleWithStrongName();
}
return ObtainDynamicModuleWithWeakName();
}
/// <summary>
/// Gets the strong-named module generated by this scope, creating a new one if none has yet been generated.
/// </summary>
/// <returns>A strong-named module generated by this scope.</returns>
public ModuleBuilder ObtainDynamicModuleWithStrongName()
{
if (disableSignedModule)
{
throw new InvalidOperationException(
"Usage of signed module has been disabled. Use unsigned module or enable signed module.");
}
lock (moduleLocker)
{
if (moduleBuilderWithStrongName == null)
{
moduleBuilderWithStrongName = CreateModule(true);
}
return moduleBuilderWithStrongName;
}
}
/// <summary>
/// Gets the weak-named module generated by this scope, creating a new one if none has yet been generated.
/// </summary>
/// <returns>A weak-named module generated by this scope.</returns>
public ModuleBuilder ObtainDynamicModuleWithWeakName()
{
lock (moduleLocker)
{
if (moduleBuilder == null)
{
moduleBuilder = CreateModule(false);
}
return moduleBuilder;
}
}
private ModuleBuilder CreateModule(bool signStrongName)
{
signStrongName = false;
var assemblyName = GetAssemblyName(signStrongName);
var moduleName = signStrongName ? StrongNamedModuleName : WeakNamedModuleName;
#if !SILVERLIGHT
if (savePhysicalAssembly)
{
AssemblyBuilder assemblyBuilder;
try
{
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
assemblyName, AssemblyBuilderAccess.RunAndSave, signStrongName ? StrongNamedModuleDirectory : WeakNamedModuleDirectory);
}
catch (ArgumentException e)
{
if (signStrongName == false && e.StackTrace.Contains("ComputePublicKey") == false)
{
// I have no idea what that could be
throw;
}
var message =
string.Format(
"There was an error creating dynamic assembly for your proxies - you don't have permissions required to sign the assembly. To workaround it you can enforce generating non-signed assembly only when creating {0}. ALternatively ensure that your account has all the required permissions.",
GetType());
throw new ArgumentException(message, e);
}
var module = assemblyBuilder.DefineDynamicModule(moduleName, moduleName, false);
return module;
}
else
#endif
{
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
assemblyName,
AssemblyBuilderAccess.Run);
var module = assemblyBuilder.DefineDynamicModule(moduleName, false);
return module;
}
}
private AssemblyName GetAssemblyName(bool signStrongName)
{
var assemblyName = new AssemblyName
{
Name = signStrongName ? strongAssemblyName : weakAssemblyName
};
#if !SILVERLIGHT
if (signStrongName)
{
byte[] keyPairStream = GetKeyPair();
if (keyPairStream != null)
{
assemblyName.KeyPair = new StrongNameKeyPair(keyPairStream);
}
}
#endif
return assemblyName;
}
#if !SILVERLIGHT
/// <summary>
/// Saves the generated assembly with the name and directory information given when this <see cref = "ModuleScope" /> instance was created (or with
/// the <see cref = "DEFAULT_FILE_NAME" /> and current directory if none was given).
/// </summary>
/// <remarks>
/// <para>
/// This method stores the generated assembly in the directory passed as part of the module information specified when this instance was
/// constructed (if any, else the current directory is used). If both a strong-named and a weak-named assembly
/// have been generated, it will throw an exception; in this case, use the <see cref = "SaveAssembly (bool)" /> overload.
/// </para>
/// <para>
/// If this <see cref = "ModuleScope" /> was created without indicating that the assembly should be saved, this method does nothing.
/// </para>
/// </remarks>
/// <exception cref = "InvalidOperationException">Both a strong-named and a weak-named assembly have been generated.</exception>
/// <returns>The path of the generated assembly file, or null if no file has been generated.</returns>
public string SaveAssembly()
{
if (!savePhysicalAssembly)
{
return null;
}
if (StrongNamedModule != null && WeakNamedModule != null)
{
throw new InvalidOperationException("Both a strong-named and a weak-named assembly have been generated.");
}
if (StrongNamedModule != null)
{
return SaveAssembly(true);
}
if (WeakNamedModule != null)
{
return SaveAssembly(false);
}
return null;
}
/// <summary>
/// Saves the specified generated assembly with the name and directory information given when this <see
/// cref = "ModuleScope" /> instance was created
/// (or with the <see cref = "DEFAULT_FILE_NAME" /> and current directory if none was given).
/// </summary>
/// <param name = "strongNamed">True if the generated assembly with a strong name should be saved (see <see
/// cref = "StrongNamedModule" />);
/// false if the generated assembly without a strong name should be saved (see <see cref = "WeakNamedModule" />.</param>
/// <remarks>
/// <para>
/// This method stores the specified generated assembly in the directory passed as part of the module information specified when this instance was
/// constructed (if any, else the current directory is used).
/// </para>
/// <para>
/// If this <see cref = "ModuleScope" /> was created without indicating that the assembly should be saved, this method does nothing.
/// </para>
/// </remarks>
/// <exception cref = "InvalidOperationException">No assembly has been generated that matches the <paramref
/// name = "strongNamed" /> parameter.
/// </exception>
/// <returns>The path of the generated assembly file, or null if no file has been generated.</returns>
public string SaveAssembly(bool strongNamed)
{
if (!savePhysicalAssembly)
{
return null;
}
AssemblyBuilder assemblyBuilder;
string assemblyFileName;
string assemblyFilePath;
if (strongNamed)
{
if (StrongNamedModule == null)
{
throw new InvalidOperationException("No strong-named assembly has been generated.");
}
assemblyBuilder = (AssemblyBuilder)StrongNamedModule.Assembly;
assemblyFileName = StrongNamedModuleName;
assemblyFilePath = StrongNamedModule.FullyQualifiedName;
}
else
{
if (WeakNamedModule == null)
{
throw new InvalidOperationException("No weak-named assembly has been generated.");
}
assemblyBuilder = (AssemblyBuilder)WeakNamedModule.Assembly;
assemblyFileName = WeakNamedModuleName;
assemblyFilePath = WeakNamedModule.FullyQualifiedName;
}
if (File.Exists(assemblyFilePath))
{
File.Delete(assemblyFilePath);
}
AddCacheMappings(assemblyBuilder);
assemblyBuilder.Save(assemblyFileName);
return assemblyFilePath;
}
#endif
#if !SILVERLIGHT
private void AddCacheMappings(AssemblyBuilder builder)
{
Dictionary<CacheKey, string> mappings;
using (Lock.ForReading())
{
mappings = new Dictionary<CacheKey, string>();
foreach (var cacheEntry in typeCache)
{
mappings.Add(cacheEntry.Key, cacheEntry.Value.FullName);
}
}
CacheMappingsAttribute.ApplyTo(builder, mappings);
}
#endif
#if !SILVERLIGHT
/// <summary>
/// Loads the generated types from the given assembly into this <see cref = "ModuleScope" />'s cache.
/// </summary>
/// <param name = "assembly">The assembly to load types from. This assembly must have been saved via <see
/// cref = "SaveAssembly(bool)" /> or
/// <see cref = "SaveAssembly()" />, or it must have the <see cref = "CacheMappingsAttribute" /> manually applied.</param>
/// <remarks>
/// This method can be used to load previously generated and persisted proxy types from disk into this scope's type cache, eg. in order
/// to avoid the performance hit associated with proxy generation.
/// </remarks>
public void LoadAssemblyIntoCache(Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
var cacheMappings =
(CacheMappingsAttribute[])assembly.GetCustomAttributes(typeof(CacheMappingsAttribute), false);
if (cacheMappings.Length == 0)
{
var message = string.Format(
"The given assembly '{0}' does not contain any cache information for generated types.",
assembly.FullName);
throw new ArgumentException(message, "assembly");
}
foreach (var mapping in cacheMappings[0].GetDeserializedMappings())
{
var loadedType = assembly.GetType(mapping.Value);
if (loadedType != null)
{
RegisterInCache(mapping.Key, loadedType);
}
}
}
#endif
public TypeBuilder DefineType(bool inSignedModulePreferably, string name, TypeAttributes flags)
{
var module = ObtainDynamicModule(disableSignedModule == false && inSignedModulePreferably);
return module.DefineType(name, flags);
}
}
}
| |
using System;
using System.Collections.Generic;
#if BEHAVIAC_USE_HTN
namespace behaviac
{
#region PlannerTask
public class PlannerTask : BehaviorTask
{
#region Public properties
public PlannerTaskComplex Parent
{
get;
set;
}
public bool PauseOnRun
{
get;
set;
}
public bool NotInterruptable
{
get;
set;
}
#endregion Public properties
#region Constructor
public PlannerTask(BehaviorNode node, Agent pAgent)
: base()
{
this.m_node = node;
this.m_id = this.m_node.GetId();
}
#endregion Constructor
public delegate PlannerTask TaskCreator(BehaviorNode node, Agent pAgent);
private static Dictionary<Type, TaskCreator> ms_factory = null;
public static void Register<T>(TaskCreator c)
{
ms_factory[typeof(T)] = c;
}
public static PlannerTask Create(BehaviorNode node, Agent pAgent)
{
if (ms_factory == null)
{
ms_factory = new Dictionary<Type, TaskCreator>();
Register<Action>((n, a) => new PlannerTaskAction(n, a));
Register<Task>((n, a) => new PlannerTaskTask(n, a));
Register<Method>((n, a) => new PlannerTaskMethod(n, a));
Register<Sequence>((n, a) => new PlannerTaskSequence(n, a));
Register<Selector>((n, a) => new PlannerTaskSelector(n, a));
Register<Parallel>((n, a) => new PlannerTaskParallel(n, a));
Register<ReferencedBehavior>((n, a) => new PlannerTaskReference(n, a));
Register<DecoratorLoop>((n, a) => new PlannerTaskLoop(n, a));
Register<DecoratorIterator>((n, a) => new PlannerTaskIterator(n, a));
}
Type type = node.GetType();
while (!ms_factory.ContainsKey(type))
{
type = type.BaseType;
Debug.Check(type != null);
}
if (ms_factory.ContainsKey(type))
{
TaskCreator c = ms_factory[type];
PlannerTask task = c(node, pAgent);
return task;
}
return null;
}
public static void Cleanup()
{
if (ms_factory != null)
{
ms_factory.Clear();
ms_factory = null;
}
}
public bool IsHigherPriority(PlannerTask other)
{
return true;
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
return EBTStatus.BT_SUCCESS;
}
public override void traverse(bool childFirst, NodeHandler_t handler, Agent pAgent, object user_data)
{ }
}
#endregion PlannerTask
public class PlannerTaskAction : PlannerTask
{
//private object[] ParamsValue { get; set; }
public PlannerTaskAction(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
Debug.Check(node is Action);
//Action action = node as Action;
//this.ParamsValue = action.GetParamsValue(pAgent);
}
protected override bool onenter(Agent pAgent)
{
Debug.Check(true);
return true;
}
protected override void onexit(Agent pAgent, EBTStatus s)
{
Debug.Check(true);
base.onexit(pAgent, s);
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is Action);
Action action = this.m_node as Action;
//this.m_status = action.Execute(pAgent, this.ParamsValue);
this.m_status = action.Execute(pAgent, childStatus);
return this.m_status;
}
}
public class PlannerTaskComplex : PlannerTask
{
protected int m_activeChildIndex = -1;
protected List<BehaviorTask> m_children;
public void AddChild(PlannerTask task)
{
if (this.m_children == null)
{
this.m_children = new List<BehaviorTask>();
}
this.m_children.Add(task);
task.Parent = this;
}
public void RemoveChild(PlannerTask childTask)
{
Debug.Check(this.m_children.Count > 0 && this.m_children[this.m_children.Count - 1] == childTask);
this.m_children.Remove(childTask);
}
public PlannerTaskComplex(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
}
//~PlannerTaskComplex()
//{
// foreach (BehaviorTask t in this.m_children)
// {
// BehaviorTask.DestroyTask(t);
// }
// this.m_children.Clear();
//}
protected override bool onenter(Agent pAgent)
{
this.m_activeChildIndex = 0;
return true;
}
protected override void onexit(Agent pAgent, EBTStatus s)
{
base.onexit(pAgent, s);
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
return EBTStatus.BT_SUCCESS;
}
}
public class PlannerTaskSequence : PlannerTaskComplex
{
public PlannerTaskSequence(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is Sequence);
Sequence node = this.m_node as Sequence;
EBTStatus s = node.SequenceUpdate(pAgent, childStatus, ref this.m_activeChildIndex, this.m_children);
return s;
}
}
public class PlannerTaskSelector : PlannerTaskComplex
{
public PlannerTaskSelector(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is Selector);
Selector node = this.m_node as Selector;
EBTStatus s = node.SelectorUpdate(pAgent, childStatus, ref this.m_activeChildIndex, this.m_children);
return s;
}
}
public class PlannerTaskParallel : PlannerTaskComplex
{
public PlannerTaskParallel(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is Parallel);
Parallel node = this.m_node as Parallel;
EBTStatus s = node.ParallelUpdate(pAgent, this.m_children);
return s;
}
}
public class PlannerTaskLoop : PlannerTaskComplex
{
public PlannerTaskLoop(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
}
protected override bool onenter(Agent pAgent)
{
base.onenter(pAgent);
//don't reset the m_n if it is restarted
if (this.m_n == 0)
{
int count = this.GetCount(pAgent);
if (count == 0)
{
return false;
}
this.m_n = count;
}
else
{
Debug.Check(true);
}
return true;
}
public int GetCount(Agent pAgent)
{
Debug.Check(this.GetNode() is DecoratorLoop);
DecoratorLoop pDecoratorCountNode = (DecoratorLoop)(this.GetNode());
return pDecoratorCountNode != null ? pDecoratorCountNode.Count(pAgent) : 0;
}
protected int m_n;
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is DecoratorLoop);
//DecoratorLoop node = this.m_node as DecoratorLoop;
Debug.Check(this.m_children.Count == 1);
BehaviorTask c = this.m_children[0];
//EBTStatus s = c.exec(pAgent);
c.exec(pAgent);
if (this.m_n > 0)
{
this.m_n--;
if (this.m_n == 0)
{
return EBTStatus.BT_SUCCESS;
}
return EBTStatus.BT_RUNNING;
}
if (this.m_n == -1)
{
return EBTStatus.BT_RUNNING;
}
Debug.Check(this.m_n == 0);
return EBTStatus.BT_SUCCESS;
}
}
public class PlannerTaskIterator : PlannerTaskComplex
{
public PlannerTaskIterator(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
}
private int m_index;
public int Index
{
set
{
this.m_index = value;
}
}
protected override bool onenter(Agent pAgent)
{
bool bOk = base.onenter(pAgent);
DecoratorIterator pNode = this.m_node as DecoratorIterator;
int count = 0;
bOk = pNode.IterateIt(pAgent, this.m_index, ref count);
return bOk;
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is DecoratorIterator);
//DecoratorIterator pNode = this.m_node as DecoratorIterator;
Debug.Check(this.m_children.Count == 1);
BehaviorTask c = this.m_children[0];
EBTStatus s = c.exec(pAgent);
return s;
}
}
public class PlannerTaskReference : PlannerTaskComplex
{
public PlannerTaskReference(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
}
private AgentState currentState;
protected override bool CheckPreconditions(Agent pAgent, bool bIsAlive)
{
if (!bIsAlive)
{
//only try to Push when enter
this.currentState = pAgent.Variables.Push(false);
Debug.Check(currentState != null);
}
bool bOk = base.CheckPreconditions(pAgent, bIsAlive);
if (!bIsAlive && !bOk)
{
this.currentState.Pop();
this.currentState = null;
}
return bOk;
}
#if !BEHAVIAC_RELEASE
private bool _logged = false;
#endif
BehaviorTreeTask oldTreeTask_ = null;
BehaviorTreeTask m_subTree = null;
public BehaviorTreeTask SubTreeTask
{
set
{
m_subTree = value;
}
}
protected override bool onenter(Agent pAgent)
{
Debug.Check(this.m_node is ReferencedBehavior);
ReferencedBehavior pNode = this.m_node as ReferencedBehavior;
Debug.Check(pNode != null);
#if !BEHAVIAC_RELEASE
_logged = false;
#endif
//this.m_subTree = Workspace.Instance.CreateBehaviorTreeTask(pNode.GetReferencedTree(pAgent));
Debug.Check(this.m_subTree != null);
pNode.SetTaskParams(pAgent, this.m_subTree);
this.oldTreeTask_ = pAgent.ExcutingTreeTask;
pAgent.ExcutingTreeTask = this.m_subTree;
return true;
}
protected override void onexit(Agent pAgent, EBTStatus status)
{
Debug.Check(this.m_node is ReferencedBehavior);
ReferencedBehavior pNode = this.m_node as ReferencedBehavior;
Debug.Check(pNode != null);
this.m_subTree = null;
pAgent.ExcutingTreeTask = this.oldTreeTask_;
#if !BEHAVIAC_RELEASE
pAgent.LogReturnTree(pNode.GetReferencedTree(pAgent));
#endif
Debug.Check(this.currentState != null);
this.currentState.Pop();
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is ReferencedBehavior);
ReferencedBehavior pNode = this.m_node as ReferencedBehavior;
Debug.Check(pNode != null);
EBTStatus status = EBTStatus.BT_RUNNING;
if (pNode.RootTaskNode(pAgent) == null)
{
status = this.m_subTree.exec(pAgent);
}
else
{
#if !BEHAVIAC_RELEASE
if (!_logged)
{
pAgent.LogJumpTree(pNode.GetReferencedTree(pAgent));
_logged = true;
}
#endif
Debug.Check(this.m_children.Count == 1);
BehaviorTask c = this.m_children[0];
BehaviorTreeTask oldTreeTask = pAgent.ExcutingTreeTask;
pAgent.ExcutingTreeTask = this.m_subTree;
status = c.exec(pAgent);
pAgent.ExcutingTreeTask = oldTreeTask;
}
return status;
}
}
public class PlannerTaskTask : PlannerTaskComplex
{
public PlannerTaskTask(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
}
protected override bool onenter(Agent pAgent)
{
//this.m_node.Parent.InstantiatePars(this.LocalVars);
return true;
}
protected override void onexit(Agent pAgent, EBTStatus s)
{
//this.m_node.Parent.UnInstantiatePars(this.LocalVars);
base.onexit(pAgent, s);
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is Task);
//Task pNode = this.m_node as Task;
Debug.Check(this.m_children.Count == 1);
BehaviorTask c = this.m_children[0];
EBTStatus s = c.exec(pAgent);
return s;
}
}
public class PlannerTaskMethod : PlannerTaskComplex
{
public PlannerTaskMethod(BehaviorNode node, Agent pAgent)
: base(node, pAgent)
{
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is Method);
//Method pNode = this.m_node as Method;
Debug.Check(this.m_children.Count == 1);
BehaviorTask c = this.m_children[0];
EBTStatus s = c.exec(pAgent);
return s;
}
}
}
#endif//#if BEHAVIAC_USE_HTN
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using DotVVM.Framework.Routing;
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Testing;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Globalization;
namespace DotVVM.Framework.Tests.Routing
{
[TestClass]
public class DotvvmRouteTests
{
DotvvmConfiguration configuration = DotvvmTestHelper.DefaultConfig;
[TestMethod]
public void DotvvmRoute_IsMatch_RouteMustNotStartWithSlash()
{
Assert.ThrowsException<ArgumentException>(() => {
var route = new DotvvmRoute("/Test", null, null, null, configuration);
});
}
[TestMethod]
public void DotvvmRoute_IsMatch_RouteMustNotEndWithSlash()
{
Assert.ThrowsException<ArgumentException>(() => {
var route = new DotvvmRoute("Test/", null, null, null, configuration);
});
}
[TestMethod]
public void DotvvmRoute_IsMatch_EmptyRouteMatchesEmptyUrl()
{
var route = new DotvvmRoute("", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("", out parameters);
Assert.IsTrue(result);
}
[TestMethod]
public void DotvvmRoute_IsMatch_UrlWithoutParametersExactMatch()
{
var route = new DotvvmRoute("Hello/Test/Page.txt", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Hello/Test/Page.txt", out parameters);
Assert.IsTrue(result);
}
[TestMethod]
public void DotvvmRoute_IsMatch_UrlWithoutParametersNoMatch()
{
var route = new DotvvmRoute("Hello/Test/Page.txt", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Hello/Test/Page", out parameters);
Assert.IsFalse(result);
}
[TestMethod]
public void DotvvmRoute_IsMatch_UrlTwoParametersBothSpecified()
{
var route = new DotvvmRoute("Article/{Id}/{Title}", null, new { Title = "test" }, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article/15/Test-title", out parameters);
Assert.IsTrue(result);
Assert.AreEqual(2, parameters.Count);
Assert.AreEqual("15", parameters["Id"]);
Assert.AreEqual("Test-title", parameters["Title"]);
}
[TestMethod]
public void DotvvmRoute_IsMatch_UrlTwoParametersOneSpecifiedOneDefault()
{
var route = new DotvvmRoute("Article/{Id}/{Title}", null, new { Title = "test" }, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article/15", out parameters);
Assert.IsTrue(result);
Assert.AreEqual(2, parameters.Count);
Assert.AreEqual("15", parameters["Id"]);
Assert.AreEqual("test", parameters["Title"]);
}
[TestMethod]
public void DotvvmRoute_IsMatch_UrlTwoParametersBothRequired_NoMatchWhenOneSpecified()
{
var route = new DotvvmRoute("Article/{Id}/{Title}", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article/15", out parameters);
Assert.IsFalse(result);
}
[TestMethod]
public void DotvvmRoute_IsMatch_UrlTwoParametersBothRequired_DifferentPart()
{
var route = new DotvvmRoute("Article/id_{Id}/{Title}", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Articles/id_15", out parameters);
Assert.IsFalse(result);
}
[TestMethod]
public void DotvvmRoute_IsMatch_UrlOneParameterRequired_TwoSpecified()
{
var route = new DotvvmRoute("Article/{Id}", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article/15/test", out parameters);
Assert.IsFalse(result);
}
[TestMethod]
public void DotvvmRoute_IsMatch_UrlTwoParametersBothRequired_BothSpecified()
{
var route = new DotvvmRoute("Article/id_{Id}/{Title}", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article/id_15/test", out parameters);
Assert.IsTrue(result);
Assert.AreEqual(2, parameters.Count);
Assert.AreEqual("15", parameters["Id"]);
Assert.AreEqual("test", parameters["Title"]);
}
[TestMethod]
public void DotvvmRoute_IsMatch_OneOptionalPrefixedParameter()
{
var route = new DotvvmRoute("{Id?}/Article", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article", out parameters);
Assert.IsTrue(result);
Assert.AreEqual(0, parameters.Count);
}
[TestMethod]
public void DotvvmRoute_IsMatch_OneOptionalSuffixedParameter_WithConstraint()
{
var route = new DotvvmRoute("Article/{Id?:int}", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article", out parameters);
Assert.IsTrue(result);
Assert.AreEqual(0, parameters.Count);
}
[TestMethod]
public void DotvvmRoute_IsMatch_OneOptionalParameter()
{
var route = new DotvvmRoute("Article/{Id?}/edit", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article/edit", out parameters);
Assert.IsTrue(result);
Assert.AreEqual(0, parameters.Count);
}
[TestMethod]
public void DotvvmRoute_IsMatch_TwoParameters_OneOptional_Suffix()
{
var route = new DotvvmRoute("Article/Test/{Id?}/{Id2}/suffix", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article/Test/5/suffix", out parameters);
Assert.IsTrue(result);
Assert.AreEqual(1, parameters.Count);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_UrlTwoParameters()
{
var route = new DotvvmRoute("Article/id_{Id}/{Title}", null, null, null, configuration);
var result = route.BuildUrl(new { Id = 15, Title = "Test" });
Assert.AreEqual("~/Article/id_15/Test", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Static_OnePart()
{
var route = new DotvvmRoute("Article", null, null, null, configuration);
var result = route.BuildUrl(new { });
Assert.AreEqual("~/Article", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Static_TwoParts()
{
var route = new DotvvmRoute("Article/Test", null, null, null, configuration);
var result = route.BuildUrl(new { });
Assert.AreEqual("~/Article/Test", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Static_TwoParts_OptionalParameter_NoValue()
{
var route = new DotvvmRoute("Article/Test/{Id?}", null, null, null, configuration);
var result = route.BuildUrl(new { });
Assert.AreEqual("~/Article/Test", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Static_TwoParts_OptionalParameter_WithValue()
{
var route = new DotvvmRoute("Article/Test/{Id?}", null, null, null, configuration);
var result = route.BuildUrl(new { Id = 5 });
Assert.AreEqual("~/Article/Test/5", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Static_TwoParts_TwoParameters_OneOptional_NoValue()
{
var route = new DotvvmRoute("Article/Test/{Id}/{Id2?}", null, null, null, configuration);
var result = route.BuildUrl(new { Id = 5 });
Assert.AreEqual("~/Article/Test/5", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Static_TwoParts_TwoParameters_OneOptional_NoValue_Suffix()
{
var route = new DotvvmRoute("Article/Test/{Id}/{Id2?}/suffix", null, null, null, configuration);
var result = route.BuildUrl(new { Id = 5 });
Assert.AreEqual("~/Article/Test/5/suffix", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Static_TwoParts_TwoParameters_OneOptional_WithValue()
{
var route = new DotvvmRoute("Article/Test/{Id}/{Id2?}", null, null, null, configuration);
var result = route.BuildUrl(new { Id = 5, Id2 = "aaa" });
Assert.AreEqual("~/Article/Test/5/aaa", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Static_TwoParts_TwoParameters_OneOptional_WithValue_Suffix()
{
var route = new DotvvmRoute("Article/Test/{Id}/{Id2?}/suffix", null, null, null, configuration);
var result = route.BuildUrl(new { Id = 5, Id2 = "aaa" });
Assert.AreEqual("~/Article/Test/5/aaa/suffix", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Static_TwoParts_TwoParameters_FirstOptionalOptional_Suffix()
{
var route = new DotvvmRoute("Article/Test/{Id?}/{Id2}/suffix", null, null, null, configuration);
var result = route.BuildUrl(new { Id2 = "aaa" });
Assert.AreEqual("~/Article/Test/aaa/suffix", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_CombineParameters_OneOptional()
{
var route = new DotvvmRoute("Article/{Id?}", null, null, null, configuration);
var result = route.BuildUrl(new Dictionary<string, object>() { { "Id", 5 } }, new { });
Assert.AreEqual("~/Article/5", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_ParameterOnly()
{
var route = new DotvvmRoute("{Id?}", null, null, null, configuration);
var result = route.BuildUrl(new { });
Assert.AreEqual("~/", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_OptionalParameter()
{
var route = new DotvvmRoute("myPage/{Id?}/edit", null, null, null, configuration);
var result = route.BuildUrl(new { });
var result2 = route.BuildUrl(new Dictionary<string, object> { ["Id"] = null });
Assert.AreEqual("~/myPage/edit", result);
Assert.AreEqual("~/myPage/edit", result2);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_OneOptionalPrefixedParameter()
{
var route = new DotvvmRoute("{Id?}/Article", null, null, null, configuration);
var result = route.BuildUrl(new { });
var result2 = route.BuildUrl(new Dictionary<string, object> { ["Id"] = 0 });
Assert.AreEqual("~/Article", result);
Assert.AreEqual("~/0/Article", result2);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_NullInParameter()
{
var route = new DotvvmRoute("myPage/{Id}/edit", null, null, null, configuration);
var ex = Assert.ThrowsException<DotvvmRouteException>(() => {
route.BuildUrl(new Dictionary<string, object> { ["Id"] = null });
});
Assert.IsInstanceOfType(ex.InnerException, typeof(ArgumentNullException));
}
[TestMethod]
public void DotvvmRoute_BuildUrl_NoParameter()
{
var route = new DotvvmRoute("RR", null, null, null, configuration);
var result = route.BuildUrl(null);
Assert.AreEqual("~/RR", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_InvariantCulture()
{
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = new CultureInfo("cs-CZ");
var route = new DotvvmRoute("RR-{p}", null, null, null, configuration);
var result = route.BuildUrl(new { p = 1.1});
Assert.AreEqual("~/RR-1.1", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_UrlEncode()
{
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = new CultureInfo("cs-CZ");
var route = new DotvvmRoute("RR-{p}", null, null, null, configuration);
var result = route.BuildUrl(new { p = 1.1});
Assert.AreEqual("~/RR-1.1", result);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Invalid_UnclosedParameter()
{
Assert.ThrowsException<ArgumentException>(() => {
var route = new DotvvmRoute("{Id", null, null, null, configuration);
var result = route.BuildUrl(new { });
});
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Invalid_UnclosedParameterConstraint()
{
Assert.ThrowsException<ArgumentException>(() => {
var route = new DotvvmRoute("{Id:int", null, null, null, configuration);
var result = route.BuildUrl(new { });
});
}
[TestMethod]
public void DotvvmRoute_BuildUrl_Parameter_UrlDecode()
{
var route = new DotvvmRoute("Article/{Title}", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article/" + Uri.EscapeDataString("x a d # ? %%%%% | ://"), out parameters);
Assert.IsTrue(result);
Assert.AreEqual(1, parameters.Count);
Assert.AreEqual("x a d # ? %%%%% | ://", parameters["Title"]);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_ParameterConstraint_Int()
{
var route = new DotvvmRoute("Article/id_{Id:int}/{Title}", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("Article/id_15/test", out parameters);
Assert.IsTrue(result);
Assert.AreEqual(2, parameters.Count);
Assert.AreEqual(15, parameters["Id"]);
Assert.AreEqual("test", parameters["Title"]);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_ParameterConstraint_FloatingPoints()
{
var route = new DotvvmRoute("R/{float:float}-{double:double}-{decimal:decimal}", null, null, null, configuration);
IDictionary<string, object> parameters;
var result = route.IsMatch("R/1.12-1.12-1.12", out parameters);
Assert.IsTrue(result);
Assert.AreEqual(3, parameters.Count);
Assert.AreEqual(1.12f, parameters["float"]);
Assert.AreEqual(1.12, parameters["double"]);
Assert.AreEqual(1.12m, parameters["decimal"]);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_ParameterConstraint_Guid()
{
var route = new DotvvmRoute("{guid1:guid}{guid2:guid}{guid3:guid}{guid4:guid}", null, null, null, configuration);
var guids = new[]
{
Guid.NewGuid(),
Guid.NewGuid(),
Guid.NewGuid(),
Guid.NewGuid(),
};
IDictionary<string, object> parameters;
var result = route.IsMatch(string.Concat(guids), out parameters);
Assert.IsTrue(result);
Assert.AreEqual(4, parameters.Count);
Assert.AreEqual(guids[0], parameters["guid1"]);
Assert.AreEqual(guids[1], parameters["guid2"]);
Assert.AreEqual(guids[2], parameters["guid3"]);
Assert.AreEqual(guids[3], parameters["guid4"]);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_ParameterConstraint_Max()
{
var route = new DotvvmRoute("{p:max(100)}", null, null, null, configuration);
IDictionary<string, object> parameters;
Assert.IsFalse(route.IsMatch("101", out parameters));
Assert.IsFalse(route.IsMatch("100.1", out parameters));
Assert.IsFalse(route.IsMatch("djhsjlkdsjalkd", out parameters));
Assert.IsTrue(route.IsMatch("54.11", out parameters));
Assert.AreEqual(1, parameters.Count);
Assert.AreEqual(54.11, parameters["p"]);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_ParameterConstraint_Ranges()
{
var route = new DotvvmRoute("{range:range(1, 100.1)}/{max:max(100)}/{min:min(-55)}/{negrange:range(-100, -12)}/{posint:posint}", null, null, null, configuration);
IDictionary<string, object> parameters;
Assert.IsTrue(route.IsMatch("50/0/0/-50/5", out parameters));
Assert.IsTrue(route.IsMatch("100.045/0.444/0.84/-50.45/0", out parameters));
Assert.IsFalse(route.IsMatch("100.045/0.444/0.84/-50.45/5.5", out parameters));
Assert.IsFalse(route.IsMatch("120/0/0/-50/5", out parameters));
Assert.IsFalse(route.IsMatch("50/100.01/0/-50/5", out parameters));
Assert.IsFalse(route.IsMatch("50/50/-100/-101/5", out parameters));
Assert.IsFalse(route.IsMatch("50/50/-100/-55/-5", out parameters));
Assert.IsTrue(route.IsMatch("54.11/-1000000/0.84/-50.45/0044", out parameters));
Assert.AreEqual(5, parameters.Count);
Assert.AreEqual(54.11, parameters["range"]);
Assert.AreEqual(-1000000.0, parameters["max"]);
Assert.AreEqual(0.84, parameters["min"]);
Assert.AreEqual(-50.45, parameters["negrange"]);
Assert.AreEqual(44, parameters["posint"]);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_ParameterConstraint_Bool()
{
var route = new DotvvmRoute("la{bool:bool}eheh", null, null, null, configuration);
IDictionary<string, object> parameters;
Assert.IsTrue(route.IsMatch("latrueeheh", out parameters));
Assert.IsTrue(route.IsMatch("lafALseeheh", out parameters));
Assert.AreEqual(1, parameters.Count);
Assert.AreEqual(false, parameters["bool"]);
}
[TestMethod]
public void DotvvmRoute_BuildUrl_ParameterConstraintAlpha()
{
var route = new DotvvmRoute("la1{aplha:alpha}7huh", null, null, null, configuration);
IDictionary<string, object> parameters;
Assert.IsTrue(route.IsMatch("la1lala7huh", out parameters));
Assert.IsTrue(route.IsMatch("la1ahoj7huh", out parameters));
Assert.AreEqual(1, parameters.Count);
Assert.AreEqual("ahoj", parameters["aplha"]);
}
[TestMethod]
public void DotvvmRoute_Performance()
{
var route = new DotvvmRoute("Article/{name}@{domain}/{id:int}", null, null, null, configuration);
IDictionary<string, object> parameters;
Assert.IsFalse(route.IsMatch("Article/f" + new string('@', 2000) + "f/4f", out parameters));
}
[TestMethod]
public void DotvvmRoute_PresenterFactoryMethod()
{
var configuration = DotvvmConfiguration.CreateDefault(services => {
services.TryAddScoped<TestPresenter>();
});
var table = new DotvvmRouteTable(configuration);
table.Add("Article", "", typeof(TestPresenter), null);
Assert.IsInstanceOfType(table.First().GetPresenter(configuration.ServiceProvider), typeof(TestPresenter));
Assert.ThrowsException<ArgumentException>(() => {
table.Add("Blog", "", typeof(TestPresenterWithoutInterface));
});
}
[TestMethod]
public void DotvvmRoute_PresenterType()
{
var configuration = DotvvmConfiguration.CreateDefault(services => {
services.TryAddScoped<TestPresenter>();
});
var table = new DotvvmRouteTable(configuration);
table.Add("Article", "", provider => provider.GetRequiredService<TestPresenter>(), null);
Assert.IsInstanceOfType(table.First().GetPresenter(configuration.ServiceProvider), typeof(TestPresenter));
}
[TestMethod]
public void DotvvmRoute_RegexConstraint()
{
var route = new DotvvmRoute("test/{Name:regex((aa|bb|cc))}", null, null, null, configuration);
Assert.IsTrue(route.IsMatch("test/aa", out var parameters));
Assert.IsTrue(route.IsMatch("test/bb", out parameters));
Assert.IsTrue(route.IsMatch("test/cc", out parameters));
Assert.IsFalse(route.IsMatch("test/aaaa", out parameters));
}
[TestMethod]
public void DotvvmRoute_UrlWithoutTypes()
{
string parse(string url) => new DotvvmRoute(url, null, null, null, configuration).UrlWithoutTypes;
Assert.AreEqual(parse("test/xx/12"), "test/xx/12");
Assert.AreEqual(parse("test/{Param}-{PaRAM2}"), "test/{param}-{param2}");
Assert.AreEqual(parse("test/{Param?}-{PaRAM2?}"), "test/{param}-{param2}");
Assert.AreEqual(parse("test/{Param:int}-{PaRAM2?:regex(.*)}"), "test/{param}-{param2}");
Assert.AreEqual(parse("test/{Param:int}-{PaRAM2?:regex((.){4,10})}"), "test/{param}-{param2}");
}
}
public class TestPresenterWithoutInterface
{
}
public class TestPresenter : IDotvvmPresenter
{
public Task ProcessRequest(IDotvvmRequestContext context)
{
throw new NotImplementedException();
}
}
}
| |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Storage.v1.Data;
using Google.Cloud.ClientTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Google.Cloud.Storage.V1.IntegrationTests
{
/// <summary>
/// Fixture which is set up at the start of the test run, and torn down at the end.
/// This creates new buckets with test data, and deletes them at the end of the test.
/// The Google Cloud Project name is fetched from the TEST_PROJECT environment variable.
/// </summary>
[CollectionDefinition(nameof(StorageFixture))]
[FileLoggerBeforeAfterTest]
public sealed class StorageFixture : CloudProjectFixtureBase, ICollectionFixture<StorageFixture>
{
internal const string CrossLanguageTestBucket = "storage-library-test-bucket";
private const string RequesterPaysProjectEnvironmentVariable = "REQUESTER_PAYS_TEST_PROJECT";
private const string RequesterPaysCredentialsEnvironmentVariable = "REQUESTER_PAYS_CREDENTIALS";
public const string DelayTestSuffix = "_InitDelayTest";
private static TypeInfo _delayTestsTypeBeingRegistered;
/// <summary>
/// Name of a bucket which already exists, but has no canned data. Mostly used
/// for creating objects.
/// </summary>
public string InitiallyEmptyBucket => BucketPrefix + "-empty";
/// <summary>
/// A small amount of content. Do not mutate the array.
/// </summary>
public byte[] SmallContent { get; } = Encoding.UTF8.GetBytes("hello, world");
/// <summary>
/// A large amount of content (more than 10K). Do not mutate the array.
/// </summary>
public byte[] LargeContent { get; }
/// <summary>
/// Bucket without versioning enabled, which tests can write to.
/// </summary>
public string SingleVersionBucket => BucketPrefix + "single";
/// <summary>
/// Bucket with versioning enabled, which tests can write to.
/// </summary>
public string MultiVersionBucket => BucketPrefix + "multi";
/// <summary>
/// Bucket to be used for requester-pays testing, or null if requester-pays is not configured.
/// </summary>
public string RequesterPaysBucket { get; }
/// <summary>
/// Project ID of the requester-pays bucket, or null if requester-pays is not configured.
/// (This may be removable later, when we don't need to specify it in options.)
/// </summary>
private string RequesterPaysProjectId { get; }
/// <summary>
/// Storage client set up with requester-pays credentials, or null if requester-pays is not configured.
/// </summary>
private StorageClient RequesterPaysClient { get; }
/// <summary>
/// Bucket which tests should *not* write to, so that tests can
/// rely on the precise contents. This bucket supports multiple versions.
/// </summary>
public string ReadBucket => BucketPrefix + "testsonlyread";
public string BucketPrefix { get; }
public StorageClient Client { get; }
/// <summary>
/// Name of an object populated in <see cref="ReadBucket"/> with <see cref="SmallContent"/>.
/// </summary>
public string SmallObject { get; } = "small.txt";
/// <summary>
/// Name of an object populated in <see cref="ReadBucket"/> with <see cref="LargeContent"/>.
/// </summary>
public string LargeObject { get; } = "large.txt";
/// <summary>
/// Name of an object in <see cref="ReadBucket"/> with a first version containing
/// <see cref="SmallContent"/> and a second version containing <see cref="LargeContent"/>.
/// </summary>
public string SmallThenLargeObject { get; } = "small_then_large.txt";
/// <summary>
/// Gets an HTTP client that can be used to make requests during a test.
/// </summary>
public HttpClient HttpClient { get; } = new HttpClient();
/// <summary>
/// Gets a <see cref="UrlSigner"/> instance which can be used for testing.
/// </summary>
public UrlSigner UrlSigner { get; } =
UrlSigner.FromServiceAccountCredential(GoogleCredential.GetApplicationDefaultAsync().Result.UnderlyingCredential as ServiceAccountCredential);
public IEnumerable<string> ReadBucketObjects => new[] { SmallObject, LargeObject, SmallThenLargeObject }.Concat(s_objectsInFolders);
/// <summary>
/// Name of the only test-related bucket beginning with z. (For easy listing tests.)
/// </summary>
public string BucketBeginningWithZ => BucketPrefix + "zbucketname";
public string LabelsTestBucket => BucketPrefix + "labels";
/// <summary>
/// Returns all the known buckets that have been created for this test run.
/// (This includes any buckets created by <see cref="CreateBucket"/> or registered
/// with <see cref="RegisterBucketToDelete(string)"/>).
/// </summary>
public IEnumerable<string> AllBuckets => _bucketsToDelete;
private static readonly string[] s_objectsInFolders = { "a/o1.txt", "a/o2.txt", "a/x/o3.txt", "a/x/o4.txt", "b/o5.txt" };
private readonly List<string> _bucketsToDelete = new List<string>();
private readonly HashSet<string> _classesWithDelayTests = new HashSet<string>();
private readonly Dictionary<string, DelayTestInfo> _delayTests = new Dictionary<string, DelayTestInfo>();
private bool _delayTestsNeedToStart;
public StorageFixture()
{
Client = StorageClient.Create();
BucketPrefix = IdGenerator.FromDateTime(prefix: "tests-", suffix: "-");
LargeContent = Encoding.UTF8.GetBytes(string.Join("\n", Enumerable.Repeat("All work and no play makes Jack a dull boy.", 500)));
CreateBucket(SingleVersionBucket, false);
CreateBucket(MultiVersionBucket, true);
CreateAndPopulateReadBucket();
CreateBucket(BucketBeginningWithZ, false);
CreateBucket(LabelsTestBucket, false);
CreateBucket(InitiallyEmptyBucket, false);
RequesterPaysClient = CreateRequesterPaysClient();
if (RequesterPaysClient != null)
{
RequesterPaysProjectId = Environment.GetEnvironmentVariable(RequesterPaysProjectEnvironmentVariable);
if (string.IsNullOrEmpty(RequesterPaysProjectId))
{
throw new Exception($"{RequesterPaysCredentialsEnvironmentVariable} set, but not {RequesterPaysProjectEnvironmentVariable}");
}
RequesterPaysBucket = CreateRequesterPaysBucket();
}
// Clean up any HMAC keys left over previous runs.
PurgeHmacKeys();
}
private static StorageClient CreateRequesterPaysClient()
{
string file = Environment.GetEnvironmentVariable(RequesterPaysCredentialsEnvironmentVariable);
if (string.IsNullOrEmpty(file))
{
return null;
}
var credential = GoogleCredential.FromFile(file);
return StorageClient.Create(credential);
}
private string CreateRequesterPaysBucket()
{
string name = IdGenerator.FromDateTime(prefix: "dotnet-requesterpays-");
CreateBucket();
AddServiceAccountBinding();
CreateObject();
return name;
// Adds the service account associated with the application default credentials as a writer for the bucket.
// Note: this assumes the default credentials *are* a service account. If we've got a compute credential,
// this will cause a problem - but in reality, our tests always run with a service account.
void AddServiceAccountBinding()
{
var credential = (ServiceAccountCredential) GoogleCredential.GetApplicationDefault().UnderlyingCredential;
string serviceAccountEmail = credential.Id;
var policy = RequesterPaysClient.GetBucketIamPolicy(name,
new GetBucketIamPolicyOptions { UserProject = RequesterPaysProjectId });
// Note: we assume there are no conditions in the policy, as we've only just created the bucket.
var writerRole = "roles/storage.objectAdmin";
Policy.BindingsData writerBinding = null;
foreach (var binding in policy.Bindings)
{
if (binding.Role == writerRole)
{
writerBinding = binding;
break;
}
}
if (writerBinding == null)
{
writerBinding = new Policy.BindingsData { Role = writerRole, Members = new List<string>() };
policy.Bindings.Add(writerBinding);
}
writerBinding.Members.Add($"serviceAccount:{serviceAccountEmail}");
RequesterPaysClient.SetBucketIamPolicy(name, policy,
new SetBucketIamPolicyOptions { UserProject = RequesterPaysProjectId });
}
void CreateBucket()
{
RequesterPaysClient.CreateBucket(RequesterPaysProjectId,
new Bucket { Name = name, Billing = new Bucket.BillingData { RequesterPays = true } });
SleepAfterBucketCreateDelete();
}
void CreateObject()
{
RequesterPaysClient.UploadObject(name, SmallObject, "text/plain", new MemoryStream(SmallContent),
new UploadObjectOptions { UserProject = RequesterPaysProjectId });
}
}
internal Bucket CreateBucket(string name, bool multiVersion)
{
var bucket = Client.CreateBucket(ProjectId, new Bucket { Name = name, Versioning = new Bucket.VersioningData { Enabled = multiVersion } });
SleepAfterBucketCreateDelete();
RegisterBucketToDelete(name);
return bucket;
}
internal string GenerateBucketName() => IdGenerator.FromGuid(prefix: BucketPrefix, separator: "", maxLength: 63);
private void CreateAndPopulateReadBucket()
{
CreateBucket(ReadBucket, true);
Client.UploadObject(ReadBucket, SmallObject, "text/plain", new MemoryStream(SmallContent));
Client.UploadObject(ReadBucket, LargeObject, "text/plain", new MemoryStream(LargeContent));
Client.UploadObject(ReadBucket, SmallThenLargeObject, "text/plain", new MemoryStream(SmallContent));
Client.UploadObject(ReadBucket, SmallThenLargeObject, "text/plain", new MemoryStream(LargeContent));
foreach (var name in s_objectsInFolders)
{
Client.UploadObject(ReadBucket, name, "text/plain", new MemoryStream(SmallContent));
}
}
/// <summary>
/// Bucket creation/deletion is rate-limited. To avoid making the tests flaky, we sleep after each operation.
/// </summary>
internal static void SleepAfterBucketCreateDelete() => Thread.Sleep(2000);
internal void RegisterBucketToDelete(string bucket) => _bucketsToDelete.Add(bucket);
internal void UnregisterBucket(string bucket) => _bucketsToDelete.Remove(bucket);
internal async Task FinishDelayTest(string testName)
{
DelayTestInfo currentTestInfo;
GaxPreconditions.CheckState(_delayTests.TryGetValue(testName, out currentTestInfo), $"{testName} was not registered or was finalized twice.");
if (_delayTestsNeedToStart)
{
_delayTestsNeedToStart = false;
foreach (var testInfo in _delayTests.Values)
{
await testInfo.StartTest();
}
}
currentTestInfo.OnTestFinalizing();
// Add some additional delay just in case there is a minor difference in times between
// this machine and the server.
var resolvedExpiration = currentTestInfo.DelayExpiration.Value + TimeSpan.FromSeconds(3);
var now = DateTimeOffset.UtcNow;
if (now < resolvedExpiration)
{
await Task.Delay(resolvedExpiration - now);
}
await currentTestInfo.AfterDelayAction();
_delayTests.Remove(testName);
}
internal void RegisterDelayTests(object testClass)
{
try
{
GaxPreconditions.CheckState(_delayTestsTypeBeingRegistered == null, "We should not be recursively registering delay tests.");
_delayTestsTypeBeingRegistered = testClass.GetType().GetTypeInfo();
if (_classesWithDelayTests.Add(_delayTestsTypeBeingRegistered.FullName))
{
var testMethodInits = from method in _delayTestsTypeBeingRegistered.DeclaredMethods
where method.IsPrivate && method.Name.EndsWith(DelayTestSuffix)
select method;
foreach (var testMethodInit in testMethodInits)
{
testMethodInit.Invoke(testClass, null);
}
}
}
finally
{
_delayTestsTypeBeingRegistered = null;
}
}
internal void RegisterDelayTest(TimeSpan duration, Func<TimeSpan, Task> beforeDelay, Func<Task> afterDelay, [CallerMemberName] string initMethodName = null)
{
GaxPreconditions.CheckArgument(
initMethodName.EndsWith(StorageFixture.DelayTestSuffix),
initMethodName,
$"The delay test initialization method name must end with {StorageFixture.DelayTestSuffix}");
var methodName = initMethodName.Substring(0, initMethodName.Length - StorageFixture.DelayTestSuffix.Length);
var testName = $"{_delayTestsTypeBeingRegistered.Name}.{methodName}";
GaxPreconditions.CheckState(!_delayTests.ContainsKey(testName), $"{testName} was registered twice");
GaxPreconditions.CheckState(
_delayTestsTypeBeingRegistered.GetDeclaredMethod(methodName) != null,
$"There is no test named {testName} representing the delay test.");
GaxPreconditions.CheckState(
_delayTestsTypeBeingRegistered.GetDeclaredMethod(methodName).GetCustomAttribute(typeof(FactAttribute)) != null,
$"{testName} must have the {nameof(FactAttribute)} attribute.");
_delayTests.Add(testName, new DelayTestInfo(duration, beforeDelay, afterDelay));
_delayTestsNeedToStart = true;
}
public override void Dispose()
{
var client = StorageClient.Create();
foreach (var bucket in _bucketsToDelete)
{
DeleteBucket(client, bucket, null);
}
if (RequesterPaysBucket != null)
{
DeleteBucket(RequesterPaysClient, RequesterPaysBucket, RequesterPaysProjectId);
}
PurgeHmacKeys();
}
private void DeleteBucket(StorageClient client, string bucket, string userProject)
{
try
{
client.DeleteBucket(bucket, new DeleteBucketOptions { UserProject = userProject, DeleteObjects = true });
}
catch (GoogleApiException)
{
// Some tests fail to delete buckets due to object retention locks etc.
// They can be cleaned up later.
}
SleepAfterBucketCreateDelete();
}
/// <summary>
/// Sets the labels on <see cref="LabelsTestBucket"/> without using any of the client *Labels methods.
/// Any old labels are wiped.
/// </summary>
public void SetUpLabels(Dictionary<string, string> labels, [CallerMemberName] string callerName = null)
{
// Just avoid mutating the parameter...
labels = new Dictionary<string, string>(labels);
var oldLabels = Client.GetBucket(LabelsTestBucket).Labels ?? new Dictionary<string, string>();
foreach (var key in oldLabels.Keys.Except(labels.Keys))
{
labels[key] = null;
}
FileLogger.Log($"Starting patching {LabelsTestBucket} by {callerName}.");
Client.PatchBucket(new Bucket { Name = LabelsTestBucket, Labels = labels });
FileLogger.Log($"Finished patching {LabelsTestBucket} by {callerName}.");
SleepAfterBucketCreateDelete();
}
/// <summary>
/// Clears the labels on <see cref="LabelsTestBucket"/> without using any of the client *Labels methods.
/// </summary>
public void ClearLabels([CallerMemberName] string callerName = null)
{
var oldLabels = Client.GetBucket(LabelsTestBucket).Labels ?? new Dictionary<string, string>();
var cleanLabels = new Dictionary<string, string>();
foreach (var key in oldLabels.Keys)
{
cleanLabels.Add(key, null);
}
FileLogger.Log($"Starting clearing labels for {LabelsTestBucket} by {callerName}.");
Client.PatchBucket(new Bucket { Name = LabelsTestBucket, Labels = cleanLabels });
FileLogger.Log($"Finished clearing labels for {LabelsTestBucket} by {callerName}.");
SleepAfterBucketCreateDelete();
}
private void PurgeHmacKeys()
{
var keys = Client.ListHmacKeys(ProjectId).ToList();
foreach (var key in keys)
{
if (key.State != HmacKeyStates.Inactive)
{
key.State = HmacKeyStates.Inactive;
Client.UpdateHmacKey(key);
}
Client.DeleteHmacKey(ProjectId, key.AccessId);
}
}
private class DelayTestInfo
{
private ExceptionDispatchInfo _exceptionDispatchInfo;
public DateTimeOffset? DelayExpiration { get; private set; }
public Func<Task> AfterDelayAction { get; }
public Func<TimeSpan, Task> BeforeDelayTask { get; }
public TimeSpan Duration { get; }
public DelayTestInfo(TimeSpan duration, Func<TimeSpan, Task> beforeDelayTask, Func<Task> afterDelayAction)
{
AfterDelayAction = afterDelayAction;
BeforeDelayTask = beforeDelayTask;
Duration = duration;
}
public async Task StartTest()
{
if (DelayExpiration == null)
{
try
{
await BeforeDelayTask(Duration);
}
catch (Exception ex)
{
_exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex);
}
DelayExpiration = DateTimeOffset.UtcNow + Duration;
}
}
public void OnTestFinalizing()
{
Debug.Assert(DelayExpiration != null, "A delay test is finalizing before being started.");
if (_exceptionDispatchInfo != null)
{
_exceptionDispatchInfo.Throw();
}
}
}
}
}
| |
/*
* LinkedList.cs - Generic doubly-linked list class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Generics
{
using System;
public sealed class LinkedList<T>
: IDeque<T>, IQueue<T>, IStack<T>, IList<T>, ICloneable
{
// Structure of a list node.
private class Node<T>
{
public T data;
public Node<T> next;
public Node<T> prev;
public Node(T data)
{
this.data = data;
this.next = null;
this.prev = null;
}
}; // class Node
// Internal state.
private Node<T> first;
private Node<T> last;
private int count;
// Constructor.
public LinkedList()
{
first = null;
last = null;
count = 0;
}
// Get a particular node in the list by index.
private Node<T> Get(int index)
{
Node<T> current;
if(index < 0 || index >= count)
{
throw new ArgumentOutOfRangeException
("index", S._("ArgRange_Array"));
}
if(index <= (count / 2))
{
// Search forwards from the start of the list.
current = first;
while(index > 0)
{
current = current.next;
--index;
}
return current;
}
else
{
// Search backwards from the end of the list.
current = last;
++index;
while(index < count)
{
current = current.prev;
++index;
}
return current;
}
}
// Remove a node from this list.
private void Remove(Node<T> node)
{
if(node.next != null)
{
node.next.prev = node.prev;
}
else
{
last = node.prev;
}
if(node.prev != null)
{
node.prev.next = node.next;
}
else
{
first = node.next;
}
--count;
}
// Insert a data item before a specific node.
private void InsertBefore(Node<T> node, T value)
{
Node<T> newNode = new Node<T>(value);
newNode.next = node;
newNode.prev = node.prev;
node.prev = newNode;
if(newNode.prev == null)
{
first = newNode;
}
++count;
}
// Implement the IDeque<T> interface.
public void PushFront(T value)
{
Node<T> node = new Node<T>(item);
node.next = first;
if(first != null)
{
first.prev = node;
}
else
{
last = node;
}
first = node;
++count;
}
public void PushBack(T value)
{
Node<T> node = new Node<T>(item);
node.prev = last;
if(last != null)
{
last.next = node;
}
else
{
first = node;
}
last = node;
++count;
}
public T PopFront()
{
if(first != null)
{
Node<T> node = first;
if(node.next != null)
{
node.next.prev = null;
}
else
{
last = null;
}
first = node.next;
--count;
return node.data;
}
else
{
throw new InvalidOperationException
(S._("Invalid_EmptyList"));
}
}
public T PopBack()
{
if(last != null)
{
Node<T> node = last;
if(node.prev != null)
{
node.prev.next = null;
}
else
{
first = null;
}
last = node.prev;
--count;
return node.data;
}
else
{
throw new InvalidOperationException
(S._("Invalid_EmptyList"));
}
}
public T PeekFront()
{
if(first != null)
{
return first.data;
}
else
{
throw new InvalidOperationException
(S._("Invalid_EmptyList"));
}
}
public T PeekEnd()
{
if(last != null)
{
return last.data;
}
else
{
throw new InvalidOperationException
(S._("Invalid_EmptyList"));
}
}
public T[] ToArray()
{
T[] array = new T [Count];
CopyTo(array, 0);
return array;
}
// Implement the IQueue<T> interface privately.
void IQueue<T>.Clear()
{
Clear();
}
bool IQueue<T>.Contains(T value)
{
return Contains(value);
}
void IQueue<T>.Enqueue(T value)
{
PushBack(value);
}
T IQueue<T>.Dequeue()
{
return PopFront();
}
T IQueue<T>.Peek()
{
return PeekFront();
}
T[] IQueue<T>.ToArray()
{
return ToArray();
}
// Implement the IStack<T> interface privately.
void IStack<T>.Clear()
{
Clear();
}
bool IStack<T>.Contains(T value)
{
return Contains(value);
}
void IStack<T>.Push(T value)
{
PushFront(value);
}
T IStack<T>.Pop()
{
return PopFront();
}
T IStack<T>.Peek()
{
return PeekFront();
}
T[] IStack<T>.ToArray()
{
return ToArray();
}
// Implement the ICollection<T> interface.
public void CopyTo(T[] array, int index)
{
IIterator<T> iterator = GetIterator();
while(iterator.MoveNext())
{
array[index++] = iterator.Current;
}
}
public int Count
{
get
{
return count;
}
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public Object SyncRoot
{
get
{
return this;
}
}
// Implement the IList<T> interface.
public int Add(T value)
{
int index = count;
PushBack(value);
return index;
}
public void Clear()
{
first = null;
last = null;
count = 0;
}
public bool Contains(T value)
{
Node<T> current = first;
if(typeof(T).IsValueType)
{
while(current != null)
{
if(value.Equals(current.data))
{
return true;
}
current = current.next;
}
return false;
}
else
{
if(((Object)value) != null)
{
while(current != null)
{
if(value.Equals(current.data))
{
return true;
}
current = current.next;
}
return false;
}
else
{
while(current != null)
{
if(((Object)(current.data)) == null)
{
return true;
}
current = current.next;
}
return false;
}
}
}
public IListIterator<T> GetIterator()
{
return new ListIterator<T>(this);
}
public int IndexOf(T value)
{
int index = 0;
Node<T> current = first;
if(typeof(T).IsValueType)
{
while(current != null)
{
if(value.Equals(current.data))
{
return index;
}
++index;
current = current.next;
}
return -1;
}
else
{
if(((Object)value) != null)
{
while(current != null)
{
if(value.Equals(current.data))
{
return index;
}
++index;
current = current.next;
}
return -1;
}
else
{
while(current != null)
{
if(((Object)(current.data)) == null)
{
return index;
}
++index;
current = current.next;
}
return -1;
}
}
}
public void Insert(int index, T value)
{
if(index == count)
{
PushBack(value);
}
else
{
Node<T> current = Get(index);
InsertBefore(current, value);
}
}
public void Remove(T value)
{
Node<T> current = first;
if(typeof(T).IsValueType)
{
while(current != null)
{
if(value.Equals(current.data))
{
Remove(current);
return;
}
current = current.next;
}
}
else
{
if(((Object)value) != null)
{
while(current != null)
{
if(value.Equals(current.data))
{
Remove(current);
return;
}
current = current.next;
}
}
else
{
while(current != null)
{
if(((Object)(current.data)) == null)
{
Remove(current);
return;
}
current = current.next;
}
}
}
}
public void RemoveAt(int index)
{
Remove(Get(index));
}
public bool IsRandomAccess
{
get
{
return false;
}
}
public T this[int index]
{
get
{
return Get(index).data;
}
set
{
Get(index).data = value;
}
}
// Implement the IIterable<T> interface.
IIterator<T> IIterator<T>.GetIterator()
{
return GetIterator();
}
// Implement the ICloneable interface.
public Object Clone()
{
LinkedList<T> clone = new LinkedList<T>();
IIterator<T> e = GetIterator();
while(e.MoveNext())
{
clone.PushBack(e.Current);
}
return clone;
}
// Iterator class for lists.
private class ListIterator<T> : IListIterator<T>
{
// Internal state, accessible to "LinkedList<T>".
public LinkedList<T> list;
public Node<T> posn;
public int index;
public bool reset;
public bool removed;
// Constructor.
public ListIterator(LinkedList<T> list)
{
this.list = list;
this.posn = null;
this.index = -1;
this.reset = true;
this.removed = false;
}
// Implement the IIterator<T> interface.
public bool MoveNext()
{
if(reset)
{
posn = list.first;
index = 0;
reset = false;
}
else if(posn != null)
{
posn = posn.next;
if(!removed)
{
++index;
}
}
removed = false;
return (posn != null);
}
public void Reset()
{
posn = null;
index = -1;
reset = true;
removed = false;
}
public void Remove()
{
if(posn == null || removed)
{
throw new InvalidOperationException
(S._("Invalid_BadIteratorPosition"));
}
list.Remove(posn);
removed = true;
}
T IIterator<T>.Current
{
get
{
if(posn == null || removed)
{
throw new InvalidOperationException
(S._("Invalid_BadIteratorPosition"));
}
return posn.data;
}
}
// Implement the IListIterator<T> interface.
public bool MovePrev()
{
if(reset)
{
posn = list.last;
index = list.count - 1;
reset = false;
}
else if(posn != null)
{
posn = posn.prev;
--index;
}
removed = false;
return (posn != null);
}
public int Position
{
get
{
if(posn == null || removed)
{
throw new InvalidOperationException
(S._("Invalid_BadIteratorPosition"));
}
return index;
}
}
public T Current
{
get
{
if(posn == null || removed)
{
throw new InvalidOperationException
(S._("Invalid_BadIteratorPosition"));
}
return posn.data;
}
set
{
if(posn == null || removed)
{
throw new InvalidOperationException
(S._("Invalid_BadIteratorPosition"));
}
posn.data = value;
}
}
}; // class ListIterator<T>
}; // class LinkedList<T>
}; // namespace Generics
| |
// 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 Internal.TypeSystem;
using Internal.TypeSystem.Interop;
using Debug = System.Diagnostics.Debug;
using Internal.TypeSystem.Ecma;
namespace Internal.IL.Stubs
{
/// <summary>
/// Provides method bodies for PInvoke methods
///
/// This by no means intends to provide full PInvoke support. The intended use of this is to
/// a) prevent calls getting generated to targets that require a full marshaller
/// (this compiler doesn't provide that), and b) offer a hand in some very simple marshalling
/// situations (but support for this part might go away as the product matures).
/// </summary>
public struct PInvokeILEmitter
{
private readonly MethodDesc _targetMethod;
private readonly Marshaller[] _marshallers;
private readonly PInvokeILEmitterConfiguration _pInvokeILEmitterConfiguration;
private readonly PInvokeMetadata _importMetadata;
private readonly PInvokeFlags _flags;
private readonly InteropStateManager _interopStateManager;
private PInvokeILEmitter(MethodDesc targetMethod, PInvokeILEmitterConfiguration pinvokeILEmitterConfiguration, InteropStateManager interopStateManager)
{
Debug.Assert(targetMethod.IsPInvoke || targetMethod is DelegateMarshallingMethodThunk);
_targetMethod = targetMethod;
_pInvokeILEmitterConfiguration = pinvokeILEmitterConfiguration;
_importMetadata = targetMethod.GetPInvokeMethodMetadata();
_interopStateManager = interopStateManager;
//
// targetMethod could be either a PInvoke or a DelegateMarshallingMethodThunk
// ForwardNativeFunctionWrapper method thunks are marked as PInvokes, so it is
// important to check them first here so that we get the right flags.
//
if (_targetMethod is DelegateMarshallingMethodThunk delegateMethod)
{
_flags = ((EcmaType)delegateMethod.DelegateType.GetTypeDefinition()).GetDelegatePInvokeFlags();
}
else
{
Debug.Assert(_targetMethod.IsPInvoke);
_flags = _importMetadata.Flags;
}
_marshallers = InitializeMarshallers(targetMethod, interopStateManager, _flags);
}
private static Marshaller[] InitializeMarshallers(MethodDesc targetMethod, InteropStateManager interopStateManager, PInvokeFlags flags)
{
MarshalDirection direction = MarshalDirection.Forward;
MethodSignature methodSig;
switch (targetMethod)
{
case DelegateMarshallingMethodThunk delegateMethod:
methodSig = delegateMethod.DelegateSignature;
direction = delegateMethod.Direction;
break;
case CalliMarshallingMethodThunk calliMethod:
methodSig = calliMethod.TargetSignature;
break;
default:
methodSig = targetMethod.Signature;
break;
}
int indexOffset = 0;
if (!methodSig.IsStatic && direction == MarshalDirection.Forward)
{
// For instance methods(eg. Forward delegate marshalling thunk), first argument is
// the instance
indexOffset = 1;
}
ParameterMetadata[] parameterMetadataArray = targetMethod.GetParameterMetadata();
Marshaller[] marshallers = new Marshaller[methodSig.Length + 1];
int parameterIndex = 0;
ParameterMetadata parameterMetadata;
for (int i = 0; i < marshallers.Length; i++)
{
Debug.Assert(parameterIndex == parameterMetadataArray.Length || i <= parameterMetadataArray[parameterIndex].Index);
if (parameterIndex == parameterMetadataArray.Length || i < parameterMetadataArray[parameterIndex].Index)
{
// if we don't have metadata for the parameter, create a dummy one
parameterMetadata = new ParameterMetadata(i, ParameterMetadataAttributes.None, null);
}
else
{
Debug.Assert(i == parameterMetadataArray[parameterIndex].Index);
parameterMetadata = parameterMetadataArray[parameterIndex++];
}
TypeDesc parameterType = (i == 0) ? methodSig.ReturnType : methodSig[i - 1]; //first item is the return type
marshallers[i] = Marshaller.CreateMarshaller(parameterType,
MarshallerType.Argument,
parameterMetadata.MarshalAsDescriptor,
direction,
marshallers,
interopStateManager,
indexOffset + parameterMetadata.Index,
flags,
parameterMetadata.In,
parameterMetadata.Out,
parameterMetadata.Return
);
}
return marshallers;
}
private void EmitDelegateCall(DelegateMarshallingMethodThunk delegateMethod, PInvokeILCodeStreams ilCodeStreams)
{
ILEmitter emitter = ilCodeStreams.Emitter;
ILCodeStream fnptrLoadStream = ilCodeStreams.FunctionPointerLoadStream;
ILCodeStream marshallingCodeStream = ilCodeStreams.MarshallingCodeStream;
ILCodeStream callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream;
TypeSystemContext context = _targetMethod.Context;
Debug.Assert(delegateMethod != null);
if (delegateMethod.Kind == DelegateMarshallingMethodThunkKind.ReverseOpenStatic)
{
//
// For Open static delegates call
// InteropHelpers.GetCurrentCalleeOpenStaticDelegateFunctionPointer()
// which returns a function pointer. Just call the function pointer and we are done.
//
TypeDesc[] parameters = new TypeDesc[_marshallers.Length - 1];
for (int i = 1; i < _marshallers.Length; i++)
{
parameters[i - 1] = _marshallers[i].ManagedParameterType;
}
MethodSignature managedSignature = new MethodSignature(
MethodSignatureFlags.Static, 0, _marshallers[0].ManagedParameterType, parameters);
fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(
delegateMethod.Context.GetHelperType("InteropHelpers").GetKnownMethod(
"GetCurrentCalleeOpenStaticDelegateFunctionPointer", null)));
ILLocalVariable vDelegateStub = emitter.NewLocal(
delegateMethod.Context.GetWellKnownType(WellKnownType.IntPtr));
fnptrLoadStream.EmitStLoc(vDelegateStub);
callsiteSetupCodeStream.EmitLdLoc(vDelegateStub);
callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(managedSignature));
}
else if (delegateMethod.Kind == DelegateMarshallingMethodThunkKind.ReverseClosed)
{
//
// For closed delegates call
// InteropHelpers.GetCurrentCalleeDelegate<Delegate>
// which returns the delegate. Do a CallVirt on the invoke method.
//
MethodDesc instantiatedHelper = delegateMethod.Context.GetInstantiatedMethod(
delegateMethod.Context.GetHelperType("InteropHelpers")
.GetKnownMethod("GetCurrentCalleeDelegate", null),
new Instantiation((delegateMethod.DelegateType)));
fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(instantiatedHelper));
ILLocalVariable vDelegateStub = emitter.NewLocal(delegateMethod.DelegateType);
fnptrLoadStream.EmitStLoc(vDelegateStub);
marshallingCodeStream.EmitLdLoc(vDelegateStub);
MethodDesc invokeMethod = delegateMethod.DelegateType.GetKnownMethod("Invoke", null);
callsiteSetupCodeStream.Emit(ILOpcode.callvirt, emitter.NewToken(invokeMethod));
}
else if (delegateMethod.Kind == DelegateMarshallingMethodThunkKind
.ForwardNativeFunctionWrapper)
{
// if the SetLastError flag is set in UnmanagedFunctionPointerAttribute, clear the error code before doing P/Invoke
if (_flags.SetLastError)
{
callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
InteropTypes.GetPInvokeMarshal(context).GetKnownMethod("ClearLastWin32Error", null)));
}
//
// For NativeFunctionWrapper we need to load the native function and call it
//
fnptrLoadStream.EmitLdArg(0);
fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(InteropTypes
.GetNativeFunctionPointerWrapper(context)
.GetMethod("get_NativeFunctionPointer", null)));
var fnPtr = emitter.NewLocal(
context.GetWellKnownType(WellKnownType.IntPtr));
fnptrLoadStream.EmitStLoc(fnPtr);
callsiteSetupCodeStream.EmitLdLoc(fnPtr);
TypeDesc nativeReturnType = _marshallers[0].NativeParameterType;
TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1];
for (int i = 1; i < _marshallers.Length; i++)
{
nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType;
}
MethodSignature nativeSig = new MethodSignature(
MethodSignatureFlags.Static | _flags.UnmanagedCallingConvention, 0, nativeReturnType, nativeParameterTypes);
callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig));
// if the SetLastError flag is set in UnmanagedFunctionPointerAttribute, call the PInvokeMarshal.
// SaveLastWin32Error so that last error can be used later by calling
// PInvokeMarshal.GetLastWin32Error
if (_flags.SetLastError)
{
callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
InteropTypes.GetPInvokeMarshal(context)
.GetKnownMethod("SaveLastWin32Error", null)));
}
}
else
{
Debug.Fail("Unexpected DelegateMarshallingMethodThunkKind");
}
}
private void EmitPInvokeCall(PInvokeILCodeStreams ilCodeStreams)
{
ILEmitter emitter = ilCodeStreams.Emitter;
ILCodeStream fnptrLoadStream = ilCodeStreams.FunctionPointerLoadStream;
ILCodeStream callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream;
TypeSystemContext context = _targetMethod.Context;
TypeDesc nativeReturnType = _marshallers[0].NativeParameterType;
TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1];
// if the SetLastError flag is set in DllImport, clear the error code before doing P/Invoke
if (_flags.SetLastError)
{
callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
InteropTypes.GetPInvokeMarshal(context).GetKnownMethod("ClearLastWin32Error", null)));
}
for (int i = 1; i < _marshallers.Length; i++)
{
nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType;
}
if (!_pInvokeILEmitterConfiguration.GenerateDirectCall(_importMetadata.Module, _importMetadata.Name))
{
MetadataType lazyHelperType = context.GetHelperType("InteropHelpers");
FieldDesc lazyDispatchCell = _interopStateManager.GetPInvokeLazyFixupField(_targetMethod);
fnptrLoadStream.Emit(ILOpcode.ldsflda, emitter.NewToken(lazyDispatchCell));
fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(lazyHelperType
.GetKnownMethod("ResolvePInvoke", null)));
MethodSignatureFlags unmanagedCallConv = _flags.UnmanagedCallingConvention;
MethodSignature nativeSig = new MethodSignature(
_targetMethod.Signature.Flags | unmanagedCallConv, 0, nativeReturnType,
nativeParameterTypes);
ILLocalVariable vNativeFunctionPointer = emitter.NewLocal(context
.GetWellKnownType(WellKnownType.IntPtr));
fnptrLoadStream.EmitStLoc(vNativeFunctionPointer);
callsiteSetupCodeStream.EmitLdLoc(vNativeFunctionPointer);
callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig));
}
else
{
// Eager call
MethodSignature nativeSig = new MethodSignature(
_targetMethod.Signature.Flags, 0, nativeReturnType, nativeParameterTypes);
MethodDesc nativeMethod =
new PInvokeTargetNativeMethod(_targetMethod, nativeSig);
callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(nativeMethod));
}
// if the SetLastError flag is set in DllImport, call the PInvokeMarshal.
// SaveLastWin32Error so that last error can be used later by calling
// PInvokeMarshal.GetLastWin32Error
if (_flags.SetLastError)
{
callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
InteropTypes.GetPInvokeMarshal(context)
.GetKnownMethod("SaveLastWin32Error", null)));
}
}
private void EmitCalli(PInvokeILCodeStreams ilCodeStreams, CalliMarshallingMethodThunk calliThunk)
{
ILEmitter emitter = ilCodeStreams.Emitter;
ILCodeStream callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream;
TypeDesc nativeReturnType = _marshallers[0].NativeParameterType;
TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1];
for (int i = 1; i < _marshallers.Length; i++)
{
nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType;
}
MethodSignature nativeSig = new MethodSignature(
calliThunk.TargetSignature.Flags, 0, nativeReturnType,
nativeParameterTypes);
callsiteSetupCodeStream.EmitLdArg(calliThunk.TargetSignature.Length);
callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig));
}
private MethodIL EmitIL()
{
PInvokeILCodeStreams pInvokeILCodeStreams = new PInvokeILCodeStreams();
ILEmitter emitter = pInvokeILCodeStreams.Emitter;
ILCodeStream unmarshallingCodestream = pInvokeILCodeStreams.UnmarshallingCodestream;
// Marshal the arguments
for (int i = 0; i < _marshallers.Length; i++)
{
_marshallers[i].EmitMarshallingIL(pInvokeILCodeStreams);
}
// make the call
switch (_targetMethod)
{
case DelegateMarshallingMethodThunk delegateMethod:
EmitDelegateCall(delegateMethod, pInvokeILCodeStreams);
break;
case CalliMarshallingMethodThunk calliMethod:
EmitCalli(pInvokeILCodeStreams, calliMethod);
break;
default:
EmitPInvokeCall(pInvokeILCodeStreams);
break;
}
_marshallers[0].LoadReturnValue(unmarshallingCodestream);
unmarshallingCodestream.Emit(ILOpcode.ret);
return new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(_targetMethod), IsStubRequired());
}
public static MethodIL EmitIL(MethodDesc method,
PInvokeILEmitterConfiguration pinvokeILEmitterConfiguration,
InteropStateManager interopStateManager)
{
try
{
return new PInvokeILEmitter(method, pinvokeILEmitterConfiguration, interopStateManager)
.EmitIL();
}
catch (NotSupportedException)
{
string message = "Method '" + method.ToString() +
"' requires non-trivial marshalling that is not yet supported by this compiler.";
return MarshalHelpers.EmitExceptionBody(message, method);
}
catch (InvalidProgramException ex)
{
Debug.Assert(!String.IsNullOrEmpty(ex.Message));
return MarshalHelpers.EmitExceptionBody(ex.Message, method);
}
}
private bool IsStubRequired()
{
Debug.Assert(_targetMethod.IsPInvoke || _targetMethod is DelegateMarshallingMethodThunk);
if (_targetMethod is DelegateMarshallingMethodThunk)
{
return true;
}
// The configuration can be null if this is delegate or calli marshalling
if (_pInvokeILEmitterConfiguration != null)
{
if (!_pInvokeILEmitterConfiguration.GenerateDirectCall(_importMetadata.Module, _importMetadata.Name))
{
return true;
}
}
if (_flags.SetLastError)
{
return true;
}
for (int i = 0; i < _marshallers.Length; i++)
{
if (_marshallers[i].IsMarshallingRequired())
return true;
}
return false;
}
}
internal sealed class PInvokeILCodeStreams
{
public ILEmitter Emitter { get; }
public ILCodeStream FunctionPointerLoadStream { get; }
public ILCodeStream MarshallingCodeStream { get; }
public ILCodeStream CallsiteSetupCodeStream { get; }
public ILCodeStream ReturnValueMarshallingCodeStream { get; }
public ILCodeStream UnmarshallingCodestream { get; }
public PInvokeILCodeStreams()
{
Emitter = new ILEmitter();
// We have 4 code streams:
// - _marshallingCodeStream is used to convert each argument into a native type and
// store that into the local
// - callsiteSetupCodeStream is used to used to load each previously generated local
// and call the actual target native method.
// - _returnValueMarshallingCodeStream is used to convert the native return value
// to managed one.
// - _unmarshallingCodestream is used to propagate [out] native arguments values to
// managed ones.
FunctionPointerLoadStream = Emitter.NewCodeStream();
MarshallingCodeStream = Emitter.NewCodeStream();
CallsiteSetupCodeStream = Emitter.NewCodeStream();
ReturnValueMarshallingCodeStream = Emitter.NewCodeStream();
UnmarshallingCodestream = Emitter.NewCodeStream();
}
public PInvokeILCodeStreams(ILEmitter emitter, ILCodeStream codeStream)
{
Emitter = emitter;
MarshallingCodeStream = codeStream;
}
}
public sealed class PInvokeILStubMethodIL : ILStubMethodIL
{
public bool IsStubRequired { get; }
public PInvokeILStubMethodIL(ILStubMethodIL methodIL, bool isStubRequired) : base(methodIL)
{
IsStubRequired = isStubRequired;
}
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using ProtoCore.DSASM.Mirror;
using ProtoTestFx.TD;
namespace ProtoTest.TD.Imperative
{
public class InlineCondition
{
public TestFrameWork thisTest = new TestFrameWork();
string testPath = "..\\..\\..\\Scripts\\TD\\Imperative\\InlineCondition\\";
[SetUp]
public void Setup()
{
}
[Test]
[Category("SmokeTest")]
public void T001_Inline_Using_Function_Call()
{
string src = @"smallest2;
largest2;
[Imperative]
{
def fo1 : int(a1 : int)
{
return = a1 * a1;
}
a = 10;
b = 20;
smallest1 = a < b ? a : b;
largest1 = a > b ? a : b;
d = fo1(a);
smallest2 = (fo1(a)) < (fo1(b)) ? (fo1(a)) : (fo1(a)); //100
largest2 = (fo1(a)) > (fo1(b)) ? (fo1(a)) : (fo1(b)); //400
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
Assert.IsTrue((Int64)mirror.GetValue("smallest2").Payload == 100);
Assert.IsTrue((Int64)mirror.GetValue("largest2").Payload == 400);
}
[Ignore]
[Category("SmokeTest")]
public void T002_Inline_Using_Math_Lib_Functions()
{
string src = @"[Imperative]
{
external (""libmath"") def dc_sqrt : double (val : double);
def sqrt : double (val : double)
{
return = dc_sqrt(val);
}
def fo1 (a1 : int) = a1 * a1 ;
a = 10;
b = 20;
smallest1 = a < b ? a : b; //10
largest1 = a > b ? a : b; //20
d = fo1(a);
smallest2 = sqrt(fo1(a)) < sqrt(fo1(b)) ? sqrt(fo1(a)) : sqrt(fo1(a)); //10.0
largest2 = sqrt(fo1(a)) > sqrt(fo1(b)) ? sqrt(fo1(a)) : sqrt(fo1(b)); //20.0
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
Assert.IsTrue((Double)mirror.GetValue("smallest2").Payload == 10.0);
Assert.IsTrue((Double)mirror.GetValue("largest2").Payload == 20.0);
}
[Ignore]
public void T003_Inline_Using_Collection()
{
string src = @"[Imperative]
{
Passed = 1;
Failed = 0;
Einstein = 56;
BenBarnes = 90;
BenGoh = 5;
Rameshwar = 80;
Jun = 68;
Roham = 50;
Smartness = { BenBarnes, BenGoh, Jun, Rameshwar, Roham }; // { 1, 0, 1, 1, 0 }
Results = Smartness > Einstein ? Passed : Failed;
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
List<Object> result = new List<object> { 1, 0, 1, 1, 0, };
Assert.IsTrue(mirror.CompareArrays("Results", result, typeof(System.Int64)));
}
[Ignore]
public void T005_Inline_Using_2_Collections_In_Condition()
{
string src = @"[Imperative]
{
a1 = 1..3..1;
b1 = 4..6..1;
a2 = 1..3..1;
b2 = 4..7..1;
a3 = 1..4..1;
b3 = 4..6..1;
c1 = a1 > b1 ? true : false; // { false, false, false }
c2 = a2 > b2 ? true : false; // { false, false, false }
c3 = a3 > b3 ? true : false; // { false, false, false, null }
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
List<Object> c1 = new List<object> { false, false, false };
List<Object> c2 = new List<object> { false, false, false };
List<Object> c3 = new List<object> { false, false, false, null };
Assert.IsTrue(mirror.CompareArrays("c1", c1, typeof(System.Boolean)));
Assert.IsTrue(mirror.CompareArrays("c2", c2, typeof(System.Boolean)));
Assert.IsTrue(mirror.CompareArrays("c3", c3, typeof(System.Object)));
}
[Ignore]
public void T006_Inline_Using_Different_Sized_1_Dim_Collections()
{
string src = @"[Imperative]
{
a = 10 ;
b = ((a - a / 2 * 2) > 0)? a : a+1 ; //11
c = 5;
d = ((c - c / 2 * 2) > 0)? c : c+1 ; //5
e1 = ((b>(d-b+d))) ? d : (d+1); //5
//inline conditional, returning different sized collections
c1 = {1,2,3};
c2 = {1,2};
a1 = {1, 2, 3, 4};
b1 = a1>3?true:a1; // expected : {1, 2, 3, true}
b2 = a1>3?true:c1; // expected : {1, 2, 3}
b3 = a1>3?c1:c2; // expected : {1, 2}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
List<Object> b1 = new List<object> { 1, 2, 3, true };
List<Object> b2 = new List<object> { 1, 2, 3 };
List<Object> b3 = new List<object> { 1, 2 };
Assert.IsTrue(mirror.CompareArrays("b1", b1, typeof(System.Object)));
Assert.IsTrue(mirror.CompareArrays("b2", b2, typeof(System.Int64)));
Assert.IsTrue(mirror.CompareArrays("b3", b3, typeof(System.Int64)));
}
[Ignore]
public void T007_Inline_Using_Collections_And_Replication()
{
string src = @"[Imperative]
{
def even : int(a : int)
{
return = a * 2;
}
a =1..10..1 ; //{1,2,3,4,5,6,7,8,9,10}
i = 1..5;
b = ((a[i] % 2) > 0)? even(a[i]) : a ; // { 1, 6, 3, 10, 5 }
c = ((a[0] % 2) > 0)? even(a[i]) : a ; // { 4, 6, 8, `0, `2 }
d = ((a[-2] % 2) == 0)? even(a[i]) : a ; // { 1, 2,..10}
e1 = (a[-2] == d[9])? 9 : a[1..2]; // { 2, 3 }
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
List<Object> b = new List<object> { 1, 6, 3, 10, 5 };
List<Object> c = new List<object> { 4, 6, 8, 0, 2 };
List<Object> d = new List<object> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<Object> e1 = new List<object> { 2, 3 };
Assert.IsTrue(mirror.CompareArrays("b", b, typeof(System.Int64)));
Assert.IsTrue(mirror.CompareArrays("c", c, typeof(System.Int64)));
Assert.IsTrue(mirror.CompareArrays("d", d, typeof(System.Int64)));
Assert.IsTrue(mirror.CompareArrays("e1", e1, typeof(System.Int64)));
}
[Test]
[Category("SmokeTest")]
public void T008_Inline_Returing_Different_Ranks()
{
string src = @"x;
[Imperative]
{
a = { 0, 1, 2, 4};
x = a > 1 ? 0 : {1,1}; // { 1, 1} ?
x_0 = x[0];
x_1 = x[1];
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
List<Object> x = new List<object> { 1, 1 };
Assert.IsTrue(mirror.CompareArrays("x", x, typeof(System.Int64)));
}
[Ignore]
public void T009_Inline_Using_Function_Call_And_Collection_And_Replication()
{
string src = @"[Imperative]
{
def even(a : int)
{
return = a * 2;
}
def odd(a : int )
{
return = a* 2 + 1;
}
x = 1..3;
a = ((even(5) > odd(3)))? even(5) : even(3); //10
b = ((even(x) > odd(x+1)))?odd(x+1):even(x) ; // {2,4,6}
c = odd(even(3)); // 13
d = ((a > c))?even(odd(c)) : odd(even(c)); //53
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
List<Object> b = new List<object> { 2, 4, 6 };
Assert.IsTrue(mirror.CompareArrays("b", b, typeof(System.Int64)));
Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 10);
Assert.IsTrue((Int64)mirror.GetValue("c").Payload == 13);
Assert.IsTrue((Int64)mirror.GetValue("d").Payload == 53);
}
[Test]
[Category("SmokeTest")]
public void T010_Inline_Using_Literal_Values()
{
string src = @"a;
b;
c;
d;
e;
f;
g;
h;
[Imperative]
{
a = 1 > 2.5 ? false: 1;
b = 0.55 == 1 ? true : false;
c = (( 1 + 0.5 ) / 2 ) <= (200/10) ? (8/2) : (6/3);
d = true ? true : false;
e = false ? true : false;
f = true == true ? 1 : 0.5;
g = (1/3.0) > 0 ? (1/3.0) : (4/3);
h = (1/3.0) < 0 ? (1/3.0) : (4/3);
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 1);
Assert.IsTrue(System.Convert.ToBoolean(mirror.GetValue("b").Payload) == false);
Assert.IsTrue(Convert.ToInt64(mirror.GetValue("c").Payload) == 4);
Assert.IsTrue(System.Convert.ToBoolean(mirror.GetValue("d").Payload));
Assert.IsTrue(System.Convert.ToBoolean(mirror.GetValue("e").Payload) == false);
Assert.IsTrue((Int64)mirror.GetValue("f").Payload == 1);
Assert.IsTrue((double)mirror.GetValue("g").Payload == 0.33333333333333331);
Assert.IsTrue(Convert.ToInt64(mirror.GetValue("h").Payload) == 1);
}
[Test]
[Category("SmokeTest")]
public void T011_Inline_Using_Variables()
{
string code = @"
class A
{
a : var;
constructor A ( i : int)
{
a = i;
}
}
x1;
x2;
x3;
x4;
x5;
temp;
[Imperative]
{
a = 1;
b = 0.5;
c = -1;
d = true;
f = null;
g = false;
h = A.A(1);
i = h.a;
x1 = a > b ? c : d;
x2 = a <= b ? c : d;
x3 = f == g ? h : i;
x4 = f != g ? h : i;
x5 = f != g ? h : h.a;
temp = x3.a;
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
Object n1 = null;
thisTest.Verify("x1", -1);
thisTest.Verify("x2", true);
thisTest.Verify("x4", 1);
thisTest.Verify("x5", 1);
thisTest.Verify("x3", 1);
thisTest.Verify("temp", n1);
}
[Test]
[Category("SmokeTest")]
public void T012_Inline_Using_Fun_Calls()
{
string code = @"
class A
{
a : var;
constructor A ( i : int)
{
a = i;
}
}
def power ( a )
{
return = a * a ;
}
a = power(1);
b = power(0.5);
c = -1;
d = true;
f = null;
g = false;
h = A.A(1);
i = h.a;
x1 = power(power(2)) > power(2) ? power(1) : power(0);
x2 = power(power(2)) < power(2) ? power(1) : power(0);
x3 = power(c) < b ? power(1) : power(0);
x4 = power(f) >= power(1) ? power(1) : power(0);
x5 = power(f) < power(1) ? power(1) : power(0);
x6 = power(i) >= power(h.a) ? power(1) : power(0);
x7 = power(f) >= power(i) ? power(1) : power(0);
";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
Object n1 = null;
thisTest.SetErrorMessage("1467231 - Sprint 26 - Rev 3393 null to bool conversion should not be allowed");
thisTest.Verify("x1", 1);
thisTest.Verify("x2", 0);
thisTest.Verify("x3", 0);
thisTest.Verify("x4", 0);
thisTest.Verify("x5", 0);
thisTest.Verify("x6", 1);
thisTest.Verify("x7", 0);
}
[Test]
[Category("SmokeTest")]
public void T013_Inline_Using_Class()
{
string code = @"
class A
{
a : var;
constructor A ( i : int)
{
a = i;
}
def foo ( b )
{
return = a * b ;
}
}
def power ( a )
{
return = a * a ;
}
a = A.A(-1);
b = A.A(0);
c = A.A(2);
x1 = a.a < a.foo(2) ? a.a : a.foo(2);
x2 = a.a >= a.foo(2) ? a.a : a.foo(2);
x3 = a.foo(power(3)) < power(b.foo(3)) ? a.foo(power(3)) : power(b.foo(3));
x4 = a.foo(power(3)) >= power(b.foo(3)) ? a.foo(power(3)) : power(b.foo(3));
";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("x1", -2, 0);
thisTest.Verify("x2", -1, 0);
thisTest.Verify("x3", -9, 0);
thisTest.Verify("x4", 0, 0);
}
[Test]
[Category("Replication")]
public void T014_Inline_Using_Collections()
{
string err = "1467166 - Sprint24 : rev 3133 : Regression : comparison of collection with singleton should yield null in imperative scope";
string src = @"t1;t2;t3;t4;t5;t7;
c1;c2;c3;c4;
[Imperative]
{
a = { 0, 1, 2};
b = { 3, 11 };
c = 5;
d = { 6, 7, 8, 9};
e = { 10 };
x1 = a < 5 ? b : 5;
t1 = x1[0];
t2 = x1[1];
c1 = 0;
for (i in x1)
{
c1 = c1 + 1;
}
x2 = 5 > b ? b : 5;
t3 = x2[0];
t4 = x2[1];
c2 = 0;
for (i in x2)
{
c2 = c2 + 1;
}
x3 = b < d ? b : e;
t5 = x3[0];
c3 = 0;
for (i in x3)
{
c3 = c3 + 1;
}
x4 = b > e ? d : { 0, 1};
t7 = x4[0];
c4 = 0;
for (i in x4)
{
c4 = c4 + 1;
}
}
";
thisTest.VerifyRunScriptSource(src, err);
thisTest.Verify("t1", 3);
thisTest.Verify("t2", 11);
thisTest.Verify("c1", 2);
thisTest.Verify("t3", 3);
thisTest.Verify("t4", 5);
thisTest.Verify("c2", 2);
thisTest.Verify("t5", 3);
thisTest.Verify("c3", 1);
thisTest.Verify("t7", 0);
thisTest.Verify("c4", 1);
}
[Test]
public void T015_Inline_In_Class_Scope()
{
// Assert.Fail("1467168 - Sprint24 : rev 3137 : Compiler error from Inline Condition and class inheritance issue");
string code = @"
class A
{
a : int;
constructor A ( i : int)
{
a = i < 0 ? i*i : i;
}
def foo1 ( b )
{
x = b == a ? b : b+a;
return = x;
}
}
class B extends A
{
b : int;
constructor B ( i : int)
{
a = i < 0 ? i*i : i;
b = i;
}
def foo2 ( x )
{
y = b == a ? x+b : x+b+a;
return = y;
}
}
b1 = B.B(1);
b2 = B.B(-1);
x1 = b1.foo2(3);
x2 = b2.foo2(-3);
a1 = A.A(-4);
x3 = a1.foo1(3);
";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("x1", 4, 0);
thisTest.Verify("x2", -3, 0);
thisTest.Verify("x3", 19, 0);
}
[Test]
[Category("Replication")]
public void T016_Inline_Using_Operators()
{
//Assert.Fail("1456751 - Sprint16 : Rev 990 : Inline conditions not working with replication over collections ");
string code = @"
def foo (a:int )
{
return = a;
}
a = 1+2 > 3*4 ? 5-9 : 10/2;
b = a > -a ? 1 : 0;
c = 2> 1 && 4>3 ? 1 : 0;
d = 1 == 1 || (1 == 0) ? 1 : 0;
e1 = a > b && c > d ? 1 : 0;
f = a <= b || c <= d ? 1 : 0;
g = foo({ 1, 2 }) > 3+ foo({4,5,6}) ? 1 : 3+ foo({4,5,6});
i = {1,3} > 2 ? 1: 0;";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
Object[][] array = { new Object[] { 7, 8, 9 }, new Object[] { 7, 8, 9 } };
Object[] array2 = { 0, 1 };
thisTest.Verify("a", 5.0, 0);
thisTest.Verify("b", 1, 0);
thisTest.Verify("c", 1, 0);
thisTest.Verify("d", 1, 0);
thisTest.Verify("e1", 0, 0);
thisTest.Verify("f", 1, 0);
thisTest.Verify("g", array, 0);
thisTest.Verify("i", array2, 0);
}
[Test]
[Category("SmokeTest")]
public void T017_Inline_In_Function_Scope()
{
string code = @"
def foo1 ( b )
{
return = b == 0 ? b : b+1;
}
def foo2 ( x )
{
y = [Imperative]
{
if(x > 0)
{
return = x >=foo1(x) ? x : foo1(x);
}
return = x >=2 ? x : 2;
}
x1 = y == 0 ? 0 : y;
return = y + x1;
}
a1 = foo1(4);
a2 = foo2(3);
";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("a1", 5, 0);
thisTest.Verify("a2", 8, 0);
}
[Test]
[Category("SmokeTest")]
public void T018_Inline_Using_Recursion()
{
Assert.Fail("Cauing NUnit failures. Disabled");
string code = @"
def factorial : int (num : int)
{
return = num < 2 ? 1 : num * factorial(num-1);
}
fac = factorial(10);";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("fac", 3628800, 0);
}
[Test]
[Category("SmokeTest")]
public void T019_Defect_1456758()
{
string code = @"
b = true;
a1 = b && true ? -1 : 1;
a2;
[Imperative]
{
a2 = b && true ? -1 : 1;
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("a1", -1);
thisTest.Verify("a2", -1);
}
[Test]
[Category("SmokeTest")]
public void T020_Nested_And_With_Range_Expr()
{
string code = @"
a1 = 1 > 2 ? true : 2 > 1 ? 2 : 1;
a2 = 1 > 2 ? true : 0..3;
b = {0,1,2,3};
a3 = 1 > 2 ? true : b;";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
Object[] ExpectedRes_1 = { 0, 1, 2, 3 };
Object[] ExpectedRes_2 = { 0, 1, 2, 3 };
thisTest.Verify("a1", 2, 0);
thisTest.Verify("a2", ExpectedRes_1, 0);
thisTest.Verify("b", ExpectedRes_2, 0);
thisTest.Verify("a3", ExpectedRes_2, 0);
}
[Test]
[Category("Imperative")]
public void T021_Defect_1467166_array_comparison_issue()
{
string code = @"
[Imperative]
{
a = { 0, 1, 2};
xx = a < 1 ? 1 : 0;
}";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("xx", 5);
}
[Test]
[Category("Replication")]
public void T22_Defect_1467166()
{
String code =
@"xx;
[Imperative]
{
a = { 0, 1, 2};
xx = a < 1 ? 1 : 0;
}
";
ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner();
String errmsg = "";
ExecutionMirror mirror = thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("xx", 0);
}
[Test]
[Category("Replication")]
public void T22_Defect_1467166_2()
{
String code =
@"xx;
[Imperative]
{
a = { 0, 1, 2};
xx = 2 > 1 ? a : 0;
}
";
ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner();
String errmsg = "";
ExecutionMirror mirror = thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("xx", new Object[] { 0, 1, 2 });
}
[Test]
[Category("Replication")]
public void T22_Defect_1467166_3()
{
String code =
@"
x1;x2;x3;x4;x5;
[Imperative]
{
def foo () = null;
x1 = null == null ? 1 : 0;
x2 = null != null ? 1 : 0;
x3 = null == a ? 1 : 0;
x4 = foo2(1) == a ? 1 : 0;
x5 = foo() == null ? 1 : 0;
}
";
ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner();
String errmsg = "";
ExecutionMirror mirror = thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("x1", 1);
thisTest.Verify("x2", 0);
thisTest.Verify("x3", 1);
thisTest.Verify("x4", 1);
thisTest.Verify("x5", 1);
}
[Test]
[Category("Replication")]
public void T23_1467403_inline_null()
{
String code =
@"a = null;
d2 = (a!=null)? 1 : 0;
";
ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner();
String errmsg = "";
ExecutionMirror mirror = thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d2", 0);
thisTest.VerifyBuildWarningCount(0);
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// Represents <see cref="T:int[]"/>, as a slice (offset + length) into an
/// existing <see cref="T:int[]"/>. The <see cref="Int32s"/> member should never be <c>null</c>; use
/// <see cref="EMPTY_INT32S"/> if necessary.
/// <para/>
/// NOTE: This was IntsRef in Lucene
/// <para/>
/// @lucene.internal
/// </summary>
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public sealed class Int32sRef : IComparable<Int32sRef>
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
/// <summary>
/// An empty integer array for convenience.
/// <para/>
/// NOTE: This was EMPTY_INTS in Lucene
/// </summary>
public static readonly int[] EMPTY_INT32S =
#if FEATURE_ARRAYEMPTY
Array.Empty<int>();
#else
new int[0];
#endif
/// <summary>
/// The contents of the <see cref="Int32sRef"/>. Should never be <c>null</c>.
/// <para/>
/// NOTE: This was ints (field) in Lucene
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] Int32s // LUCENENET TODO: API - change to indexer
{
get => ints;
set
{
if (value == null)
{
throw new ArgumentNullException("Ints should never be null");
}
ints = value;
}
}
private int[] ints;
/// <summary>
/// Offset of first valid integer. </summary>
public int Offset { get; set; }
/// <summary>
/// Length of used <see cref="int"/>s. </summary>
public int Length { get; set; }
/// <summary>
/// Create a <see cref="Int32sRef"/> with <see cref="EMPTY_INT32S"/>. </summary>
public Int32sRef()
{
ints = EMPTY_INT32S;
}
/// <summary>
/// Create a <see cref="Int32sRef"/> pointing to a new array of size <paramref name="capacity"/>.
/// Offset and length will both be zero.
/// </summary>
public Int32sRef(int capacity)
{
ints = new int[capacity];
}
/// <summary>
/// This instance will directly reference <paramref name="ints"/> w/o making a copy.
/// <paramref name="ints"/> should not be <c>null</c>.
/// </summary>
public Int32sRef(int[] ints, int offset, int length)
{
this.ints = ints;
this.Offset = offset;
this.Length = length;
Debug.Assert(IsValid());
}
/// <summary>
/// Returns a shallow clone of this instance (the underlying <see cref="int"/>s are
/// <b>not</b> copied and will be shared by both the returned object and this
/// object.
/// </summary>
/// <seealso cref="DeepCopyOf(Int32sRef)"/>
public object Clone()
{
return new Int32sRef(ints, Offset, Length);
}
public override int GetHashCode()
{
const int prime = 31;
int result = 0;
int end = Offset + Length;
for (int i = Offset; i < end; i++)
{
result = prime * result + ints[i];
}
return result;
}
public override bool Equals(object other)
{
if (other == null)
{
return false;
}
if (other is Int32sRef)
{
return this.Int32sEquals((Int32sRef)other);
}
return false;
}
/// <summary>
/// NOTE: This was intsEquals() in Lucene
/// </summary>
public bool Int32sEquals(Int32sRef other)
{
if (Length == other.Length)
{
int otherUpto = other.Offset;
int[] otherInts = other.ints;
int end = Offset + Length;
for (int upto = Offset; upto < end; upto++, otherUpto++)
{
if (ints[upto] != otherInts[otherUpto])
{
return false;
}
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Signed <see cref="int"/> order comparison. </summary>
public int CompareTo(Int32sRef other)
{
if (this == other)
{
return 0;
}
int[] aInts = this.ints;
int aUpto = this.Offset;
int[] bInts = other.ints;
int bUpto = other.Offset;
int aStop = aUpto + Math.Min(this.Length, other.Length);
while (aUpto < aStop)
{
int aInt = aInts[aUpto++];
int bInt = bInts[bUpto++];
if (aInt > bInt)
{
return 1;
}
else if (aInt < bInt)
{
return -1;
}
}
// One is a prefix of the other, or, they are equal:
return this.Length - other.Length;
}
/// <summary>
/// NOTE: This was copyInts() in Lucene
/// </summary>
public void CopyInt32s(Int32sRef other)
{
if (ints.Length - Offset < other.Length)
{
ints = new int[other.Length];
Offset = 0;
}
Array.Copy(other.ints, other.Offset, ints, Offset, other.Length);
Length = other.Length;
}
/// <summary>
/// Used to grow the reference array.
/// <para/>
/// In general this should not be used as it does not take the offset into account.
/// <para/>
/// @lucene.internal
/// </summary>
public void Grow(int newLength)
{
Debug.Assert(Offset == 0);
if (ints.Length < newLength)
{
ints = ArrayUtil.Grow(ints, newLength);
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
int end = Offset + Length;
for (int i = Offset; i < end; i++)
{
if (i > Offset)
{
sb.Append(' ');
}
sb.Append(ints[i].ToString("x"));
}
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// Creates a new <see cref="Int32sRef"/> that points to a copy of the <see cref="int"/>s from
/// <paramref name="other"/>
/// <para/>
/// The returned <see cref="Int32sRef"/> will have a length of <c>other.Length</c>
/// and an offset of zero.
/// </summary>
public static Int32sRef DeepCopyOf(Int32sRef other)
{
Int32sRef clone = new Int32sRef();
clone.CopyInt32s(other);
return clone;
}
/// <summary>
/// Performs internal consistency checks.
/// Always returns true (or throws <see cref="InvalidOperationException"/>)
/// </summary>
public bool IsValid()
{
if (ints == null)
{
throw new InvalidOperationException("ints is null");
}
if (Length < 0)
{
throw new InvalidOperationException("length is negative: " + Length);
}
if (Length > ints.Length)
{
throw new InvalidOperationException("length is out of bounds: " + Length + ",ints.length=" + Int32s.Length);
}
if (Offset < 0)
{
throw new InvalidOperationException("offset is negative: " + Offset);
}
if (Offset > ints.Length)
{
throw new InvalidOperationException("offset out of bounds: " + Offset + ",ints.length=" + Int32s.Length);
}
if (Offset + Length < 0)
{
throw new InvalidOperationException("offset+length is negative: offset=" + Offset + ",length=" + Length);
}
if (Offset + Length > Int32s.Length)
{
throw new InvalidOperationException("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",ints.length=" + Int32s.Length);
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections.Generic;
// Test derived from dotnet/corefx src\System.Numerics.Vectors\src\System\Numerics\Matrix4x4.cs, op_Multiply().
// This was an ARM32-specific bug for addressing local variables as floats. ARM32 floating-point instructions
// have a different offset range than integer instructions. If the local variable itself is a struct, but the
// instruction generated is a float local field, then we were computing the offset as integer, but the actual
// instruction was float. In certain frame layouts, the range will be out of range in this case, but we will
// not have allocated a "reserved" register which is used for generating large offsets.
//
// The key functions in the JIT that are related are Compiler::compRsvdRegCheck() and Compiler::lvaFrameAddress().
public class Test
{
public struct BigStruct
{
public float float1;
public float float2;
public float float3;
public float float4;
public float float5;
public float float6;
public float float7;
public float float8;
public float float9;
public float float10;
public float float11;
public float float12;
public float float13;
public float float14;
public float float15;
public float float16;
public float float17;
public float float18;
public float float19;
public float float20;
public float float21;
public float float22;
public float float23;
public float float24;
public float float25;
public float float26;
public float float27;
public float float28;
public float float29;
public float float30;
public float float31;
public float float32;
public float float33;
public float float34;
public float float35;
public float float36;
public float float37;
public float float38;
public float float39;
public float float40;
public float float41;
public float float42;
public float float43;
public float float44;
public float float45;
public float float46;
public float float47;
public float float48;
public float float49;
public float float50;
public float float51;
public float float52;
public float float53;
public float float54;
public float float55;
public float float56;
public float float57;
public float float58;
public float float59;
public float float60;
public float float61;
public float float62;
public float float63;
public float float64;
public float float65;
public float float66;
public float float67;
public float float68;
public float float69;
public float float70;
public float float71;
public float float72;
public float float73;
public float float74;
public float float75;
public float float76;
public float float77;
public float float78;
public float float79;
public float float80;
public float float81;
public float float82;
public float float83;
public float float84;
public float float85;
public float float86;
public float float87;
public float float88;
public float float89;
public float float90;
public float float91;
public float float92;
public float float93;
public float float94;
public float float95;
public float float96;
public float float97;
public float float98;
public float float99;
public float float100;
public float float101;
public float float102;
public float float103;
public float float104;
public float float105;
public float float106;
public float float107;
public float float108;
public float float109;
public float float110;
public float float111;
public float float112;
public float float113;
public float float114;
public float float115;
public float float116;
public float float117;
public float float118;
public float float119;
public float float120;
public float float121;
public float float122;
public float float123;
public float float124;
public float float125;
public float float126;
public float float127;
public float float128;
public float float129;
public float float130;
public float float131;
public float float132;
public float float133;
public float float134;
public float float135;
public float float136;
public float float137;
public float float138;
public float float139;
public float float140;
public float float141;
public float float142;
public float float143;
public float float144;
public float float145;
public float float146;
public float float147;
public float float148;
public float float149;
public float float150;
public float float151;
public float float152;
public float float153;
public float float154;
public float float155;
public float float156;
public float float157;
public float float158;
public float float159;
public float float160;
public float float161;
public float float162;
public float float163;
public float float164;
public float float165;
public float float166;
public float float167;
public float float168;
public float float169;
public float float170;
public float float171;
public float float172;
public float float173;
public float float174;
public float float175;
public float float176;
public float float177;
public float float178;
public float float179;
public float float180;
public float float181;
public float float182;
public float float183;
public float float184;
public float float185;
public float float186;
public float float187;
public float float188;
public float float189;
public float float190;
public float float191;
public float float192;
public float float193;
public float float194;
public float float195;
public float float196;
public float float197;
public float float198;
public float float199;
public float float200;
public float float201;
public float float202;
public float float203;
public float float204;
public float float205;
public float float206;
public float float207;
public float float208;
public float float209;
public float float210;
public float float211;
public float float212;
public float float213;
public float float214;
public float float215;
public float float216;
public float float217;
public float float218;
public float float219;
public float float220;
public float float221;
public float float222;
public float float223;
public float float224;
public float float225;
public float float226;
public float float227;
public float float228;
public float float229;
public float float230;
public float float231;
public float float232;
public float float233;
public float float234;
public float float235;
public float float236;
public float float237;
public float float238;
public float float239;
public float float240;
public float float241;
public float float242;
public float float243;
public float float244;
public float float245;
public float float246;
public float float247;
public float float248;
public float float249;
public float float250;
public float float251;
public float float252;
public float float253;
public float float254;
public float float255;
}
public struct Matrix4x4
{
public float M11;
public float M12;
public float M13;
public float M14;
public float M21;
public float M22;
public float M23;
public float M24;
public float M31;
public float M32;
public float M33;
public float M34;
public float M41;
public float M42;
public float M43;
public float M44;
/// <summary>
/// Constructs a Matrix4x4 from the given components.
/// </summary>
public Matrix4x4(float m11, float m12, float m13, float m14,
float m21, float m22, float m23, float m24,
float m31, float m32, float m33, float m34,
float m41, float m42, float m43, float m44)
{
this.M11 = m11;
this.M12 = m12;
this.M13 = m13;
this.M14 = m14;
this.M21 = m21;
this.M22 = m22;
this.M23 = m23;
this.M24 = m24;
this.M31 = m31;
this.M32 = m32;
this.M33 = m33;
this.M34 = m34;
this.M41 = m41;
this.M42 = m42;
this.M43 = m43;
this.M44 = m44;
}
/// <summary>
/// Returns a boolean indicating whether the given two matrices are equal.
/// </summary>
/// <param name="value1">The first matrix to compare.</param>
/// <param name="value2">The second matrix to compare.</param>
/// <returns>True if the given matrices are equal; False otherwise.</returns>
public static bool Equals(Matrix4x4 value1, Matrix4x4 value2)
{
return (value1.M11 == value2.M11 && value1.M22 == value2.M22 && value1.M33 == value2.M33 && value1.M44 == value2.M44 && // Check diagonal element first for early out.
value1.M12 == value2.M12 && value1.M13 == value2.M13 && value1.M14 == value2.M14 && value1.M21 == value2.M21 &&
value1.M23 == value2.M23 && value1.M24 == value2.M24 && value1.M31 == value2.M31 && value1.M32 == value2.M32 &&
value1.M34 == value2.M34 && value1.M41 == value2.M41 && value1.M42 == value2.M42 && value1.M43 == value2.M43);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AddHelper(ref BigStruct b)
{
b.float1 += 1.0F;
b.float255 += 2.0F;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Matrix4x4 AddTest(Matrix4x4 value1, Matrix4x4 value2)
{
BigStruct b = new BigStruct();
b.float1 = value1.M11 + value2.M11;
b.float255 = value1.M12 + value2.M12;
AddHelper(ref b);
Matrix4x4 m;
m = value1;
m.M11 = b.float1 + b.float255;
m.M12 = b.float1 - b.float255;
return m;
}
/// <summary>
/// Returns a String representing this matrix instance.
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
return string.Format("{{ {{M11:{0} M12:{1} M13:{2} M14:{3}}} {{M21:{4} M22:{5} M23:{6} M24:{7}}} {{M31:{8} M32:{9} M33:{10} M34:{11}}} {{M41:{12} M42:{13} M43:{14} M44:{15}}} }}",
M11, M12, M13, M14,
M21, M22, M23, M24,
M31, M32, M33, M34,
M41, M42, M43, M44);
}
public static int Main()
{
Matrix4x4 m1 = new Matrix4x4(1.0F,2.0F,3.0F,4.0F,
5.0F,6.0F,7.0F,8.0F,
9.0F,10.0F,11.0F,12.0F,
13.0F,14.0F,15.0F,16.0F);
Matrix4x4 m2 = new Matrix4x4(13.0F,14.0F,15.0F,16.0F,
9.0F,10.0F,11.0F,12.0F,
5.0F,6.0F,7.0F,8.0F,
1.0F,2.0F,3.0F,4.0F);
Matrix4x4 m3 = AddTest(m1,m2);
Matrix4x4 mresult = new Matrix4x4(33.0F,-3.0F,3.0F,4.0F,
5.0F,6.0F,7.0F,8.0F,
9.0F,10.0F,11.0F,12.0F,
13.0F,14.0F,15.0F,16.0F);
if (Equals(m3,mresult))
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL: matrices don't match");
Console.WriteLine(" m3 = {0}", m3.ToString());
Console.WriteLine(" mresult = {0}", mresult.ToString());
return 1;
}
}
}
}
| |
/*
Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/)
Apache License Version 2.0
*/
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FlaUI.Core;
using Klocman;
using Klocman.Tools;
using UninstallerAutomatizer.Properties;
using UninstallTools;
using Debug = System.Diagnostics.Debug;
namespace UninstallerAutomatizer
{
public class UninstallHandler
{
public bool KillOnFail { get; private set; }
public string UninstallTarget { get; private set; }
public bool IsDaemon { get; private set; }
public event EventHandler<UninstallHandlerUpdateArgs> StatusUpdate;
public void Pause()
{
throw new NotImplementedException();
}
public void Resume()
{
throw new NotImplementedException();
}
public void Start()
{
var args = Environment.GetCommandLineArgs().Skip(1).ToArray();
if (args.Length == 1 && args[0].Equals("/d", StringComparison.OrdinalIgnoreCase))
{
StartDaemon();
return;
}
IsDaemon = false;
if (args.Length < 2)
{
Program.ReturnValue = ReturnValue.InvalidArgumentCode;
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Failed, Localization.Error_Invalid_number_of_arguments));
return;
}
UninstallerType uType;
if (!Enum.TryParse(args[0], out uType))
{
Program.ReturnValue = ReturnValue.InvalidArgumentCode;
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Failed, string.Format(Localization.Error_UnknownUninstallerType, args[0])));
return;
}
args = args.Skip(1).ToArray();
if (args[0].Equals("/k", StringComparison.InvariantCultureIgnoreCase))
{
args = args.Skip(1).ToArray();
KillOnFail = true;
}
UninstallTarget = string.Join(" ", args);
if (!File.Exists(ProcessTools.SeparateArgsFromCommand(UninstallTarget).FileName))
{
Program.ReturnValue = ReturnValue.InvalidArgumentCode;
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Failed, string.Format(Localization.Error_InvalidPath, UninstallTarget)));
return;
}
if (uType != UninstallerType.Nsis)
{
Program.ReturnValue = ReturnValue.InvalidArgumentCode;
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Failed, string.Format(Localization.Error_NotSupported, uType)));
return;
}
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Normal, string.Format(Localization.Message_Starting, UninstallTarget)));
_automationThread = new Thread(AutomationThread) { Name = "AutomationThread", IsBackground = false, Priority = ThreadPriority.AboveNormal };
_automationThread.Start();
}
private void StartDaemon()
{
IsDaemon = true;
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Normal, Localization.UninstallHandler_StartDaemon));
_automationThread = new Thread(DaemonThread) { Name = "AutomationThread", IsBackground = false, Priority = ThreadPriority.AboveNormal };
_automationThread.Start();
}
readonly ConcurrentDictionary<int, Task> _runningHooks = new ConcurrentDictionary<int, Task>();
/// <summary>
/// Run in background as a daemon. Receive application PIDs to monitor, "stop" to exit.
/// </summary>
private void DaemonThread()
{
try
{
using (var server = new NamedPipeServerStream("UninstallAutomatizerDaemon", PipeDirection.In))
using (var reader = new StreamReader(server))
{
while (true)
{
server.WaitForConnection();
Debug.WriteLine("Client connected through pipe");
while (true)
{
var line = reader.ReadLine()?.ToLowerInvariant();
Debug.WriteLine("Received through pipe: " + (line ?? "NULL"));
if (line == null)
{
Thread.Sleep(500);
continue;
}
if (line == "stop")
return;
int pid;
if (!int.TryParse(line, out pid))
{
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Normal,
string.Format(Localization.UninstallHandler_InvalidProcessNumber, pid)));
continue;
}
try
{
if (_runningHooks.TryGetValue(pid, out var ttt) && !ttt.IsCompleted)
continue;
var target = Process.GetProcessById(pid);
if (!ProcessCanBeAutomatized(target))
{
Debug.WriteLine("Tried to automate not allowed process: " + target.ProcessName);
continue;
}
var app = Application.Attach(target);
var t = new Task(() =>
{
try
{
Debug.WriteLine("Running automatizer on thread pool");
AutomatedUninstallManager.AutomatizeApplication(app, AutomatizeStatusCallback);
}
catch (Exception ex)
{
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Normal,
string.Format(Localization.Message_UninstallFailed,
ex.InnerException?.Message ?? ex.Message)));
}
finally
{
Task tt;
_runningHooks.TryRemove(pid, out tt);
}
});
_runningHooks.AddOrUpdate(pid, t, (i, task) => t);
Debug.WriteLine("Created automatizer thread");
t.Start();
}
catch (SystemException ex) { Console.WriteLine(ex); }
}
}
}
}
catch (Exception ex)
{
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Normal,
Localization.UninstallHandler_DaemonStoppedReason + (ex.InnerException?.Message ?? ex.Message)));
}
finally
{
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Succeeded, Localization.Message_Success));
}
}
private static bool ProcessCanBeAutomatized(Process target)
{
return target.Id > 4 && !string.Equals(target.ProcessName, Program.AutomatizerProcessName, StringComparison.Ordinal);
}
Thread _automationThread;
private bool _abort;
private void AutomationThread()
{
try
{
AutomatedUninstallManager.UninstallNsisQuietly(UninstallTarget, AutomatizeStatusCallback);
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Succeeded, Localization.Message_Success));
}
catch (AutomatedUninstallManager.AutomatedUninstallException ex)
{
Debug.Assert(ex.InnerException != null, "ex.InnerException != null");
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Failed, string.Format(Localization.Message_UninstallFailed, ex.InnerException?.Message ?? ex.Message)));
// todo grace period / move to window?
if (ex.UninstallerProcess != null && KillOnFail)
{
try
{
ex.UninstallerProcess.Kill(true);
}
catch
{
// Ignore process errors, can't do anything about it
}
}
Program.ReturnValue = ReturnValue.FunctionFailedCode;
}
}
private void AutomatizeStatusCallback(string s)
{
if (_abort) throw new OperationCanceledException(Localization.Message_UserCancelled);
OnStatusUpdate(new UninstallHandlerUpdateArgs(UninstallHandlerUpdateKind.Normal, s));
}
private UninstallHandlerUpdateArgs _previousArgs;
protected virtual void OnStatusUpdate(UninstallHandlerUpdateArgs e)
{
// Filter out repeated updates
if (Equals(_previousArgs, e)) return;
_previousArgs = e;
StatusUpdate?.Invoke(this, e);
Console.WriteLine(e.Message);
}
public void Abort()
{
_abort = true;
}
}
}
| |
using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace OAuth {
public class OAuthBase {
/// <summary>
/// Provides a predefined set of algorithms that are supported officially by the protocol
/// </summary>
public enum SignatureTypes {
HMACSHA1,
PLAINTEXT,
RSASHA1
}
/// <summary>
/// Provides an internal structure to sort the query parameter
/// </summary>
protected class QueryParameter {
private string name = null;
private string value = null;
public QueryParameter(string name, string value) {
this.name = name;
this.value = value;
}
public string Name {
get { return name; }
}
public string Value {
get { return value; }
}
}
/// <summary>
/// Comparer class used to perform the sorting of the query parameters
/// </summary>
protected class QueryParameterComparer : IComparer<QueryParameter> {
#region IComparer<QueryParameter> Members
public int Compare(QueryParameter x, QueryParameter y) {
if (x.Name == y.Name) {
return string.Compare(x.Value, y.Value);
} else {
return string.Compare(x.Name, y.Name);
}
}
#endregion
}
protected const string OAuthVersion = "1.0";
protected const string OAuthParameterPrefix = "oauth_";
//
// List of know and used oauth parameters' names
//
protected const string OAuthConsumerKeyKey = "oauth_consumer_key";
protected const string OAuthCallbackKey = "oauth_callback";
protected const string OAuthVersionKey = "oauth_version";
protected const string OAuthSignatureMethodKey = "oauth_signature_method";
protected const string OAuthSignatureKey = "oauth_signature";
protected const string OAuthTimestampKey = "oauth_timestamp";
protected const string OAuthNonceKey = "oauth_nonce";
protected const string OAuthTokenKey = "oauth_token";
protected const string OAuthTokenSecretKey = "oauth_token_secret";
protected const string HMACSHA1SignatureType = "HMAC-SHA1";
protected const string PlainTextSignatureType = "PLAINTEXT";
protected const string RSASHA1SignatureType = "RSA-SHA1";
protected Random random = new Random();
protected string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
/// <summary>
/// Helper function to compute a hash value
/// </summary>
/// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param>
/// <param name="data">The data to hash</param>
/// <returns>a Base64 string of the hash value</returns>
private string ComputeHash(HashAlgorithm hashAlgorithm, string data) {
if (hashAlgorithm == null) {
throw new ArgumentNullException("hashAlgorithm");
}
if (string.IsNullOrEmpty(data)) {
throw new ArgumentNullException("data");
}
byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data);
byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
/// <summary>
/// Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_")
/// </summary>
/// <param name="parameters">The query string part of the Url</param>
/// <returns>A list of QueryParameter each containing the parameter name and value</returns>
private List<QueryParameter> GetQueryParameters(string parameters) {
if (parameters.StartsWith("?")) {
parameters = parameters.Remove(0, 1);
}
List<QueryParameter> result = new List<QueryParameter>();
if (!string.IsNullOrEmpty(parameters)) {
string[] p = parameters.Split('&');
foreach (string s in p) {
if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix)) {
if (s.IndexOf('=') > -1) {
string[] temp = s.Split('=');
result.Add(new QueryParameter(temp[0], temp[1]));
} else {
result.Add(new QueryParameter(s, string.Empty));
}
}
}
}
return result;
}
/// <summary>
/// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
/// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
/// </summary>
/// <param name="value">The value to Url encode</param>
/// <returns>Returns a Url encoded string</returns>
protected string UrlEncode(string value) {
StringBuilder result = new StringBuilder();
foreach (char symbol in value) {
if (unreservedChars.IndexOf(symbol) != -1) {
result.Append(symbol);
} else {
result.Append('%' + String.Format("{0:X2}", (int)symbol));
}
}
return result.ToString();
}
/// <summary>
/// Normalizes the request parameters according to the spec
/// </summary>
/// <param name="parameters">The list of parameters already sorted</param>
/// <returns>a string representing the normalized parameters</returns>
protected string NormalizeRequestParameters(IList<QueryParameter> parameters) {
StringBuilder sb = new StringBuilder();
QueryParameter p = null;
for (int i = 0; i < parameters.Count; i++) {
p = parameters[i];
sb.AppendFormat("{0}={1}", p.Name, p.Value);
if (i < parameters.Count - 1) {
sb.Append("&");
}
}
return sb.ToString();
}
/// <summary>
/// Generate the signature base that is used to produce the signature
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param>
/// <returns>The signature base</returns>
public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string signatureType, out string normalizedUrl, out string normalizedRequestParameters) {
if (token == null) {
token = string.Empty;
}
if (tokenSecret == null) {
tokenSecret = string.Empty;
}
if (string.IsNullOrEmpty(consumerKey)) {
throw new ArgumentNullException("consumerKey");
}
if (string.IsNullOrEmpty(httpMethod)) {
throw new ArgumentNullException("httpMethod");
}
if (string.IsNullOrEmpty(signatureType)) {
throw new ArgumentNullException("signatureType");
}
normalizedUrl = null;
normalizedRequestParameters = null;
List<QueryParameter> parameters = GetQueryParameters(url.Query);
parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));
parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));
parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));
if (!string.IsNullOrEmpty(token)) {
parameters.Add(new QueryParameter(OAuthTokenKey, token));
}
parameters.Sort(new QueryParameterComparer());
normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{
normalizedUrl += ":" + url.Port;
}
normalizedUrl += url.AbsolutePath;
normalizedRequestParameters = NormalizeRequestParameters(parameters);
StringBuilder signatureBase = new StringBuilder();
signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));
return signatureBase.ToString();
}
/// <summary>
/// Generate the signature value based on the given signature base and hash algorithm
/// </summary>
/// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
/// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash) {
return ComputeHash(hash, signatureBase);
}
/// <summary>
/// Generates a signature using the HMAC-SHA1 algorithm
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer seceret</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out string normalizedRequestParameters) {
return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, httpMethod, timeStamp, nonce, SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
}
/// <summary>
/// Generates a signature using the specified signatureType
/// </summary>
/// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer seceret</param>
/// <param name="token">The token, if available. If not available pass null or an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The type of signature to use</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters) {
normalizedUrl = null;
normalizedRequestParameters = null;
switch (signatureType) {
case SignatureTypes.PLAINTEXT:
return HttpUtility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret));
case SignatureTypes.HMACSHA1:
string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, timeStamp, nonce, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters);
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)));
return GenerateSignatureUsingHash(signatureBase, hmacsha1);
case SignatureTypes.RSASHA1:
throw new NotImplementedException();
default:
throw new ArgumentException("Unknown signature type", "signatureType");
}
}
/// <summary>
/// Generate the timestamp for the signature
/// </summary>
/// <returns></returns>
public virtual string GenerateTimeStamp() {
// Default implementation of UNIX time of the current UTC time
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// Generate a nonce
/// </summary>
/// <returns></returns>
public virtual string GenerateNonce() {
// Just a simple implementation of a random number between 123400 and 9999999
return random.Next(123400, 9999999).ToString();
}
}
}
| |
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using XenAdmin.Controls;
namespace XenAdmin.TabPages
{
sealed partial class SnapshotsPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
ConnectionsManager.History.CollectionChanged -= History_CollectionChanged;
if(components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SnapshotsPage));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
this.GeneralTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.contentTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.panelPropertiesColumn = new System.Windows.Forms.Panel();
this.panelVMPP = new System.Windows.Forms.Panel();
this.linkLabelVMPPInfo = new System.Windows.Forms.LinkLabel();
this.labelVMPPInfo = new System.Windows.Forms.Label();
this.pictureBoxVMPPInfo = new System.Windows.Forms.PictureBox();
this.propertiesGroupBox = new System.Windows.Forms.GroupBox();
this.propertiesTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanelSimpleSelection = new System.Windows.Forms.TableLayoutPanel();
this.folderLabel = new System.Windows.Forms.Label();
this.sizeLabel = new System.Windows.Forms.Label();
this.tagsLabel = new System.Windows.Forms.Label();
this.descriptionLabel = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.sizeTitleLabel = new System.Windows.Forms.Label();
this.folderTitleLabel = new System.Windows.Forms.Label();
this.tagsTitleLabel = new System.Windows.Forms.Label();
this.customFieldTitle1 = new System.Windows.Forms.Label();
this.customFieldContent1 = new System.Windows.Forms.Label();
this.customFieldTitle2 = new System.Windows.Forms.Label();
this.customFieldContent2 = new System.Windows.Forms.Label();
this.labelModeTitle = new System.Windows.Forms.Label();
this.labelMode = new System.Windows.Forms.Label();
this.propertiesButton = new System.Windows.Forms.Button();
this.nameLabel = new System.Windows.Forms.Label();
this.shadowPanel1 = new XenAdmin.Controls.ShadowPanel();
this.screenshotPictureBox = new System.Windows.Forms.PictureBox();
this.viewPanel = new System.Windows.Forms.Panel();
this.snapshotTreeView = new XenAdmin.Controls.SnapshotTreeView(this.components);
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.newSnapshotButton = new System.Windows.Forms.Button();
this.toolTipContainerRevertButton = new XenAdmin.Controls.ToolTipContainer();
this.revertButton = new System.Windows.Forms.Button();
this.buttonView = new System.Windows.Forms.Button();
this.saveButton = new System.Windows.Forms.Button();
this.deleteButton = new System.Windows.Forms.Button();
this.chevronButton1 = new XenAdmin.Controls.ChevronButton();
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.TakeSnapshotToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.revertToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveVMToolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveVMToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveTemplateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.separatorDeleteToolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortByToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortByNameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortByCreatedOnToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortBySizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortByTypeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortToolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.propertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.Live = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Snapshot = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Date = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.size = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.tags = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.description = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dateLabel = new System.Windows.Forms.Label();
this.tableLayoutPanelMultipleSelection = new System.Windows.Forms.TableLayoutPanel();
this.multipleSelectionTags = new System.Windows.Forms.Label();
this.multipleSelectionTotalSize = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.saveMenuStrip = new XenAdmin.Controls.NonReopeningContextMenuStrip(this.components);
this.saveAsVMToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.saveAsTemplateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportAsBackupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStripView = new XenAdmin.Controls.NonReopeningContextMenuStrip(this.components);
this.toolStripButtonListView = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripButtonTreeView = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparatorView = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItemScheduledSnapshots = new System.Windows.Forms.ToolStripMenuItem();
this.pageContainerPanel.SuspendLayout();
this.GeneralTableLayoutPanel.SuspendLayout();
this.contentTableLayoutPanel.SuspendLayout();
this.panelPropertiesColumn.SuspendLayout();
this.panelVMPP.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxVMPPInfo)).BeginInit();
this.propertiesGroupBox.SuspendLayout();
this.propertiesTableLayoutPanel.SuspendLayout();
this.tableLayoutPanelSimpleSelection.SuspendLayout();
this.shadowPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.screenshotPictureBox)).BeginInit();
this.viewPanel.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.toolTipContainerRevertButton.SuspendLayout();
this.contextMenuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.tableLayoutPanelMultipleSelection.SuspendLayout();
this.saveMenuStrip.SuspendLayout();
this.contextMenuStripView.SuspendLayout();
this.SuspendLayout();
//
// pageContainerPanel
//
this.pageContainerPanel.Controls.Add(this.GeneralTableLayoutPanel);
resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel");
//
// GeneralTableLayoutPanel
//
resources.ApplyResources(this.GeneralTableLayoutPanel, "GeneralTableLayoutPanel");
this.GeneralTableLayoutPanel.BackColor = System.Drawing.Color.Transparent;
this.GeneralTableLayoutPanel.Controls.Add(this.contentTableLayoutPanel, 0, 1);
this.GeneralTableLayoutPanel.Controls.Add(this.tableLayoutPanel2, 0, 0);
this.GeneralTableLayoutPanel.Name = "GeneralTableLayoutPanel";
//
// contentTableLayoutPanel
//
resources.ApplyResources(this.contentTableLayoutPanel, "contentTableLayoutPanel");
this.contentTableLayoutPanel.Controls.Add(this.panelPropertiesColumn, 1, 0);
this.contentTableLayoutPanel.Controls.Add(this.viewPanel, 0, 0);
this.contentTableLayoutPanel.Name = "contentTableLayoutPanel";
//
// panelPropertiesColumn
//
this.panelPropertiesColumn.Controls.Add(this.panelVMPP);
this.panelPropertiesColumn.Controls.Add(this.propertiesGroupBox);
resources.ApplyResources(this.panelPropertiesColumn, "panelPropertiesColumn");
this.panelPropertiesColumn.Name = "panelPropertiesColumn";
//
// panelVMPP
//
resources.ApplyResources(this.panelVMPP, "panelVMPP");
this.panelVMPP.Controls.Add(this.linkLabelVMPPInfo);
this.panelVMPP.Controls.Add(this.labelVMPPInfo);
this.panelVMPP.Controls.Add(this.pictureBoxVMPPInfo);
this.panelVMPP.Name = "panelVMPP";
//
// linkLabelVMPPInfo
//
resources.ApplyResources(this.linkLabelVMPPInfo, "linkLabelVMPPInfo");
this.linkLabelVMPPInfo.Name = "linkLabelVMPPInfo";
this.linkLabelVMPPInfo.TabStop = true;
this.linkLabelVMPPInfo.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelVMPPInfo_Click);
//
// labelVMPPInfo
//
resources.ApplyResources(this.labelVMPPInfo, "labelVMPPInfo");
this.labelVMPPInfo.AutoEllipsis = true;
this.labelVMPPInfo.Name = "labelVMPPInfo";
//
// pictureBoxVMPPInfo
//
this.pictureBoxVMPPInfo.Image = global::XenAdmin.Properties.Resources._000_Alert2_h32bit_16;
resources.ApplyResources(this.pictureBoxVMPPInfo, "pictureBoxVMPPInfo");
this.pictureBoxVMPPInfo.Name = "pictureBoxVMPPInfo";
this.pictureBoxVMPPInfo.TabStop = false;
//
// propertiesGroupBox
//
resources.ApplyResources(this.propertiesGroupBox, "propertiesGroupBox");
this.propertiesGroupBox.Controls.Add(this.propertiesTableLayoutPanel);
this.propertiesGroupBox.Name = "propertiesGroupBox";
this.propertiesGroupBox.TabStop = false;
//
// propertiesTableLayoutPanel
//
resources.ApplyResources(this.propertiesTableLayoutPanel, "propertiesTableLayoutPanel");
this.propertiesTableLayoutPanel.Controls.Add(this.tableLayoutPanelSimpleSelection, 0, 2);
this.propertiesTableLayoutPanel.Controls.Add(this.propertiesButton, 0, 3);
this.propertiesTableLayoutPanel.Controls.Add(this.nameLabel, 0, 1);
this.propertiesTableLayoutPanel.Controls.Add(this.shadowPanel1, 0, 0);
this.propertiesTableLayoutPanel.Name = "propertiesTableLayoutPanel";
//
// tableLayoutPanelSimpleSelection
//
resources.ApplyResources(this.tableLayoutPanelSimpleSelection, "tableLayoutPanelSimpleSelection");
this.tableLayoutPanelSimpleSelection.Controls.Add(this.folderLabel, 1, 4);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.sizeLabel, 1, 2);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.tagsLabel, 1, 3);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.descriptionLabel, 1, 0);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.sizeTitleLabel, 0, 2);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.folderTitleLabel, 0, 4);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.tagsTitleLabel, 0, 3);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.customFieldTitle1, 0, 5);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.customFieldContent1, 1, 5);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.customFieldTitle2, 0, 6);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.customFieldContent2, 1, 6);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.labelModeTitle, 0, 1);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.labelMode, 1, 1);
this.tableLayoutPanelSimpleSelection.Name = "tableLayoutPanelSimpleSelection";
//
// folderLabel
//
this.folderLabel.AutoEllipsis = true;
resources.ApplyResources(this.folderLabel, "folderLabel");
this.folderLabel.Name = "folderLabel";
this.folderLabel.UseMnemonic = false;
//
// sizeLabel
//
resources.ApplyResources(this.sizeLabel, "sizeLabel");
this.sizeLabel.Name = "sizeLabel";
this.sizeLabel.UseMnemonic = false;
//
// tagsLabel
//
this.tagsLabel.AutoEllipsis = true;
resources.ApplyResources(this.tagsLabel, "tagsLabel");
this.tagsLabel.Name = "tagsLabel";
this.tagsLabel.UseMnemonic = false;
//
// descriptionLabel
//
this.descriptionLabel.AutoEllipsis = true;
resources.ApplyResources(this.descriptionLabel, "descriptionLabel");
this.descriptionLabel.Name = "descriptionLabel";
this.descriptionLabel.UseMnemonic = false;
//
// label1
//
this.label1.AutoEllipsis = true;
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
this.label1.UseMnemonic = false;
//
// sizeTitleLabel
//
resources.ApplyResources(this.sizeTitleLabel, "sizeTitleLabel");
this.sizeTitleLabel.Name = "sizeTitleLabel";
this.sizeTitleLabel.UseMnemonic = false;
//
// folderTitleLabel
//
resources.ApplyResources(this.folderTitleLabel, "folderTitleLabel");
this.folderTitleLabel.Name = "folderTitleLabel";
this.folderTitleLabel.UseMnemonic = false;
//
// tagsTitleLabel
//
resources.ApplyResources(this.tagsTitleLabel, "tagsTitleLabel");
this.tagsTitleLabel.Name = "tagsTitleLabel";
this.tagsTitleLabel.UseMnemonic = false;
//
// customFieldTitle1
//
this.customFieldTitle1.AutoEllipsis = true;
resources.ApplyResources(this.customFieldTitle1, "customFieldTitle1");
this.customFieldTitle1.Name = "customFieldTitle1";
this.customFieldTitle1.UseMnemonic = false;
//
// customFieldContent1
//
this.customFieldContent1.AutoEllipsis = true;
resources.ApplyResources(this.customFieldContent1, "customFieldContent1");
this.customFieldContent1.Name = "customFieldContent1";
this.customFieldContent1.UseMnemonic = false;
//
// customFieldTitle2
//
this.customFieldTitle2.AutoEllipsis = true;
resources.ApplyResources(this.customFieldTitle2, "customFieldTitle2");
this.customFieldTitle2.Name = "customFieldTitle2";
this.customFieldTitle2.UseMnemonic = false;
//
// customFieldContent2
//
this.customFieldContent2.AutoEllipsis = true;
resources.ApplyResources(this.customFieldContent2, "customFieldContent2");
this.customFieldContent2.Name = "customFieldContent2";
this.customFieldContent2.UseMnemonic = false;
//
// labelModeTitle
//
resources.ApplyResources(this.labelModeTitle, "labelModeTitle");
this.labelModeTitle.Name = "labelModeTitle";
this.labelModeTitle.UseMnemonic = false;
//
// labelMode
//
resources.ApplyResources(this.labelMode, "labelMode");
this.labelMode.Name = "labelMode";
//
// propertiesButton
//
resources.ApplyResources(this.propertiesButton, "propertiesButton");
this.propertiesButton.Name = "propertiesButton";
this.propertiesButton.UseVisualStyleBackColor = true;
this.propertiesButton.Click += new System.EventHandler(this.propertiesButton_Click);
//
// nameLabel
//
this.nameLabel.AutoEllipsis = true;
resources.ApplyResources(this.nameLabel, "nameLabel");
this.nameLabel.Name = "nameLabel";
this.nameLabel.UseMnemonic = false;
//
// shadowPanel1
//
resources.ApplyResources(this.shadowPanel1, "shadowPanel1");
this.shadowPanel1.BorderColor = System.Drawing.Color.Empty;
this.shadowPanel1.Controls.Add(this.screenshotPictureBox);
this.shadowPanel1.Name = "shadowPanel1";
this.shadowPanel1.PanelColor = System.Drawing.Color.Empty;
//
// screenshotPictureBox
//
this.screenshotPictureBox.Cursor = System.Windows.Forms.Cursors.Hand;
resources.ApplyResources(this.screenshotPictureBox, "screenshotPictureBox");
this.screenshotPictureBox.Name = "screenshotPictureBox";
this.screenshotPictureBox.TabStop = false;
this.screenshotPictureBox.Click += new System.EventHandler(this.screenshotPictureBox_Click);
//
// viewPanel
//
this.viewPanel.Controls.Add(this.snapshotTreeView);
resources.ApplyResources(this.viewPanel, "viewPanel");
this.viewPanel.Name = "viewPanel";
//
// snapshotTreeView
//
resources.ApplyResources(this.snapshotTreeView, "snapshotTreeView");
this.snapshotTreeView.AllowDrop = true;
this.snapshotTreeView.AutoArrange = false;
this.snapshotTreeView.BackgroundImageTiled = true;
this.snapshotTreeView.GridLines = true;
this.snapshotTreeView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.snapshotTreeView.HGap = 42;
this.snapshotTreeView.HideSelection = false;
this.snapshotTreeView.LinkLineColor = System.Drawing.SystemColors.ActiveBorder;
this.snapshotTreeView.Name = "snapshotTreeView";
this.snapshotTreeView.OwnerDraw = true;
this.snapshotTreeView.ShowGroups = false;
this.snapshotTreeView.ShowItemToolTips = true;
this.snapshotTreeView.TileSize = new System.Drawing.Size(80, 60);
this.snapshotTreeView.UseCompatibleStateImageBehavior = false;
this.snapshotTreeView.VGap = 50;
this.snapshotTreeView.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.snapshotTreeView_ItemDrag);
this.snapshotTreeView.SelectedIndexChanged += new System.EventHandler(this.view_SelectionChanged);
this.snapshotTreeView.DragDrop += new System.Windows.Forms.DragEventHandler(this.snapshotTreeView_DragDrop);
this.snapshotTreeView.DragEnter += new System.Windows.Forms.DragEventHandler(this.snapshotTreeView_DragEnter);
this.snapshotTreeView.DragOver += new System.Windows.Forms.DragEventHandler(this.snapshotTreeView_DragOver);
this.snapshotTreeView.Enter += new System.EventHandler(this.snapshotTreeView_Enter);
this.snapshotTreeView.Leave += new System.EventHandler(this.snapshotTreeView_Leave);
this.snapshotTreeView.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.snapshotTreeView1_MouseDoubleClick);
this.snapshotTreeView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.snapshotTreeView_MouseClick);
this.snapshotTreeView.MouseMove += new System.Windows.Forms.MouseEventHandler(this.snapshotTreeView_MouseMove);
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.newSnapshotButton, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.toolTipContainerRevertButton, 1, 0);
this.tableLayoutPanel2.Controls.Add(this.buttonView, 4, 0);
this.tableLayoutPanel2.Controls.Add(this.saveButton, 2, 0);
this.tableLayoutPanel2.Controls.Add(this.deleteButton, 3, 0);
this.tableLayoutPanel2.Controls.Add(this.chevronButton1, 6, 0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// newSnapshotButton
//
resources.ApplyResources(this.newSnapshotButton, "newSnapshotButton");
this.newSnapshotButton.Name = "newSnapshotButton";
this.newSnapshotButton.UseVisualStyleBackColor = true;
this.newSnapshotButton.Click += new System.EventHandler(this.takeSnapshotToolStripButton_Click);
//
// toolTipContainerRevertButton
//
this.toolTipContainerRevertButton.Controls.Add(this.revertButton);
resources.ApplyResources(this.toolTipContainerRevertButton, "toolTipContainerRevertButton");
this.toolTipContainerRevertButton.Name = "toolTipContainerRevertButton";
this.toolTipContainerRevertButton.TabStop = true;
//
// revertButton
//
resources.ApplyResources(this.revertButton, "revertButton");
this.revertButton.Name = "revertButton";
this.revertButton.UseVisualStyleBackColor = true;
this.revertButton.Click += new System.EventHandler(this.revertButton_Click);
//
// buttonView
//
this.buttonView.Image = global::XenAdmin.Properties.Resources.expanded_triangle;
resources.ApplyResources(this.buttonView, "buttonView");
this.buttonView.Name = "buttonView";
this.buttonView.UseVisualStyleBackColor = true;
this.buttonView.Click += new System.EventHandler(this.button1_Click);
//
// saveButton
//
this.saveButton.Image = global::XenAdmin.Properties.Resources.expanded_triangle;
resources.ApplyResources(this.saveButton, "saveButton");
this.saveButton.Name = "saveButton";
this.saveButton.UseVisualStyleBackColor = true;
this.saveButton.Click += new System.EventHandler(this.saveButton_Click);
//
// deleteButton
//
resources.ApplyResources(this.deleteButton, "deleteButton");
this.deleteButton.Name = "deleteButton";
this.deleteButton.UseVisualStyleBackColor = true;
this.deleteButton.Click += new System.EventHandler(this.deleteButton_Click);
//
// chevronButton1
//
resources.ApplyResources(this.chevronButton1, "chevronButton1");
this.chevronButton1.Cursor = System.Windows.Forms.Cursors.Default;
this.chevronButton1.Image = ((System.Drawing.Image)(resources.GetObject("chevronButton1.Image")));
this.chevronButton1.Name = "chevronButton1";
this.chevronButton1.ButtonClick += new System.EventHandler(this.chevronButton1_ButtonClick);
this.chevronButton1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.chevronButton1_KeyDown);
//
// contextMenuStrip
//
this.contextMenuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.TakeSnapshotToolStripMenuItem,
this.revertToolStripMenuItem,
this.saveVMToolStripSeparator,
this.saveVMToolStripMenuItem,
this.saveTemplateToolStripMenuItem,
this.exportToolStripMenuItem,
this.separatorDeleteToolStripSeparator,
this.viewToolStripMenuItem,
this.sortByToolStripMenuItem,
this.sortToolStripSeparator,
this.deleteToolStripMenuItem,
this.propertiesToolStripMenuItem});
this.contextMenuStrip.Name = "contextMenuStrip1";
resources.ApplyResources(this.contextMenuStrip, "contextMenuStrip");
this.contextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip_Opening);
//
// TakeSnapshotToolStripMenuItem
//
this.TakeSnapshotToolStripMenuItem.Name = "TakeSnapshotToolStripMenuItem";
resources.ApplyResources(this.TakeSnapshotToolStripMenuItem, "TakeSnapshotToolStripMenuItem");
this.TakeSnapshotToolStripMenuItem.Click += new System.EventHandler(this.takeSnapshotToolStripButton_Click);
//
// revertToolStripMenuItem
//
this.revertToolStripMenuItem.Name = "revertToolStripMenuItem";
resources.ApplyResources(this.revertToolStripMenuItem, "revertToolStripMenuItem");
this.revertToolStripMenuItem.Click += new System.EventHandler(this.restoreToolStripButton_Click);
//
// saveVMToolStripSeparator
//
this.saveVMToolStripSeparator.Name = "saveVMToolStripSeparator";
resources.ApplyResources(this.saveVMToolStripSeparator, "saveVMToolStripSeparator");
//
// saveVMToolStripMenuItem
//
this.saveVMToolStripMenuItem.Name = "saveVMToolStripMenuItem";
resources.ApplyResources(this.saveVMToolStripMenuItem, "saveVMToolStripMenuItem");
this.saveVMToolStripMenuItem.Click += new System.EventHandler(this.saveAsAVirtualMachineToolStripMenuItem_Click);
//
// saveTemplateToolStripMenuItem
//
this.saveTemplateToolStripMenuItem.Name = "saveTemplateToolStripMenuItem";
resources.ApplyResources(this.saveTemplateToolStripMenuItem, "saveTemplateToolStripMenuItem");
this.saveTemplateToolStripMenuItem.Click += new System.EventHandler(this.saveAsATemplateToolStripMenuItem_Click);
//
// exportToolStripMenuItem
//
this.exportToolStripMenuItem.Name = "exportToolStripMenuItem";
resources.ApplyResources(this.exportToolStripMenuItem, "exportToolStripMenuItem");
this.exportToolStripMenuItem.Click += new System.EventHandler(this.exportSnapshotToolStripMenuItem_Click);
//
// separatorDeleteToolStripSeparator
//
this.separatorDeleteToolStripSeparator.Name = "separatorDeleteToolStripSeparator";
resources.ApplyResources(this.separatorDeleteToolStripSeparator, "separatorDeleteToolStripSeparator");
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
resources.ApplyResources(this.viewToolStripMenuItem, "viewToolStripMenuItem");
//
// sortByToolStripMenuItem
//
this.sortByToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.sortByNameToolStripMenuItem,
this.sortByCreatedOnToolStripMenuItem,
this.sortBySizeToolStripMenuItem,
this.sortByTypeToolStripMenuItem});
this.sortByToolStripMenuItem.Name = "sortByToolStripMenuItem";
resources.ApplyResources(this.sortByToolStripMenuItem, "sortByToolStripMenuItem");
//
// sortByNameToolStripMenuItem
//
this.sortByNameToolStripMenuItem.Name = "sortByNameToolStripMenuItem";
resources.ApplyResources(this.sortByNameToolStripMenuItem, "sortByNameToolStripMenuItem");
this.sortByNameToolStripMenuItem.Click += new System.EventHandler(this.sortByToolStripMenuItem_Click);
//
// sortByCreatedOnToolStripMenuItem
//
this.sortByCreatedOnToolStripMenuItem.Name = "sortByCreatedOnToolStripMenuItem";
resources.ApplyResources(this.sortByCreatedOnToolStripMenuItem, "sortByCreatedOnToolStripMenuItem");
this.sortByCreatedOnToolStripMenuItem.Click += new System.EventHandler(this.sortByToolStripMenuItem_Click);
//
// sortBySizeToolStripMenuItem
//
this.sortBySizeToolStripMenuItem.Name = "sortBySizeToolStripMenuItem";
resources.ApplyResources(this.sortBySizeToolStripMenuItem, "sortBySizeToolStripMenuItem");
this.sortBySizeToolStripMenuItem.Click += new System.EventHandler(this.sortByToolStripMenuItem_Click);
//
// sortByTypeToolStripMenuItem
//
this.sortByTypeToolStripMenuItem.Name = "sortByTypeToolStripMenuItem";
resources.ApplyResources(this.sortByTypeToolStripMenuItem, "sortByTypeToolStripMenuItem");
this.sortByTypeToolStripMenuItem.Click += new System.EventHandler(this.sortByToolStripMenuItem_Click);
//
// sortToolStripSeparator
//
this.sortToolStripSeparator.Name = "sortToolStripSeparator";
resources.ApplyResources(this.sortToolStripSeparator, "sortToolStripSeparator");
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem");
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripButton_Click);
//
// propertiesToolStripMenuItem
//
this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem";
resources.ApplyResources(this.propertiesToolStripMenuItem, "propertiesToolStripMenuItem");
this.propertiesToolStripMenuItem.Click += new System.EventHandler(this.propertiesButton_Click);
//
// dataGridView
//
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.AllowUserToOrderColumns = true;
this.dataGridView.AllowUserToResizeRows = false;
this.dataGridView.BackgroundColor = System.Drawing.Color.White;
this.dataGridView.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.ControlDarkDark;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridView.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Live,
this.Snapshot,
this.Date,
this.size,
this.tags,
this.description});
resources.ApplyResources(this.dataGridView, "dataGridView");
this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true;
this.dataGridView.RowHeadersVisible = false;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.SelectionChanged += new System.EventHandler(this.view_SelectionChanged);
this.dataGridView.MouseClick += new System.Windows.Forms.MouseEventHandler(this.dataGridView_MouseClick);
//
// Live
//
this.Live.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
resources.ApplyResources(this.Live, "Live");
this.Live.Name = "Live";
this.Live.ReadOnly = true;
this.Live.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// Snapshot
//
this.Snapshot.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
resources.ApplyResources(this.Snapshot, "Snapshot");
this.Snapshot.Name = "Snapshot";
this.Snapshot.ReadOnly = true;
this.Snapshot.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// Date
//
this.Date.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
resources.ApplyResources(this.Date, "Date");
this.Date.Name = "Date";
this.Date.ReadOnly = true;
this.Date.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// size
//
this.size.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
this.size.DefaultCellStyle = dataGridViewCellStyle2;
resources.ApplyResources(this.size, "size");
this.size.Name = "size";
this.size.ReadOnly = true;
//
// tags
//
this.tags.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
resources.ApplyResources(this.tags, "tags");
this.tags.Name = "tags";
this.tags.ReadOnly = true;
this.tags.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// description
//
this.description.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.description, "description");
this.description.Name = "description";
this.description.ReadOnly = true;
this.description.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// dateLabel
//
resources.ApplyResources(this.dateLabel, "dateLabel");
this.dateLabel.Name = "dateLabel";
//
// tableLayoutPanelMultipleSelection
//
resources.ApplyResources(this.tableLayoutPanelMultipleSelection, "tableLayoutPanelMultipleSelection");
this.tableLayoutPanelMultipleSelection.Controls.Add(this.multipleSelectionTags, 1, 1);
this.tableLayoutPanelMultipleSelection.Controls.Add(this.multipleSelectionTotalSize, 1, 0);
this.tableLayoutPanelMultipleSelection.Controls.Add(this.label6, 0, 0);
this.tableLayoutPanelMultipleSelection.Controls.Add(this.label7, 0, 1);
this.tableLayoutPanelMultipleSelection.Name = "tableLayoutPanelMultipleSelection";
//
// multipleSelectionTags
//
resources.ApplyResources(this.multipleSelectionTags, "multipleSelectionTags");
this.multipleSelectionTags.Name = "multipleSelectionTags";
//
// multipleSelectionTotalSize
//
resources.ApplyResources(this.multipleSelectionTotalSize, "multipleSelectionTotalSize");
this.multipleSelectionTotalSize.Name = "multipleSelectionTotalSize";
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.Name = "label7";
//
// saveMenuStrip
//
this.saveMenuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.saveMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveAsVMToolStripMenuItem,
this.toolStripSeparator2,
this.saveAsTemplateToolStripMenuItem,
this.exportAsBackupToolStripMenuItem});
this.saveMenuStrip.Name = "saveMenuStrip";
resources.ApplyResources(this.saveMenuStrip, "saveMenuStrip");
//
// saveAsVMToolStripMenuItem
//
this.saveAsVMToolStripMenuItem.Name = "saveAsVMToolStripMenuItem";
resources.ApplyResources(this.saveAsVMToolStripMenuItem, "saveAsVMToolStripMenuItem");
this.saveAsVMToolStripMenuItem.Click += new System.EventHandler(this.toolStripMenuItem1_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// saveAsTemplateToolStripMenuItem
//
this.saveAsTemplateToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.saveAsTemplateToolStripMenuItem.Name = "saveAsTemplateToolStripMenuItem";
resources.ApplyResources(this.saveAsTemplateToolStripMenuItem, "saveAsTemplateToolStripMenuItem");
this.saveAsTemplateToolStripMenuItem.Click += new System.EventHandler(this.saveAsTemplateToolStripMenuItem_Click);
//
// exportAsBackupToolStripMenuItem
//
this.exportAsBackupToolStripMenuItem.Name = "exportAsBackupToolStripMenuItem";
resources.ApplyResources(this.exportAsBackupToolStripMenuItem, "exportAsBackupToolStripMenuItem");
this.exportAsBackupToolStripMenuItem.Click += new System.EventHandler(this.exportAsBackupToolStripMenuItem_Click);
//
// contextMenuStripView
//
this.contextMenuStripView.ImageScalingSize = new System.Drawing.Size(20, 20);
this.contextMenuStripView.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButtonListView,
this.toolStripButtonTreeView,
this.toolStripSeparatorView,
this.toolStripMenuItemScheduledSnapshots});
this.contextMenuStripView.Name = "contextMenuStripView";
resources.ApplyResources(this.contextMenuStripView, "contextMenuStripView");
//
// toolStripButtonListView
//
this.toolStripButtonListView.Image = global::XenAdmin.Properties.Resources._000_ViewModeList_h32bit_16;
this.toolStripButtonListView.Name = "toolStripButtonListView";
resources.ApplyResources(this.toolStripButtonListView, "toolStripButtonListView");
this.toolStripButtonListView.Click += new System.EventHandler(this.gridToolStripMenuItem_Click);
//
// toolStripButtonTreeView
//
this.toolStripButtonTreeView.Image = global::XenAdmin.Properties.Resources._000_ViewModeTree_h32bit_16;
this.toolStripButtonTreeView.Name = "toolStripButtonTreeView";
resources.ApplyResources(this.toolStripButtonTreeView, "toolStripButtonTreeView");
this.toolStripButtonTreeView.Click += new System.EventHandler(this.treeToolStripMenuItem_Click);
//
// toolStripSeparatorView
//
this.toolStripSeparatorView.Name = "toolStripSeparatorView";
resources.ApplyResources(this.toolStripSeparatorView, "toolStripSeparatorView");
//
// toolStripMenuItemScheduledSnapshots
//
this.toolStripMenuItemScheduledSnapshots.Name = "toolStripMenuItemScheduledSnapshots";
resources.ApplyResources(this.toolStripMenuItemScheduledSnapshots, "toolStripMenuItemScheduledSnapshots");
this.toolStripMenuItemScheduledSnapshots.Click += new System.EventHandler(this.toolStripMenuItemScheduledSnapshots_Click);
//
// SnapshotsPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.DoubleBuffered = true;
this.Name = "SnapshotsPage";
this.Controls.SetChildIndex(this.pageContainerPanel, 0);
this.pageContainerPanel.ResumeLayout(false);
this.pageContainerPanel.PerformLayout();
this.GeneralTableLayoutPanel.ResumeLayout(false);
this.GeneralTableLayoutPanel.PerformLayout();
this.contentTableLayoutPanel.ResumeLayout(false);
this.panelPropertiesColumn.ResumeLayout(false);
this.panelPropertiesColumn.PerformLayout();
this.panelVMPP.ResumeLayout(false);
this.panelVMPP.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxVMPPInfo)).EndInit();
this.propertiesGroupBox.ResumeLayout(false);
this.propertiesGroupBox.PerformLayout();
this.propertiesTableLayoutPanel.ResumeLayout(false);
this.propertiesTableLayoutPanel.PerformLayout();
this.tableLayoutPanelSimpleSelection.ResumeLayout(false);
this.tableLayoutPanelSimpleSelection.PerformLayout();
this.shadowPanel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.screenshotPictureBox)).EndInit();
this.viewPanel.ResumeLayout(false);
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.toolTipContainerRevertButton.ResumeLayout(false);
this.contextMenuStrip.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.tableLayoutPanelMultipleSelection.ResumeLayout(false);
this.saveMenuStrip.ResumeLayout(false);
this.contextMenuStripView.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DataGridView dataGridView;
private System.Windows.Forms.TableLayoutPanel GeneralTableLayoutPanel;
private SnapshotTreeView snapshotTreeView;
private Panel viewPanel;
private GroupBox propertiesGroupBox;
private TableLayoutPanel propertiesTableLayoutPanel;
private Label folderTitleLabel;
private Label tagsTitleLabel;
private Label sizeTitleLabel;
private Label dateLabel;
private Label descriptionLabel;
private Label nameLabel;
private Label sizeLabel;
private Button propertiesButton;
private Label folderLabel;
private ContextMenuStrip contextMenuStrip;
private ToolStripMenuItem deleteToolStripMenuItem;
private ToolStripMenuItem revertToolStripMenuItem;
private ToolStripMenuItem TakeSnapshotToolStripMenuItem;
private ToolStripMenuItem exportToolStripMenuItem;
private ToolStripSeparator separatorDeleteToolStripSeparator;
private ToolStripMenuItem propertiesToolStripMenuItem;
private ToolStripSeparator saveVMToolStripSeparator;
private ToolStripMenuItem saveVMToolStripMenuItem;
private ToolStripMenuItem saveTemplateToolStripMenuItem;
private Label tagsLabel;
private ToolStripMenuItem viewToolStripMenuItem;
private ToolStripMenuItem sortByToolStripMenuItem;
private ToolStripSeparator sortToolStripSeparator;
private ToolStripMenuItem sortByNameToolStripMenuItem;
private ToolStripMenuItem sortByCreatedOnToolStripMenuItem;
private ToolStripMenuItem sortBySizeToolStripMenuItem;
private ToolStripMenuItem sortByTypeToolStripMenuItem;
private Label label1;
private PictureBox screenshotPictureBox;
private TableLayoutPanel tableLayoutPanelSimpleSelection;
private TableLayoutPanel tableLayoutPanelMultipleSelection;
private Label multipleSelectionTags;
private Label multipleSelectionTotalSize;
private Label label6;
private Label label7;
private ShadowPanel shadowPanel1;
private TableLayoutPanel contentTableLayoutPanel;
private NonReopeningContextMenuStrip saveMenuStrip;
private ToolStripMenuItem saveAsTemplateToolStripMenuItem;
private ToolStripMenuItem saveAsVMToolStripMenuItem;
private TableLayoutPanel tableLayoutPanel2;
private ToolStripMenuItem exportAsBackupToolStripMenuItem;
private Button newSnapshotButton;
private Button revertButton;
private Button saveButton;
private Button deleteButton;
private Label customFieldTitle1;
private Label customFieldContent1;
private Label customFieldTitle2;
private Label customFieldContent2;
private ToolTipContainer toolTipContainerRevertButton;
private Label labelModeTitle;
private Label labelMode;
private Panel panelPropertiesColumn;
private Panel panelVMPP;
private Label labelVMPPInfo;
private PictureBox pictureBoxVMPPInfo;
private LinkLabel linkLabelVMPPInfo;
private Button buttonView;
private NonReopeningContextMenuStrip contextMenuStripView;
private ToolStripMenuItem toolStripButtonListView;
private ToolStripMenuItem toolStripButtonTreeView;
private ToolStripSeparator toolStripSeparatorView;
private ToolStripMenuItem toolStripMenuItemScheduledSnapshots;
private ToolStripSeparator toolStripSeparator2;
private DataGridViewTextBoxColumn Live;
private DataGridViewTextBoxColumn Snapshot;
private DataGridViewTextBoxColumn Date;
private DataGridViewTextBoxColumn size;
private DataGridViewTextBoxColumn tags;
private DataGridViewTextBoxColumn description;
private ChevronButton chevronButton1;
}
internal class MySR : ToolStripSystemRenderer
{
public MySR() { }
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
{
//base.OnRenderToolStripBorder(e);
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Primitives;
using AspNet.Security.OpenIdConnect.Server;
using OpenIdConnectServer.ViewModels.Shared;
using OpenIdConnectServer.ViewModels.AuthorizationViewModels;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using OpenIddict.Core;
using OpenIddict.Models;
using OpenIdConnectServer.Models;
using OpenIdConnectServer.Helpers;
using AspNetCore.Identity.DynamoDB.OpenIddict;
using AspNetCore.Identity.DynamoDB.OpenIddict.Models;
using System.Threading;
using OpenIdConnectServer.Services;
using AspNetCore.Identity.DynamoDB.OpenIddict.Stores;
using OpenIddict.DeviceCodeFlow;
using System;
namespace OpenIdConnectServer.Controllers
{
public partial class AuthorizationController : Controller
{
private readonly OpenIddictApplicationManager<DynamoIdentityApplication> _applicationManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationAuthorizationManager<DynamoIdentityAuthorization> _authorizationManager;
private readonly DeviceCodeManager<DynamoIdentityDeviceCode> _deviceCodeManager;
private readonly DeviceCodeOptions _deviceCodeOptions;
public AuthorizationController(
OpenIddictApplicationManager<DynamoIdentityApplication> applicationManager,
SignInManager<ApplicationUser> signInManager,
UserManager<ApplicationUser> userManager,
OpenIddictAuthorizationManager<DynamoIdentityAuthorization> authorizationManager,
DeviceCodeManager<DynamoIdentityDeviceCode> deviceCodeManager,
DeviceCodeOptions deviceCodeOptions)
{
_applicationManager = applicationManager;
_signInManager = signInManager;
_userManager = userManager;
_authorizationManager = authorizationManager as ApplicationAuthorizationManager<DynamoIdentityAuthorization>;
_deviceCodeManager = deviceCodeManager;
_deviceCodeOptions = deviceCodeOptions;
}
[Authorize, HttpGet("~/connect/authorize")]
public async Task<IActionResult> Authorize(OpenIdConnectRequest request, CancellationToken cancellationToken)
{
Debug.Assert(request.IsAuthorizationRequest(),
"The OpenIddict binder for ASP.NET Core MVC is not registered. " +
"Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");
// Retrieve the application details from the database.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);
if (application == null)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = "Details concerning the calling client application cannot be found in the database"
});
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.ServerError,
ErrorDescription = "An internal error has occurred"
});
}
var authorization = await _authorizationManager.FindAsync(user.Id, application.Id, cancellationToken);
if (authorization != null)
{
// if we didn't ask for any scopes that aren't already authorized
if (false == request.GetScopes().Except(authorization.Scopes).Any())
{
var ticket = await CreateTicketAsync(request, user);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
}
// Flow the request_id to allow OpenIddict to restore
// the original authorization request from the cache.
return View(new AuthorizeViewModel
{
ApplicationName = application.DisplayName,
RequestId = request.RequestId,
Scope = request.Scope,
ClientId = request.ClientId,
ResponseType = request.ResponseType,
ResponseMode = request.ResponseMode,
RedirectUri = request.RedirectUri,
State = request.State,
Nonce = request.Nonce
});
}
[Authorize, FormValueRequired("submit.Accept")]
[HttpPost("~/connect/authorize"), ValidateAntiForgeryToken]
public async Task<IActionResult> Accept(OpenIdConnectRequest request, CancellationToken cancellationToken)
{
Debug.Assert(request.IsAuthorizationRequest(),
"The OpenIddict binder for ASP.NET Core MVC is not registered. " +
"Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");
var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);
if (application == null)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = "Details concerning the calling client application cannot be found in the database"
});
}
// Retrieve the profile of the logged in user.
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return View("Error", new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.ServerError,
ErrorDescription = "An internal error has occurred"
});
}
// Create a new authentication ticket.
var ticket = await CreateTicketAsync(request, user);
var authorization = await _authorizationManager.FindAsync(user.Id, application.Id, cancellationToken);
if (authorization != null)
{
if (false == request.GetScopes().Except(authorization.Scopes).Any())
{
authorization.Scopes = authorization.Scopes.Union(request.GetScopes()).ToList();
await _authorizationManager.UpdateAsync(authorization, cancellationToken);
}
}
else
{
authorization = new DynamoIdentityAuthorization()
{
Application = application.Id,
Subject = user.Id,
Scopes = ticket.GetScopes().ToList()
};
await _authorizationManager.CreateAsync(authorization, cancellationToken);
}
// Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
[Authorize, FormValueRequired("submit.Deny")]
[HttpPost("~/connect/authorize"), ValidateAntiForgeryToken]
public IActionResult Deny()
{
// Notify OpenIddict that the authorization grant has been denied by the resource owner
// to redirect the user agent to the client application using the appropriate response_mode.
return Forbid(OpenIdConnectServerDefaults.AuthenticationScheme);
}
[HttpGet("~/connect/logout")]
public IActionResult Logout(OpenIdConnectRequest request)
{
// Flow the request_id to allow OpenIddict to restore
// the original logout request from the distributed cache.
return View(new LogoutViewModel
{
RequestId = request.RequestId,
PostLogoutRedirectUri = request.PostLogoutRedirectUri,
IdTokenHint = request.IdTokenHint,
State = request.State
});
}
[HttpPost("~/connect/logout"), ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
// Ask ASP.NET Core Identity to delete the local and external cookies created
// when the user agent is redirected from the external identity provider
// after a successful authentication flow (e.g Google or Facebook).
await _signInManager.SignOutAsync();
// Returning a SignOutResult will ask OpenIddict to redirect the user agent
// to the post_logout_redirect_uri specified by the client application.
return SignOut(OpenIdConnectServerDefaults.AuthenticationScheme);
}
[HttpPost("~/connect/token"), Produces("application/json")]
public async Task<IActionResult> Exchange(string device_code, OpenIdConnectRequest request, CancellationToken cancellationToken)
{
Debug.Assert(request.IsTokenRequest(),
"The OpenIddict binder for ASP.NET Core MVC is not registered. " +
"Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");
if (request.IsDeviceCodeGrantType())
{
if (request.ClientId == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = "Missing required parameter client_id."
});
}
// exchange device code for tokens
var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);
if (application == null)
{
return BadRequest(new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = "Details concerning the calling client application cannot be found in the database"
});
}
var code = await _deviceCodeManager.FindByDeviceCodeAsync(device_code);
if (code == null)
{
return BadRequest(new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.AccessDenied,
ErrorDescription = "Access denied" // todo: use canonical descriptions message for these errors
});
}
if (code.AuthorizedOn == default(DateTimeOffset))
{
if (code.LastPolledAt == default(DateTimeOffset))
{
code.LastPolledAt = DateTimeOffset.Now;
await _deviceCodeManager.UpdateLastPolledAt(code);
}
else
{
var interval = DateTimeOffset.Now - code.LastPolledAt;
if (interval.TotalMilliseconds < _deviceCodeOptions.Interval * 950)
{
return BadRequest(new ErrorViewModel
{
Error = DeviceCodeFlowConstants.Errors.SlowDown,
ErrorDescription = "Slow down"
});
}
else
{
code.LastPolledAt = DateTimeOffset.Now;
await _deviceCodeManager.UpdateLastPolledAt(code);
}
}
return BadRequest(new ErrorViewModel
{
Error = DeviceCodeFlowConstants.Errors.DeviceCodeAuthorizationPending,
ErrorDescription = "Device code authorization pending"
});
}
var user = await _userManager.FindByIdAsync(code.Subject);
if (user == null)
{
return BadRequest(new ErrorViewModel
{
Error = OpenIdConnectConstants.Errors.ServerError,
ErrorDescription = "An internal error has occurred"
});
}
await _deviceCodeManager.Consume(code);
// Ensure the user is still allowed to sign in.
if (!await _signInManager.CanSignInAsync(user))
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The user is no longer allowed to sign in."
});
}
var ticket = await CreateTicketAsync(new OpenIdConnectRequest
{
Scope = string.Join(" ", code.Scopes),
ClientId = request.ClientId,
ClientSecret = request.ClientSecret,
GrantType = request.GrantType
}, user);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
else if (request.IsPasswordGrantType())
{
// not implemented
}
else if (request.IsAuthorizationCodeGrantType())
{
// Retrieve the claims principal stored in the authorization code.
var info = await HttpContext.Authentication.GetAuthenticateInfoAsync(
OpenIdConnectServerDefaults.AuthenticationScheme);
// Retrieve the user profile corresponding to the authorization code.
var user = await _userManager.GetUserAsync(info.Principal);
if (user == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The authorization code is no longer valid."
});
}
// Ensure the user is still allowed to sign in.
if (!await _signInManager.CanSignInAsync(user))
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The user is no longer allowed to sign in."
});
}
// Create a new authentication ticket, but reuse the properties stored
// in the authorization code, including the scopes originally granted.
var ticket = await CreateTicketAsync(request, user, info.Properties);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
ErrorDescription = "The specified grant type is not supported."
});
}
private async Task<AuthenticationTicket> CreateTicketAsync(
OpenIdConnectRequest request, ApplicationUser user,
AuthenticationProperties properties = null)
{
// Create a new ClaimsPrincipal containing the claims that
// will be used to create an id_token, a token or a code.
var principal = await _signInManager.CreateUserPrincipalAsync(user);
// Note: by default, claims are NOT automatically included in the access and identity tokens.
// To allow OpenIddict to serialize them, you must attach them a destination, that specifies
// whether they should be included in access tokens, in identity tokens or in both.
foreach (var claim in principal.Claims)
{
// In this sample, every claim is serialized in both the access and the identity tokens.
// In a real world application, you'd probably want to exclude confidential claims
// or apply a claims policy based on the scopes requested by the client application.
claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
OpenIdConnectConstants.Destinations.IdentityToken);
}
// Create a new authentication ticket holding the user identity.
var ticket = new AuthenticationTicket(principal, properties,
OpenIdConnectServerDefaults.AuthenticationScheme);
if (!request.IsAuthorizationCodeGrantType() && !request.IsRefreshTokenGrantType())
{
// Set the list of scopes granted to the client application.
// Note: the offline_access scope must be granted
// to allow OpenIddict to return a refresh token.
ticket.SetScopes(new[]
{
OpenIdConnectConstants.Scopes.OpenId,
OpenIdConnectConstants.Scopes.Email,
OpenIdConnectConstants.Scopes.Profile,
OpenIddictConstants.Scopes.Roles
}.Intersect(request.GetScopes()));
}
ticket.SetResources("resource_server");
return ticket;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Shell.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCloudShellServiceClientTest
{
[xunit::FactAttribute]
public void GetEnvironmentRequestObject()
{
moq::Mock<CloudShellService.CloudShellServiceClient> mockGrpcClient = new moq::Mock<CloudShellService.CloudShellServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
Id = "id74b70bb8",
DockerImage = "docker_image790036d7",
State = Environment.Types.State.Running,
SshUsername = "ssh_usernamef089694d",
SshHost = "ssh_hostf6f9047e",
SshPort = 385289463,
PublicKeys =
{
"public_keys8ff48db4",
},
WebHost = "web_hosta5049b32",
};
mockGrpcClient.Setup(x => x.GetEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudShellServiceClient client = new CloudShellServiceClientImpl(mockGrpcClient.Object, null);
Environment response = client.GetEnvironment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEnvironmentRequestObjectAsync()
{
moq::Mock<CloudShellService.CloudShellServiceClient> mockGrpcClient = new moq::Mock<CloudShellService.CloudShellServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
Id = "id74b70bb8",
DockerImage = "docker_image790036d7",
State = Environment.Types.State.Running,
SshUsername = "ssh_usernamef089694d",
SshHost = "ssh_hostf6f9047e",
SshPort = 385289463,
PublicKeys =
{
"public_keys8ff48db4",
},
WebHost = "web_hosta5049b32",
};
mockGrpcClient.Setup(x => x.GetEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Environment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudShellServiceClient client = new CloudShellServiceClientImpl(mockGrpcClient.Object, null);
Environment responseCallSettings = await client.GetEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Environment responseCancellationToken = await client.GetEnvironmentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEnvironment()
{
moq::Mock<CloudShellService.CloudShellServiceClient> mockGrpcClient = new moq::Mock<CloudShellService.CloudShellServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
Id = "id74b70bb8",
DockerImage = "docker_image790036d7",
State = Environment.Types.State.Running,
SshUsername = "ssh_usernamef089694d",
SshHost = "ssh_hostf6f9047e",
SshPort = 385289463,
PublicKeys =
{
"public_keys8ff48db4",
},
WebHost = "web_hosta5049b32",
};
mockGrpcClient.Setup(x => x.GetEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudShellServiceClient client = new CloudShellServiceClientImpl(mockGrpcClient.Object, null);
Environment response = client.GetEnvironment(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEnvironmentAsync()
{
moq::Mock<CloudShellService.CloudShellServiceClient> mockGrpcClient = new moq::Mock<CloudShellService.CloudShellServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
Id = "id74b70bb8",
DockerImage = "docker_image790036d7",
State = Environment.Types.State.Running,
SshUsername = "ssh_usernamef089694d",
SshHost = "ssh_hostf6f9047e",
SshPort = 385289463,
PublicKeys =
{
"public_keys8ff48db4",
},
WebHost = "web_hosta5049b32",
};
mockGrpcClient.Setup(x => x.GetEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Environment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudShellServiceClient client = new CloudShellServiceClientImpl(mockGrpcClient.Object, null);
Environment responseCallSettings = await client.GetEnvironmentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Environment responseCancellationToken = await client.GetEnvironmentAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEnvironmentResourceNames()
{
moq::Mock<CloudShellService.CloudShellServiceClient> mockGrpcClient = new moq::Mock<CloudShellService.CloudShellServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
Id = "id74b70bb8",
DockerImage = "docker_image790036d7",
State = Environment.Types.State.Running,
SshUsername = "ssh_usernamef089694d",
SshHost = "ssh_hostf6f9047e",
SshPort = 385289463,
PublicKeys =
{
"public_keys8ff48db4",
},
WebHost = "web_hosta5049b32",
};
mockGrpcClient.Setup(x => x.GetEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudShellServiceClient client = new CloudShellServiceClientImpl(mockGrpcClient.Object, null);
Environment response = client.GetEnvironment(request.EnvironmentName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEnvironmentResourceNamesAsync()
{
moq::Mock<CloudShellService.CloudShellServiceClient> mockGrpcClient = new moq::Mock<CloudShellService.CloudShellServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"),
Id = "id74b70bb8",
DockerImage = "docker_image790036d7",
State = Environment.Types.State.Running,
SshUsername = "ssh_usernamef089694d",
SshHost = "ssh_hostf6f9047e",
SshPort = 385289463,
PublicKeys =
{
"public_keys8ff48db4",
},
WebHost = "web_hosta5049b32",
};
mockGrpcClient.Setup(x => x.GetEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Environment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudShellServiceClient client = new CloudShellServiceClientImpl(mockGrpcClient.Object, null);
Environment responseCallSettings = await client.GetEnvironmentAsync(request.EnvironmentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Environment responseCancellationToken = await client.GetEnvironmentAsync(request.EnvironmentName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using TriangleNet;
using TriangleNet.Data;
using TriangleNet.Geometry;
namespace TriangleNet.Tools
{
public class Voronoi : IVoronoi
{
private Mesh mesh;
private Point[] points;
private List<VoronoiRegion> regions;
private Dictionary<int, Point> rayPoints;
private int rayIndex;
private BoundingBox bounds;
public Point[] Points
{
get
{
return this.points;
}
}
public List<VoronoiRegion> Regions
{
get
{
return this.regions;
}
}
public Voronoi(Mesh mesh)
{
this.mesh = mesh;
this.Generate();
}
private bool BoxRayIntersection(Point pt, double dx, double dy, out Vertex intersect)
{
double num;
double num1;
double num2;
double num3;
double num4;
double num5;
double x = pt.X;
double y = pt.Y;
double xmin = this.bounds.Xmin;
double xmax = this.bounds.Xmax;
double ymin = this.bounds.Ymin;
double ymax = this.bounds.Ymax;
if (x < xmin || x > xmax || y < ymin || y > ymax)
{
intersect = null;
return false;
}
if (dx < 0)
{
num = (xmin - x) / dx;
num1 = xmin;
num2 = y + num * dy;
}
else if (dx <= 0)
{
num = double.MaxValue;
double num6 = 0;
num2 = num6;
num1 = num6;
}
else
{
num = (xmax - x) / dx;
num1 = xmax;
num2 = y + num * dy;
}
if (dy < 0)
{
num3 = (ymin - y) / dy;
num4 = x + num3 * dx;
num5 = ymin;
}
else if (dx <= 0)
{
num3 = double.MaxValue;
double num7 = 0;
num5 = num7;
num4 = num7;
}
else
{
num3 = (ymax - y) / dy;
num4 = x + num3 * dx;
num5 = ymax;
}
if (num >= num3)
{
intersect = new Vertex(num4, num5, -1);
}
else
{
intersect = new Vertex(num1, num2, -1);
}
return true;
}
private void ComputeCircumCenters()
{
Otri otri = new Otri();
double num = 0;
double num1 = 0;
foreach (Triangle value in this.mesh.triangles.Values)
{
otri.triangle = value;
Point point = Primitives.FindCircumcenter(otri.Org(), otri.Dest(), otri.Apex(), ref num, ref num1);
point.id = value.id;
this.points[value.id] = point;
this.bounds.Update(point.x, point.y);
}
double num2 = Math.Max(this.bounds.Width, this.bounds.Height);
this.bounds.Scale(num2, num2);
}
private void ConstructVoronoiRegion(Vertex vertex)
{
Vertex vertex1;
Vertex vertex2;
VoronoiRegion voronoiRegion = new VoronoiRegion(vertex);
this.regions.Add(voronoiRegion);
List<Point> points = new List<Point>();
Otri otri = new Otri();
Otri otri1 = new Otri();
Otri otri2 = new Otri();
Otri otri3 = new Otri();
Osub osub = new Osub();
vertex.tri.Copy(ref otri1);
otri1.Copy(ref otri);
otri1.Onext(ref otri2);
if (otri2.triangle == Mesh.dummytri)
{
otri1.Oprev(ref otri3);
if (otri3.triangle != Mesh.dummytri)
{
otri1.Copy(ref otri2);
otri1.OprevSelf();
otri1.Copy(ref otri);
}
}
while (otri2.triangle != Mesh.dummytri)
{
points.Add(this.points[otri.triangle.id]);
if (otri2.Equal(otri1))
{
voronoiRegion.Add(points);
return;
}
otri2.Copy(ref otri);
otri2.OnextSelf();
}
voronoiRegion.Bounded = false;
int count = this.mesh.triangles.Count;
otri.Lprev(ref otri2);
otri2.SegPivot(ref osub);
int num = osub.seg.hash;
points.Add(this.points[otri.triangle.id]);
if (!this.rayPoints.ContainsKey(num))
{
vertex1 = otri.Org();
Vertex vertex3 = otri.Apex();
this.BoxRayIntersection(this.points[otri.triangle.id], vertex1.y - vertex3.y, vertex3.x - vertex1.x, out vertex2);
vertex2.id = count + this.rayIndex;
this.points[count + this.rayIndex] = vertex2;
this.rayIndex = this.rayIndex + 1;
points.Add(vertex2);
this.rayPoints.Add(num, vertex2);
}
else
{
points.Add(this.rayPoints[num]);
}
points.Reverse();
otri1.Copy(ref otri);
otri.Oprev(ref otri3);
while (otri3.triangle != Mesh.dummytri)
{
points.Add(this.points[otri3.triangle.id]);
otri3.Copy(ref otri);
otri3.OprevSelf();
}
otri.SegPivot(ref osub);
num = osub.seg.hash;
if (!this.rayPoints.ContainsKey(num))
{
vertex1 = otri.Org();
Vertex vertex4 = otri.Dest();
this.BoxRayIntersection(this.points[otri.triangle.id], vertex4.y - vertex1.y, vertex1.x - vertex4.x, out vertex2);
vertex2.id = count + this.rayIndex;
this.points[count + this.rayIndex] = vertex2;
this.rayIndex = this.rayIndex + 1;
points.Add(vertex2);
this.rayPoints.Add(num, vertex2);
}
else
{
points.Add(this.rayPoints[num]);
}
points.Reverse();
voronoiRegion.Add(points);
}
private void Generate()
{
this.mesh.Renumber();
this.mesh.MakeVertexMap();
this.points = new Point[this.mesh.triangles.Count + this.mesh.hullsize];
this.regions = new List<VoronoiRegion>(this.mesh.vertices.Count);
this.rayPoints = new Dictionary<int, Point>();
this.rayIndex = 0;
this.bounds = new BoundingBox();
this.ComputeCircumCenters();
foreach (Vertex value in this.mesh.vertices.Values)
{
this.ConstructVoronoiRegion(value);
}
}
}
}
| |
//
// SqlGuidTest.cs - NUnit Test Cases for System.Data.SqlTypes.SqlGuid
//
// Authors:
// Ville Palo ([email protected])
// Martin Willemoes Hansen ([email protected])
//
// (C) 2002 Ville Palo
// (C) 2003 Martin Willemoes Hansen
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Data.SqlTypes;
namespace MonoTests.System.Data.SqlTypes
{
[TestFixture]
public class SqlGuidTest : Assertion {
// 00000a01-0000-0000-0000-000000000000
private SqlGuid Test1;
// 00000f64-0000-0000-0000-000000000000
private SqlGuid Test2;
private SqlGuid Test3;
// 0000fafa-0000-0000-0000-000000000000
private SqlGuid Test4;
[SetUp]
public void GetReady()
{
byte [] b1 = new byte [16];
byte [] b2 = new byte [16];
byte [] b3 = new byte [16];
byte [] b4 = new byte [16];
b1 [0] = 1;
b1 [1] = 10;
b2 [0] = 100;
b2 [1] = 15;
b3 [0] = 100;
b3 [1] = 15;
b4 [0] = 250;
b4 [1] = 250;
Test1 = new SqlGuid (b1);
Test2 = new SqlGuid (b2);
Test3 = new SqlGuid (b3);
Test4 = new SqlGuid (b4);
}
// Test constructor
[Test]
public void Create()
{
// SqlGuid (Byte[])
byte [] b = new byte [16];
b [0] = 100;
b [1] = 200;
try {
SqlGuid Test = new SqlGuid (b);
// SqlGuid (Guid)
Guid TestGuid = new Guid (b);
Test = new SqlGuid (TestGuid);
// SqlGuid (string)
Test = new SqlGuid ("12345678-1234-1234-1234-123456789012");
// SqlGuid (int, short, short, byte, byte, byte, byte, byte, byte, byte, byte)
Test = new SqlGuid (10, 1, 2, 13, 14, 15, 16, 17, 19, 20 ,21);
} catch (Exception e) {
Fail ("#A01 " + e);
}
}
// Test public fields
[Test]
public void PublicFields()
{
Assert ("#B01", SqlGuid.Null.IsNull);
}
// Test properties
[Test]
public void Properties()
{
Guid ResultGuid = new Guid ("00000f64-0000-0000-0000-000000000000");
Assert ("#C01", !Test1.IsNull);
Assert ("#C02", SqlGuid.Null.IsNull);
AssertEquals ("#C03", ResultGuid, Test2.Value);
}
// PUBLIC METHODS
[Test]
public void CompareTo()
{
String TestString = "This is a test string";
SqlGuid test1 = new SqlGuid("1AAAAAAA-BBBB-CCCC-DDDD-3EEEEEEEEEEE");
SqlGuid test2 = new SqlGuid("1AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE");
SqlGuid test3 = new SqlGuid("1AAAAAAA-BBBB-CCCC-DDDD-1EEEEEEEEEEE");
Assert ("#D01", Test1.CompareTo (Test3) < 0);
Assert ("#D02", Test4.CompareTo (Test1) > 0);
Assert ("#D03", Test3.CompareTo (Test2) == 0);
Assert ("#D04", Test4.CompareTo (SqlGuid.Null) > 0);
Assert ("#D05", test1.CompareTo (test2) > 0);
Assert ("#D06", test3.CompareTo (test2) < 0);
try {
Test1.CompareTo (TestString);
Fail("#D05");
} catch(Exception e) {
AssertEquals ("#D06", typeof (ArgumentException), e.GetType ());
}
}
[Test]
public void EqualsMethods()
{
Assert ("#E01", !Test1.Equals (Test2));
Assert ("#E02", !Test2.Equals (Test4));
Assert ("#E03", !Test2.Equals (new SqlString ("TEST")));
Assert ("#E04", Test2.Equals (Test3));
// Static Equals()-method
Assert ("#E05", SqlGuid.Equals (Test2, Test3).Value);
Assert ("#E06", !SqlGuid.Equals (Test1, Test2).Value);
}
[Test]
public void GetHashCodeTest()
{
AssertEquals ("#F01", Test1.GetHashCode (), Test1.GetHashCode ());
Assert ("#F02", Test1.GetHashCode () != Test2.GetHashCode ());
AssertEquals ("#F02", Test3.GetHashCode (), Test2.GetHashCode ());
}
[Test]
public void GetTypeTest()
{
AssertEquals ("#G01", "System.Data.SqlTypes.SqlGuid", Test1.GetType ().ToString ());
AssertEquals ("#G02", "System.Guid", Test3.Value.GetType ().ToString ());
}
[Test]
public void Greaters()
{
// GreateThan ()
Assert ("#H01", !SqlGuid.GreaterThan (Test1, Test2).Value);
Assert ("#H02", SqlGuid.GreaterThan (Test2, Test1).Value);
Assert ("#H03", !SqlGuid.GreaterThan (Test2, Test3).Value);
// GreaterTharOrEqual ()
Assert ("#H04", !SqlGuid.GreaterThanOrEqual (Test1, Test2).Value);
Assert ("#H05", SqlGuid.GreaterThanOrEqual (Test2, Test1).Value);
Assert ("#H06", SqlGuid.GreaterThanOrEqual (Test2, Test3).Value);
}
[Test]
public void Lessers()
{
// LessThan()
Assert ("#I01", !SqlGuid.LessThan (Test2, Test3).Value);
Assert ("#I02", !SqlGuid.LessThan (Test2, Test1).Value);
Assert ("#I03", SqlGuid.LessThan (Test1, Test2).Value);
// LessThanOrEqual ()
Assert ("#I04", SqlGuid.LessThanOrEqual (Test1, Test2).Value);
Assert ("#I05", !SqlGuid.LessThanOrEqual (Test2, Test1).Value);
Assert ("#I06", SqlGuid.LessThanOrEqual (Test2, Test3).Value);
Assert ("#I07", SqlGuid.LessThanOrEqual (Test4, SqlGuid.Null).IsNull);
}
[Test]
public void NotEquals()
{
Assert ("#J01", SqlGuid.NotEquals (Test1, Test2).Value);
Assert ("#J02", SqlGuid.NotEquals (Test2, Test1).Value);
Assert ("#J03", SqlGuid.NotEquals (Test3, Test1).Value);
Assert ("#J04", !SqlGuid.NotEquals (Test3, Test2).Value);
Assert ("#J05", SqlGuid.NotEquals (SqlGuid.Null, Test2).IsNull);
}
[Test]
public void Parse()
{
try {
SqlGuid.Parse (null);
Fail ("#K01");
} catch (Exception e) {
AssertEquals ("#K02", typeof (ArgumentNullException), e.GetType ());
}
try {
SqlGuid.Parse ("not-a-number");
Fail ("#K03");
} catch (Exception e) {
AssertEquals ("#K04", typeof (FormatException), e.GetType ());
}
try {
SqlGuid.Parse ("9e400");
Fail ("#K05");
} catch (Exception e) {
AssertEquals ("#K06", typeof (FormatException), e.GetType ());
}
AssertEquals("#K07", new Guid("87654321-0000-0000-0000-000000000000"),
SqlGuid.Parse ("87654321-0000-0000-0000-000000000000").Value);
}
[Test]
public void Conversions()
{
// ToByteArray ()
AssertEquals ("#L01", (byte)1, Test1.ToByteArray () [0]);
AssertEquals ("#L02", (byte)15, Test2.ToByteArray () [1]);
// ToSqlBinary ()
byte [] b = new byte [2];
b [0] = 100;
b [1] = 15;
AssertEquals ("#L03", new SqlBinary (b), Test3.ToSqlBinary ());
// ToSqlString ()
AssertEquals ("#L04", "00000a01-0000-0000-0000-000000000000",
Test1.ToSqlString ().Value);
AssertEquals ("#L05", "0000fafa-0000-0000-0000-000000000000",
Test4.ToSqlString ().Value);
// ToString ()
AssertEquals ("#L06", "00000a01-0000-0000-0000-000000000000",
Test1.ToString ());
AssertEquals ("#L07", "0000fafa-0000-0000-0000-000000000000",
Test4.ToString ());
}
// OPERATORS
[Test]
public void ThanOrEqualOperators()
{
// == -operator
Assert ("#M01", (Test3 == Test2).Value);
Assert ("#M02", !(Test1 == Test2).Value);
Assert ("#M03", (Test1 == SqlGuid.Null).IsNull);
// != -operator
Assert ("#M04", !(Test2 != Test3).Value);
Assert ("#M05", (Test1 != Test3).Value);
Assert ("#M06", (Test1 != SqlGuid.Null).IsNull);
// > -operator
Assert ("#M07", (Test2 > Test1).Value);
Assert ("#M08", !(Test1 > Test3).Value);
Assert ("#M09", !(Test3 > Test2).Value);
Assert ("#M10", (Test1 > SqlGuid.Null).IsNull);
// >= -operator
Assert ("#M12", !(Test1 >= Test3).Value);
Assert ("#M13", (Test3 >= Test1).Value);
Assert ("#M14", (Test3 >= Test2).Value);
Assert ("#M15", (Test1 >= SqlGuid.Null).IsNull);
// < -operator
Assert ("#M16", !(Test2 < Test1).Value);
Assert ("#M17", (Test1 < Test3).Value);
Assert ("#M18", !(Test2 < Test3).Value);
Assert ("#M19", (Test1 < SqlGuid.Null).IsNull);
// <= -operator
Assert ("#M20", (Test1 <= Test3).Value);
Assert ("#M21", !(Test3 <= Test1).Value);
Assert ("#M22", (Test2 <= Test3).Value);
Assert ("#M23", (Test1 <= SqlGuid.Null).IsNull);
}
[Test]
public void SqlBinaryToSqlGuid()
{
byte [] b = new byte [16];
b [0] = 100;
b [1] = 200;
SqlBinary TestBinary = new SqlBinary (b);
AssertEquals ("#N01", new Guid("0000c864-0000-0000-0000-000000000000"),
((SqlGuid)TestBinary).Value);
}
[Test]
public void SqlGuidToGuid()
{
AssertEquals ("#O01", new Guid("00000a01-0000-0000-0000-000000000000"),
(Guid)Test1);
AssertEquals ("#O02", new Guid("00000f64-0000-0000-0000-000000000000"),
(Guid)Test2);
}
[Test]
public void SqlStringToSqlGuid()
{
SqlString TestString = new SqlString ("Test string");
SqlString TestString100 = new SqlString ("0000c864-0000-0000-0000-000000000000");
AssertEquals ("#P01", new Guid("0000c864-0000-0000-0000-000000000000"),
((SqlGuid)TestString100).Value);
try {
SqlGuid test = (SqlGuid)TestString;
Fail ("#P02");
} catch(Exception e) {
AssertEquals ("#P03", typeof (FormatException), e.GetType ());
}
}
[Test]
public void GuidToSqlGuid()
{
Guid TestGuid = new Guid("0000c864-0000-0000-0000-000007650000");
AssertEquals ("#Q01", new SqlGuid("0000c864-0000-0000-0000-000007650000"),
(SqlGuid)TestGuid);
}
}
}
| |
// <copyright file="InternetExplorerOptions.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 OpenQA.Selenium.Remote;
namespace OpenQA.Selenium.IE
{
/// <summary>
/// Specifies the scroll behavior of elements scrolled into view in the IE driver.
/// </summary>
public enum InternetExplorerElementScrollBehavior
{
/// <summary>
/// Indicates the behavior is unspecified.
/// </summary>
Default,
/// <summary>
/// Scrolls elements to align with the top of the viewport.
/// </summary>
Top,
/// <summary>
/// Scrolls elements to align with the bottom of the viewport.
/// </summary>
Bottom
}
/// <summary>
/// Specifies the behavior of handling unexpected alerts in the IE driver.
/// </summary>
public enum InternetExplorerUnexpectedAlertBehavior
{
/// <summary>
/// Indicates the behavior is not set.
/// </summary>
Default,
/// <summary>
/// Ignore unexpected alerts, such that the user must handle them.
/// </summary>
Ignore,
/// <summary>
/// Accept unexpected alerts.
/// </summary>
Accept,
/// <summary>
/// Dismiss unexpected alerts.
/// </summary>
Dismiss
}
/// <summary>
/// Class to manage options specific to <see cref="InternetExplorerDriver"/>
/// </summary>
/// <example>
/// <code>
/// InternetExplorerOptions options = new InternetExplorerOptions();
/// options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
/// </code>
/// <para></para>
/// <para>For use with InternetExplorerDriver:</para>
/// <para></para>
/// <code>
/// InternetExplorerDriver driver = new InternetExplorerDriver(options);
/// </code>
/// <para></para>
/// <para>For use with RemoteWebDriver:</para>
/// <para></para>
/// <code>
/// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities());
/// </code>
/// </example>
public class InternetExplorerOptions : DriverOptions
{
/// <summary>
/// Gets the name of the capability used to store IE options in
/// a <see cref="DesiredCapabilities"/> object.
/// </summary>
public static readonly string Capability = "se:ieOptions";
private const string BrowserNameValue = "internet explorer";
private const string IgnoreProtectedModeSettingsCapability = "ignoreProtectedModeSettings";
private const string IgnoreZoomSettingCapability = "ignoreZoomSetting";
private const string InitialBrowserUrlCapability = "initialBrowserUrl";
private const string EnablePersistentHoverCapability = "enablePersistentHover";
private const string ElementScrollBehaviorCapability = "elementScrollBehavior";
private const string RequireWindowFocusCapability = "requireWindowFocus";
private const string BrowserAttachTimeoutCapability = "browserAttachTimeout";
private const string BrowserCommandLineSwitchesCapability = "ie.browserCommandLineSwitches";
private const string ForceCreateProcessApiCapability = "ie.forceCreateProcessApi";
private const string UsePerProcessProxyCapability = "ie.usePerProcessProxy";
private const string EnsureCleanSessionCapability = "ie.ensureCleanSession";
private const string ForceShellWindowsApiCapability = "ie.forceShellWindowsApi";
private const string FileUploadDialogTimeoutCapability = "ie.fileUploadDialogTimeout";
private const string EnableFullPageScreenshotCapability = "ie.enableFullPageScreenshot";
private bool ignoreProtectedModeSettings;
private bool ignoreZoomLevel;
private bool enableNativeEvents = true;
private bool requireWindowFocus;
private bool enablePersistentHover = true;
private bool forceCreateProcessApi;
private bool forceShellWindowsApi;
private bool usePerProcessProxy;
private bool ensureCleanSession;
private bool validateCookieDocumentType = true;
private bool enableFullPageScreenshot = true;
private TimeSpan browserAttachTimeout = TimeSpan.MinValue;
private TimeSpan fileUploadDialogTimeout = TimeSpan.MinValue;
private string initialBrowserUrl = string.Empty;
private string browserCommandLineArguments = string.Empty;
private InternetExplorerElementScrollBehavior elementScrollBehavior = InternetExplorerElementScrollBehavior.Default;
private Dictionary<string, object> additionalCapabilities = new Dictionary<string, object>();
private Dictionary<string, object> additionalInternetExplorerOptions = new Dictionary<string, object>();
public InternetExplorerOptions() : base()
{
this.BrowserName = BrowserNameValue;
this.PlatformName = "windows";
this.AddKnownCapabilityName(Capability, "current InterentExplorerOptions class instance");
this.AddKnownCapabilityName(IgnoreProtectedModeSettingsCapability, "IntroduceInstabilityByIgnoringProtectedModeSettings property");
this.AddKnownCapabilityName(IgnoreZoomSettingCapability, "IgnoreZoomLevel property");
this.AddKnownCapabilityName(CapabilityType.HasNativeEvents, "EnableNativeEvents property");
this.AddKnownCapabilityName(InitialBrowserUrlCapability, "InitialBrowserUrl property");
this.AddKnownCapabilityName(ElementScrollBehaviorCapability, "ElementScrollBehavior property");
this.AddKnownCapabilityName(CapabilityType.UnexpectedAlertBehavior, "UnhandledPromptBehavior property");
this.AddKnownCapabilityName(EnablePersistentHoverCapability, "EnablePersistentHover property");
this.AddKnownCapabilityName(RequireWindowFocusCapability, "RequireWindowFocus property");
this.AddKnownCapabilityName(BrowserAttachTimeoutCapability, "BrowserAttachTimeout property");
this.AddKnownCapabilityName(ForceCreateProcessApiCapability, "ForceCreateProcessApi property");
this.AddKnownCapabilityName(ForceShellWindowsApiCapability, "ForceShellWindowsApi property");
this.AddKnownCapabilityName(BrowserCommandLineSwitchesCapability, "BrowserComaandLineArguments property");
this.AddKnownCapabilityName(UsePerProcessProxyCapability, "UsePerProcessProxy property");
this.AddKnownCapabilityName(EnsureCleanSessionCapability, "EnsureCleanSession property");
this.AddKnownCapabilityName(FileUploadDialogTimeoutCapability, "FileUploadDialogTimeout property");
this.AddKnownCapabilityName(EnableFullPageScreenshotCapability, "EnableFullPageScreenshot property");
}
/// <summary>
/// Gets or sets a value indicating whether to ignore the settings of the Internet Explorer Protected Mode.
/// </summary>
public bool IntroduceInstabilityByIgnoringProtectedModeSettings
{
get { return this.ignoreProtectedModeSettings; }
set { this.ignoreProtectedModeSettings = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to ignore the zoom level of Internet Explorer .
/// </summary>
public bool IgnoreZoomLevel
{
get { return this.ignoreZoomLevel; }
set { this.ignoreZoomLevel = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to use native events in interacting with elements.
/// </summary>
public bool EnableNativeEvents
{
get { return this.enableNativeEvents; }
set { this.enableNativeEvents = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to require the browser window to have focus before interacting with elements.
/// </summary>
public bool RequireWindowFocus
{
get { return this.requireWindowFocus; }
set { this.requireWindowFocus = value; }
}
/// <summary>
/// Gets or sets the initial URL displayed when IE is launched. If not set, the browser launches
/// with the internal startup page for the WebDriver server.
/// </summary>
/// <remarks>
/// By setting the <see cref="IntroduceInstabilityByIgnoringProtectedModeSettings"/> to <see langword="true"/>
/// and this property to a correct URL, you can launch IE in the Internet Protected Mode zone. This can be helpful
/// to avoid the flakiness introduced by ignoring the Protected Mode settings. Nevertheless, setting Protected Mode
/// zone settings to the same value in the IE configuration is the preferred method.
/// </remarks>
public string InitialBrowserUrl
{
get { return this.initialBrowserUrl; }
set { this.initialBrowserUrl = value; }
}
/// <summary>
/// Gets or sets the value for describing how elements are scrolled into view in the IE driver. Defaults
/// to scrolling the element to the top of the viewport.
/// </summary>
public InternetExplorerElementScrollBehavior ElementScrollBehavior
{
get { return this.elementScrollBehavior; }
set { this.elementScrollBehavior = value; }
}
/// <summary>
/// Gets or sets the value for describing how unexpected alerts are to be handled in the IE driver.
/// Defaults to <see cref="InternetExplorerUnexpectedAlertBehavior.Default"/>.
/// </summary>
[Obsolete("This property is being replaced by the UnhandledPromptBehavior property, and will be removed in a future version of the .NET bindings. Please use that instead.")]
public InternetExplorerUnexpectedAlertBehavior UnexpectedAlertBehavior
{
get { return this.GetUnexpectedAlertBehavior(); }
set { this.SetUnhandledPromptBehavior(value); }
}
/// <summary>
/// Gets or sets a value indicating whether to enable persistently sending WM_MOUSEMOVE messages
/// to the IE window during a mouse hover.
/// </summary>
public bool EnablePersistentHover
{
get { return this.enablePersistentHover; }
set { this.enablePersistentHover = value; }
}
/// <summary>
/// Gets or sets the amount of time the driver will attempt to look for a newly launched instance
/// of Internet Explorer.
/// </summary>
public TimeSpan BrowserAttachTimeout
{
get { return this.browserAttachTimeout; }
set { this.browserAttachTimeout = value; }
}
/// <summary>
/// Gets or sets the amount of time the driver will attempt to look for the file selection
/// dialog when attempting to upload a file.
/// </summary>
public TimeSpan FileUploadDialogTimeout
{
get { return this.fileUploadDialogTimeout; }
set { this.fileUploadDialogTimeout = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to force the use of the Windows CreateProcess API
/// when launching Internet Explorer. The default value is <see langword="false"/>.
/// </summary>
public bool ForceCreateProcessApi
{
get { return this.forceCreateProcessApi; }
set { this.forceCreateProcessApi = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to force the use of the Windows ShellWindows API
/// when attaching to Internet Explorer. The default value is <see langword="false"/>.
/// </summary>
public bool ForceShellWindowsApi
{
get { return this.forceShellWindowsApi; }
set { this.forceShellWindowsApi = value; }
}
/// <summary>
/// Gets or sets the command line arguments used in launching Internet Explorer when the
/// Windows CreateProcess API is used. This property only has an effect when the
/// <see cref="ForceCreateProcessApi"/> is <see langword="true"/>.
/// </summary>
public string BrowserCommandLineArguments
{
get { return this.browserCommandLineArguments; }
set { this.browserCommandLineArguments = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to use the supplied <see cref="Proxy"/>
/// settings on a per-process basis, not updating the system installed proxy setting.
/// This property is only valid when setting a <see cref="Proxy"/>, where the
/// <see cref="OpenQA.Selenium.Proxy.Kind"/> property is either <see cref="ProxyKind.Direct"/>,
/// <see cref="ProxyKind.System"/>, or <see cref="ProxyKind.Manual"/>, and is
/// otherwise ignored. Defaults to <see langword="false"/>.
/// </summary>
public bool UsePerProcessProxy
{
get { return this.usePerProcessProxy; }
set { this.usePerProcessProxy = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to clear the Internet Explorer cache
/// before launching the browser. When set to <see langword="true"/>, clears the
/// system cache for all instances of Internet Explorer, even those already running
/// when the driven instance is launched. Defaults to <see langword="false"/>.
/// </summary>
public bool EnsureCleanSession
{
get { return this.ensureCleanSession; }
set { this.ensureCleanSession = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to enable full-page screenshots for
/// the IE driver. Defaults to <see langword="true"/>.
/// </summary>
[Obsolete("The driver no longer supports this capability. It will be removed in a future release.")]
public bool EnableFullPageScreenshot
{
get { return this.enableFullPageScreenshot; }
set { this.enableFullPageScreenshot = value; }
}
/// <summary>
/// Provides a means to add additional capabilities not yet added as type safe options
/// for the Internet Explorer driver.
/// </summary>
/// <param name="capabilityName">The name of the capability to add.</param>
/// <param name="capabilityValue">The value of the capability to add.</param>
/// <exception cref="ArgumentException">
/// thrown when attempting to add a capability for which there is already a type safe option, or
/// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string.
/// </exception>
/// <remarks>Calling <see cref="AddAdditionalCapability(string, object)"/>
/// where <paramref name="capabilityName"/> has already been added will overwrite the
/// existing value with the new value in <paramref name="capabilityValue"/>.
/// Also, by default, calling this method adds capabilities to the options object passed to
/// IEDriverServer.exe.</remarks>
public override void AddAdditionalCapability(string capabilityName, object capabilityValue)
{
// Add the capability to the ieOptions object by default. This is to handle
// the 80% case where the IE driver adds a new option in IEDriverServer.exe
// and the bindings have not yet had a type safe option added.
this.AddAdditionalCapability(capabilityName, capabilityValue, false);
}
/// <summary>
/// Provides a means to add additional capabilities not yet added as type safe options
/// for the Internet Explorer driver.
/// </summary>
/// <param name="capabilityName">The name of the capability to add.</param>
/// <param name="capabilityValue">The value of the capability to add.</param>
/// <param name="isGlobalCapability">Indicates whether the capability is to be set as a global
/// capability for the driver instead of a IE-specific option.</param>
/// <exception cref="ArgumentException">
/// thrown when attempting to add a capability for which there is already a type safe option, or
/// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string.
/// </exception>
/// <remarks>Calling <see cref="AddAdditionalCapability(string, object, bool)"/> where <paramref name="capabilityName"/>
/// has already been added will overwrite the existing value with the new value in <paramref name="capabilityValue"/></remarks>
public void AddAdditionalCapability(string capabilityName, object capabilityValue, bool isGlobalCapability)
{
if (this.IsKnownCapabilityName(capabilityName))
{
string typeSafeOptionName = this.GetTypeSafeOptionName(capabilityName);
string message = string.Format(CultureInfo.InvariantCulture, "There is already an option for the {0} capability. Please use the {1} instead.", capabilityName, typeSafeOptionName);
throw new ArgumentException(message, "capabilityName");
}
if (string.IsNullOrEmpty(capabilityName))
{
throw new ArgumentException("Capability name may not be null an empty string.", "capabilityName");
}
if (isGlobalCapability)
{
this.additionalCapabilities[capabilityName] = capabilityValue;
}
else
{
this.additionalInternetExplorerOptions[capabilityName] = capabilityValue;
}
}
/// <summary>
/// Returns DesiredCapabilities for IE with these options included as
/// capabilities. This copies the options. Further changes will not be
/// reflected in the returned capabilities.
/// </summary>
/// <returns>The DesiredCapabilities for IE with these options.</returns>
public override ICapabilities ToCapabilities()
{
DesiredCapabilities capabilities = this.GenerateDesiredCapabilities(true);
Dictionary<string, object> internetExplorerOptions = this.BuildInternetExplorerOptionsDictionary();
capabilities.SetCapability(InternetExplorerOptions.Capability, internetExplorerOptions);
foreach (KeyValuePair<string, object> pair in this.additionalCapabilities)
{
capabilities.SetCapability(pair.Key, pair.Value);
}
return capabilities;
}
private Dictionary<string, object> BuildInternetExplorerOptionsDictionary()
{
Dictionary<string, object> internetExplorerOptionsDictionary = new Dictionary<string, object>();
internetExplorerOptionsDictionary[CapabilityType.HasNativeEvents] = this.enableNativeEvents;
internetExplorerOptionsDictionary[EnablePersistentHoverCapability] = this.enablePersistentHover;
if (this.requireWindowFocus)
{
internetExplorerOptionsDictionary[RequireWindowFocusCapability] = true;
}
if (this.ignoreProtectedModeSettings)
{
internetExplorerOptionsDictionary[IgnoreProtectedModeSettingsCapability] = true;
}
if (this.ignoreZoomLevel)
{
internetExplorerOptionsDictionary[IgnoreZoomSettingCapability] = true;
}
if (!string.IsNullOrEmpty(this.initialBrowserUrl))
{
internetExplorerOptionsDictionary[InitialBrowserUrlCapability] = this.initialBrowserUrl;
}
if (this.elementScrollBehavior != InternetExplorerElementScrollBehavior.Default)
{
if (this.elementScrollBehavior == InternetExplorerElementScrollBehavior.Bottom)
{
internetExplorerOptionsDictionary[ElementScrollBehaviorCapability] = 1;
}
else
{
internetExplorerOptionsDictionary[ElementScrollBehaviorCapability] = 0;
}
}
if (this.browserAttachTimeout != TimeSpan.MinValue)
{
internetExplorerOptionsDictionary[BrowserAttachTimeoutCapability] = Convert.ToInt32(this.browserAttachTimeout.TotalMilliseconds);
}
if (this.fileUploadDialogTimeout != TimeSpan.MinValue)
{
internetExplorerOptionsDictionary[FileUploadDialogTimeoutCapability] = Convert.ToInt32(this.fileUploadDialogTimeout.TotalMilliseconds);
}
if (this.forceCreateProcessApi)
{
internetExplorerOptionsDictionary[ForceCreateProcessApiCapability] = true;
if (!string.IsNullOrEmpty(this.browserCommandLineArguments))
{
internetExplorerOptionsDictionary[BrowserCommandLineSwitchesCapability] = this.browserCommandLineArguments;
}
}
if (this.forceShellWindowsApi)
{
internetExplorerOptionsDictionary[ForceShellWindowsApiCapability] = true;
}
if (this.Proxy != null)
{
internetExplorerOptionsDictionary[UsePerProcessProxyCapability] = this.usePerProcessProxy;
}
if (this.ensureCleanSession)
{
internetExplorerOptionsDictionary[EnsureCleanSessionCapability] = true;
}
if (!this.enableFullPageScreenshot)
{
internetExplorerOptionsDictionary[EnableFullPageScreenshotCapability] = false;
}
foreach (KeyValuePair<string, object> pair in this.additionalInternetExplorerOptions)
{
internetExplorerOptionsDictionary[pair.Key] = pair.Value;
}
return internetExplorerOptionsDictionary;
}
private void SetUnhandledPromptBehavior(InternetExplorerUnexpectedAlertBehavior unexpectedAlertBehavior)
{
switch (unexpectedAlertBehavior)
{
case InternetExplorerUnexpectedAlertBehavior.Accept:
this.UnhandledPromptBehavior = UnhandledPromptBehavior.AcceptAndNotify;
break;
case InternetExplorerUnexpectedAlertBehavior.Dismiss:
this.UnhandledPromptBehavior = UnhandledPromptBehavior.DismissAndNotify;
break;
case InternetExplorerUnexpectedAlertBehavior.Ignore:
this.UnhandledPromptBehavior = UnhandledPromptBehavior.Ignore;
break;
default:
this.UnhandledPromptBehavior = UnhandledPromptBehavior.Default;
break;
}
}
private InternetExplorerUnexpectedAlertBehavior GetUnexpectedAlertBehavior()
{
switch (this.UnhandledPromptBehavior)
{
case UnhandledPromptBehavior.AcceptAndNotify:
return InternetExplorerUnexpectedAlertBehavior.Accept;
case UnhandledPromptBehavior.DismissAndNotify:
return InternetExplorerUnexpectedAlertBehavior.Dismiss;
case UnhandledPromptBehavior.Ignore:
return InternetExplorerUnexpectedAlertBehavior.Ignore;
}
return InternetExplorerUnexpectedAlertBehavior.Default;
}
}
}
| |
//-----------------------------------------------------------------------------
// Filename: SIPUserField.cs
//
// Description:
// Encapsulates the format for the SIP Contact, From and To headers
//
// History:
// 21 Apr 2006 Aaron Clauson Created.
// 04 Sep 2008 Aaron Clauson Changed display name to always use quotes. Some SIP stacks were
// found to have porblems with a comma in a non-quoted display name.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006 Aaron Clauson ([email protected]), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// 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 SIP Sorcery PTY LTD.
// 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.Serialization;
using System.Text.RegularExpressions;
using SIPSorcery.Sys;
using log4net;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.SIP
{
/// <summary>
/// name-addr = [ display-name ] LAQUOT addr-spec RAQUOT
/// addr-spec = SIP-URI / SIPS-URI / absoluteURI
/// SIP-URI = "sip:" [ userinfo ] hostport
/// uri-parameters [ headers ]
/// SIPS-URI = "sips:" [ userinfo ] hostport
/// uri-parameters [ headers ]
/// userinfo = ( user / telephone-subscriber ) [ ":" password ] "@"
///
/// If no "<" and ">" are present, all parameters after the URI are header
/// parameters, not URI parameters.
/// </summary>
[DataContract]
public class SIPUserField
{
private const char PARAM_TAG_DELIMITER = ';';
private static ILog logger = AssemblyState.logger;
[DataMember]
public string Name;
[DataMember]
public SIPURI URI;
[DataMember]
public SIPParameters Parameters = new SIPParameters(null, PARAM_TAG_DELIMITER);
public SIPUserField()
{ }
public SIPUserField(string name, SIPURI uri, string paramsAndHeaders)
{
Name = name;
URI = uri;
Parameters = new SIPParameters(paramsAndHeaders, PARAM_TAG_DELIMITER);
}
public static SIPUserField ParseSIPUserField(string userFieldStr)
{
if (userFieldStr.IsNullOrBlank())
{
throw new ArgumentException("A SIPUserField cannot be parsed from an empty string.");
}
SIPUserField userField = new SIPUserField();
string trimUserField = userFieldStr.Trim();
int position = trimUserField.IndexOf('<');
if (position == -1)
{
// Treat the field as a URI only, except that all parameters are Header parameters and not URI parameters
// (RFC3261 section 20.39 which refers to 20.10 for parsing rules).
string uriStr = trimUserField;
int paramDelimPosn = trimUserField.IndexOf(PARAM_TAG_DELIMITER);
if (paramDelimPosn != -1)
{
string paramStr = trimUserField.Substring(paramDelimPosn + 1).Trim();
userField.Parameters = new SIPParameters(paramStr, PARAM_TAG_DELIMITER);
uriStr = trimUserField.Substring(0, paramDelimPosn);
}
userField.URI = SIPURI.ParseSIPURI(uriStr);
}
else
{
if (position > 0)
{
userField.Name = trimUserField.Substring(0, position).Trim().Trim('"');
trimUserField = trimUserField.Substring(position, trimUserField.Length - position);
}
int addrSpecLen = trimUserField.Length;
position = trimUserField.IndexOf('>');
if (position != -1)
{
addrSpecLen = trimUserField.Length - 1;
if (position != -1)
{
addrSpecLen = position - 1;
string paramStr = trimUserField.Substring(position + 1).Trim();
userField.Parameters = new SIPParameters(paramStr, PARAM_TAG_DELIMITER);
}
string addrSpec = trimUserField.Substring(1, addrSpecLen);
userField.URI = SIPURI.ParseSIPURI(addrSpec);
}
else
{
throw new SIPValidationException(SIPValidationFieldsEnum.ContactHeader, "A SIPUserField was missing the right quote, " + userFieldStr + ".");
}
}
return userField;
}
public override string ToString()
{
try
{
string userFieldStr = null;
if (Name != null)
{
/*if(Regex.Match(Name, @"\s").Success)
{
userFieldStr = "\"" + Name + "\" ";
}
else
{
userFieldStr = Name + " ";
}*/
userFieldStr = "\"" + Name + "\" ";
}
userFieldStr += "<" + URI.ToString() + ">" + Parameters.ToString();
return userFieldStr;
}
catch (Exception excp)
{
logger.Error("Exception SIPUserField ToString. " + excp.Message);
throw;
}
}
public string ToParameterlessString()
{
try
{
string userFieldStr = null;
if (Name != null)
{
userFieldStr = "\"" + Name + "\" ";
}
userFieldStr += "<" + URI.ToParameterlessString() + ">";
return userFieldStr;
}
catch (Exception excp)
{
logger.Error("Exception SIPUserField ToParameterlessString. " + excp.Message);
throw;
}
}
public SIPUserField CopyOf()
{
SIPUserField copy = new SIPUserField();
copy.Name = Name;
copy.URI = URI.CopyOf();
copy.Parameters = Parameters.CopyOf();
return copy;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <[email protected]> //
// //
// 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. //
// //
////////////////////////////////////////////////////////////////////////////////
/* This HBox constains the buttons used to control the timeline playback and
* the counter that displays the current position */
namespace Diva.Editor.Gui {
using System;
using Gtk;
using Mono.Unix;
using Gdv;
using Util;
public class MediaControlsHBox : HBox {
// Translatable ////////////////////////////////////////////////
readonly static string nextMessageSS = Catalog.GetString
("Seek to next cut");
readonly static string prevMessageSS = Catalog.GetString
("Seek to previous cut");
readonly static string rewindMessageSS = Catalog.GetString
("Rewind to start");
readonly static string counterMessageSS = Catalog.GetString
("Displays current playback cursor position");
// Fields //////////////////////////////////////////////////////
Label counterLabel; // The label with the counter
Model.Root modelRoot = null; // App model
long nextMessageToken = -1;
long prevMessageToken = -1;
long rewindMessageToken = -1;
long counterMessageToken = -1;
// Properties //////////////////////////////////////////////////
public Time Counter {
set {
string str = TimeFu.ToSMPTE (value,
modelRoot.ProjectDetails.Format.VideoFormat.Fps);
counterLabel.Markup = String.Format ("<b><big><big><big>[{0}]</big></big></big></b>",
str);
}
}
// Public methods //////////////////////////////////////////////
public MediaControlsHBox (Model.Root root) : base (false, 6)
{
modelRoot = root;
MediaButton prevCutButton = new MediaButton ("stock_media-prev");
prevCutButton.Clicked += OnPrevCutClicked;
prevCutButton.Entered += OnPrevCutEntered;
prevCutButton.Left += OnPrevCutLeft;
MediaButton nextCutButton = new MediaButton ("stock_media-next");
nextCutButton.Clicked += OnNextCutClicked;
nextCutButton.Entered += OnNextCutEntered;
nextCutButton.Left += OnNextCutLeft;
MediaButton rewindButton = new MediaButton ("stock_media-rew");
rewindButton.Clicked += OnRewindClicked;
rewindButton.Entered += OnRewindEntered;
rewindButton.Left += OnRewindLeft;
PlayButton playButton = new PlayButton (root);
counterLabel = new Label ();
counterLabel.AddEvents ((int) Gdk.EventMask.LeaveNotifyMask);
counterLabel.AddEvents ((int) Gdk.EventMask.EnterNotifyMask);
counterLabel.EnterNotifyEvent += OnCounterEntered;
counterLabel.LeaveNotifyEvent += OnCounterLeft;
PackStart (rewindButton, false, false, 0);
PackStart (prevCutButton, false, false, 0);
PackStart (playButton, false, false, 0);
PackStart (counterLabel, true, true, 0);
PackStart (nextCutButton, false, false, 0);
Counter = Gdv.Time.Zero;
modelRoot.Pipeline.Ticker += OnTicker;
}
// Private methods /////////////////////////////////////////////
void OnTicker (object o, Model.PipelineTickerArgs args)
{
Counter = args.Time;
}
void OnPrevCutClicked (object o, EventArgs args)
{
modelRoot.Pipeline.SeekToPrevCut ();
}
void OnNextCutClicked (object o, EventArgs args)
{
modelRoot.Pipeline.SeekToNextCut ();
}
void OnRewindClicked (object o, EventArgs args)
{
modelRoot.Pipeline.SeekToZero ();
}
void OnPrevCutEntered (object o, EventArgs args)
{
if (prevMessageToken != -1) {
modelRoot.Window.PopMessage (prevMessageToken);
prevMessageToken = -1;
}
prevMessageToken = modelRoot.Window.PushMessage (prevMessageSS, Editor.Model.MessageLayer.Widget2);
}
void OnPrevCutLeft (object o, EventArgs args)
{
if (prevMessageToken != -1) {
modelRoot.Window.PopMessage (prevMessageToken);
prevMessageToken = -1;
}
}
void OnNextCutEntered (object o, EventArgs args)
{
if (nextMessageToken != -1) {
modelRoot.Window.PopMessage (nextMessageToken);
nextMessageToken = -1;
}
nextMessageToken = modelRoot.Window.PushMessage (nextMessageSS, Editor.Model.MessageLayer.Widget2);
}
void OnNextCutLeft (object o, EventArgs args)
{
if (nextMessageToken != -1) {
modelRoot.Window.PopMessage (nextMessageToken);
nextMessageToken = -1;
}
}
void OnRewindEntered (object o, EventArgs args)
{
if (rewindMessageToken != -1) {
modelRoot.Window.PopMessage (rewindMessageToken);
rewindMessageToken = -1;
}
rewindMessageToken = modelRoot.Window.PushMessage (rewindMessageSS, Editor.Model.MessageLayer.Widget2);
}
void OnRewindLeft (object o, EventArgs args)
{
if (rewindMessageToken != -1) {
modelRoot.Window.PopMessage (rewindMessageToken);
rewindMessageToken = -1;
}
}
void OnCounterEntered (object o, EnterNotifyEventArgs args)
{
if (counterMessageToken != -1) {
modelRoot.Window.PopMessage (counterMessageToken);
counterMessageToken = -1;
}
counterMessageToken = modelRoot.Window.PushMessage (counterMessageSS, Editor.Model.MessageLayer.Widget2);
}
void OnCounterLeft (object o, LeaveNotifyEventArgs args)
{
if (counterMessageToken != -1) {
modelRoot.Window.PopMessage (counterMessageToken);
counterMessageToken = -1;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Should.Core.Exceptions;
namespace Should.Core.Assertions
{
/// <summary>
/// A wrapper for Assert which is used by <see cref="TestClass"/>.
/// </summary>
public class Assertions
{
/// <summary>
/// Verifies that a collection contains a given object.
/// </summary>
/// <typeparam name="T">The type of the object to be verified</typeparam>
/// <param name="expected">The object expected to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="ContainsException">Thrown when the object is not present in the collection</exception>
public void Contains<T>(T expected, IEnumerable<T> collection)
{
Assert.Contains(expected, collection);
}
/// <summary>
/// Verifies that a collection contains a given object, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the object to be verified</typeparam>
/// <param name="expected">The object expected to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <param name="comparer">The comparer used to equate objects in the collection with the expected object</param>
/// <exception cref="ContainsException">Thrown when the object is not present in the collection</exception>
public void Contains<T>(T expected, IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
Assert.Contains(expected, collection, comparer);
}
/// <summary>
/// Verifies that a string contains a given sub-string, using the current culture.
/// </summary>
/// <param name="expectedSubString">The sub-string expected to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <exception cref="ContainsException">Thrown when the sub-string is not present inside the string</exception>
public void Contains(string expectedSubString, string actualString)
{
Assert.Contains(expectedSubString, actualString);
}
/// <summary>
/// Verifies that a string contains a given sub-string, using the given comparison type.
/// </summary>
/// <param name="expectedSubString">The sub-string expected to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <param name="comparisonType">The type of string comparison to perform</param>
/// <exception cref="ContainsException">Thrown when the sub-string is not present inside the string</exception>
public void Contains(string expectedSubString, string actualString, StringComparison comparisonType)
{
Assert.Contains(expectedSubString, actualString, comparisonType);
}
/// <summary>
/// Verifies that a collection does not contain a given object.
/// </summary>
/// <typeparam name="T">The type of the object to be compared</typeparam>
/// <param name="expected">The object that is expected not to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="DoesNotContainException">Thrown when the object is present inside the container</exception>
public void DoesNotContain<T>(T expected, IEnumerable<T> collection)
{
Assert.DoesNotContain(expected, collection);
}
/// <summary>
/// Verifies that a collection does not contain a given object, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the object to be compared</typeparam>
/// <param name="expected">The object that is expected not to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <param name="comparer">The comparer used to equate objects in the collection with the expected object</param>
/// <exception cref="DoesNotContainException">Thrown when the object is present inside the container</exception>
public void DoesNotContain<T>(T expected, IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
Assert.DoesNotContain(expected, collection, comparer);
}
/// <summary>
/// Verifies that a string does not contain a given sub-string, using the current culture.
/// </summary>
/// <param name="expectedSubString">The sub-string which is expected not to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <exception cref="DoesNotContainException">Thrown when the sub-string is present inside the string</exception>
public void DoesNotContain(string expectedSubString, string actualString)
{
Assert.DoesNotContain(expectedSubString, actualString);
}
/// <summary>
/// Verifies that a string does not contain a given sub-string, using the current culture.
/// </summary>
/// <param name="expectedSubString">The sub-string which is expected not to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <param name="comparisonType">The type of string comparison to perform</param>
/// <exception cref="DoesNotContainException">Thrown when the sub-string is present inside the given string</exception>
public void DoesNotContain(string expectedSubString, string actualString, StringComparison comparisonType)
{
Assert.DoesNotContain(expectedSubString, actualString, comparisonType);
}
///// <summary>
///// Verifies that a block of code does not throw any exceptions.
///// </summary>
///// <param name="testCode">A delegate to the code to be tested</param>
//public void DoesNotThrow(Assert.ThrowsDelegate testCode)
//{
// Assert.DoesNotThrow(testCode);
//}
/// <summary>
/// Verifies that a collection is empty.
/// </summary>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="ArgumentNullException">Thrown when the collection is null</exception>
/// <exception cref="EmptyException">Thrown when the collection is not empty</exception>
public void Empty(IEnumerable collection)
{
Assert.Empty(collection);
}
/// <summary>
/// Verifies that two objects are equal, using a default comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <exception cref="EqualException">Thrown when the objects are not equal</exception>
public void Equal<T>(T expected, T actual)
{
Assert.Equal(expected, actual);
}
/// <summary>
/// Verifies that two objects are equal, using a custom comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <param name="comparer">The comparer used to compare the two objects</param>
/// <exception cref="EqualException">Thrown when the objects are not equal</exception>
public void Equal<T>(T expected, T actual, IEqualityComparer<T> comparer)
{
Assert.Equal(expected, actual, comparer);
}
/// <summary>Do not call this method. Call Assert.Equal() instead.</summary>
public override bool Equals(object obj)
{
throw new NotImplementedException();
}
/// <summary>
/// Verifies that the condition is false.
/// </summary>
/// <param name="condition">The condition to be tested</param>
/// <exception cref="FalseException">Thrown if the condition is not false</exception>
public void False(bool condition)
{
Assert.False(condition);
}
/// <summary>
/// Verifies that the condition is false.
/// </summary>
/// <param name="condition">The condition to be tested</param>
/// <param name="userMessage">The message to show when the condition is not false</param>
/// <exception cref="FalseException">Thrown if the condition is not false</exception>
public void False(bool condition, string userMessage)
{
Assert.False(condition, userMessage);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>A hash code for the current <see cref="T:System.Object"/>.</returns>
public override int GetHashCode()
{
return 42;
}
/// <summary>Verifies that an object is greater than the exclusive minimum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="value">The object to be evaluated.</param>
/// <param name="maxValue">An object representing the exclusive minimum value of paramref name="value"/>.</param>
public static void GreaterThan<T>(T value, T maxValue)
{
Assert.GreaterThan(value, maxValue);
}
/// <summary>Verifies that an object is greater than the exclusive minimum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="value">The object to be evaluated.</param>
/// <param name="minValue">An object representing the exclusive minimum value of paramref name="value"/>.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param>
public static void GreaterThan<T>(T value, T minValue, IComparer<T> comparer)
{
Assert.GreaterThan(value, minValue, comparer);
}
/// <summary>Verifies that an object is greater than the inclusive minimum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="value">The object to be evaluated.</param>
/// <param name="minValue">An object representing the inclusive minimum value of paramref name="value"/>.</param>
public static void GreaterThanOrEqual<T>(T value, T minValue)
{
Assert.GreaterThanOrEqual(value, minValue);
}
/// <summary>Verifies that an object is greater than the inclusive minimum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="value">The object to be evaluated.</param>
/// <param name="minValue">An object representing the inclusive minimum value of paramref name="value"/>.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param>
public static void GreaterThanOrEqual<T>(T value, T minValue, IComparer<T> comparer)
{
Assert.GreaterThanOrEqual(value, minValue, comparer);
}
/// <summary>
/// Verifies that a value is within a given range.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <exception cref="InRangeException">Thrown when the value is not in the given range</exception>
public void InRange<T>(T actual, T low, T high)
{
Assert.InRange(actual, low, high);
}
/// <summary>
/// Verifies that a value is within a given range, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <param name="comparer">The comparer used to evaluate the value's range</param>
/// <exception cref="InRangeException">Thrown when the value is not in the given range</exception>
public void InRange<T>(T actual, T low, T high, IComparer<T> comparer)
{
Assert.InRange(actual, low, high, comparer);
}
/// <summary>
/// Verifies that an object is not exactly the given type.
/// </summary>
/// <typeparam name="T">The type the object should not be</typeparam>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsTypeException">Thrown when the object is the given type</exception>
public void IsNotType<T>(object @object)
{
Assert.IsNotType<T>(@object);
}
/// <summary>
/// Verifies that an object is not exactly the given type.
/// </summary>
/// <param name="expectedType">The type the object should not be</param>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsTypeException">Thrown when the object is the given type</exception>
public void IsNotType(Type expectedType, object @object)
{
Assert.IsNotType(expectedType, @object);
}
/// <summary>
/// Verifies that an object is exactly the given type (and not a derived type).
/// </summary>
/// <typeparam name="T">The type the object should be</typeparam>
/// <param name="object">The object to be evaluated</param>
/// <returns>The object, casted to type T when successful</returns>
/// <exception cref="IsTypeException">Thrown when the object is not the given type</exception>
public T IsType<T>(object @object)
{
return Assert.IsType<T>(@object);
}
/// <summary>
/// Verifies that an object is exactly the given type (and not a derived type).
/// </summary>
/// <param name="expectedType">The type the object should be</param>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsTypeException">Thrown when the object is not the given type</exception>
public void IsType(Type expectedType, object @object)
{
Assert.IsType(expectedType, @object);
}
/// <summary>Verifies that an object is less than the exclusive maximum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="value">The object to be evaluated.</param>
/// <param name="maxValue">An object representing the exclusive maximum value of paramref name="value"/>.</param>
public static void LessThan<T>(T value, T maxValue)
{
Assert.LessThan(value, maxValue);
}
/// <summary>Verifies that an object is less than the exclusive maximum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="value">The object to be evaluated.</param>
/// <param name="maxValue">An object representing the exclusive maximum value of paramref name="value"/>.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param>
public static void LessThan<T>(T value, T maxValue, IComparer<T> comparer)
{
Assert.LessThan(value, maxValue, comparer);
}
/// <summary>Verifies that an object is less than the inclusive maximum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="value">The object to be evaluated.</param>
/// <param name="maxValue">An object representing the inclusive maximum value of paramref name="value"/>.</param>
public static void LessThanOrEqual<T>(T value, T maxValue)
{
Assert.LessThanOrEqual(value, maxValue);
}
/// <summary>Verifies that an object is less than the inclusive maximum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="value">The object to be evaluated.</param>
/// <param name="maxValue">An object representing the inclusive maximum value of paramref name="value"/>.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param>
public static void LessThanOrEqual<T>(T value, T maxValue, IComparer<T> comparer)
{
Assert.LessThanOrEqual(value, maxValue, comparer);
}
/// <summary>
/// Verifies that a collection is not empty.
/// </summary>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="ArgumentNullException">Thrown when a null collection is passed</exception>
/// <exception cref="NotEmptyException">Thrown when the collection is empty</exception>
public void NotEmpty(IEnumerable collection)
{
Assert.NotEmpty(collection);
}
/// <summary>
/// Verifies that two objects are not equal, using a default comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected object</param>
/// <param name="actual">The actual object</param>
/// <exception cref="NotEqualException">Thrown when the objects are equal</exception>
public void NotEqual<T>(T expected, T actual)
{
Assert.NotEqual(expected, actual);
}
/// <summary>
/// Verifies that two objects are not equal, using a custom comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected object</param>
/// <param name="actual">The actual object</param>
/// <param name="comparer">The comparer used to examine the objects</param>
/// <exception cref="NotEqualException">Thrown when the objects are equal</exception>
public void NotEqual<T>(T expected, T actual, IEqualityComparer<T> comparer)
{
Assert.NotEqual(expected, actual, comparer);
}
/// <summary>
/// Verifies that a value is not within a given range, using the default comparer.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception>
public void NotInRange<T>(T actual, T low, T high)
{
Assert.NotInRange(actual, low, high);
}
/// <summary>
/// Verifies that a value is not within a given range, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <param name="comparer">The comparer used to evaluate the value's range</param>
/// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception>
public void NotInRange<T>(T actual, T low, T high, IComparer<T> comparer)
{
Assert.NotInRange(actual, low, high, comparer);
}
/// <summary>
/// Verifies that an object reference is not null.
/// </summary>
/// <param name="object">The object to be validated</param>
/// <exception cref="NotNullException">Thrown when the object is not null</exception>
public void NotNull(object @object)
{
Assert.NotNull(@object);
}
/// <summary>
/// Verifies that two objects are not the same instance.
/// </summary>
/// <param name="expected">The expected object instance</param>
/// <param name="actual">The actual object instance</param>
/// <exception cref="NotSameException">Thrown when the objects are the same instance</exception>
public void NotSame(object expected, object actual)
{
Assert.NotSame(expected, actual);
}
/// <summary>
/// Verifies that an object reference is null.
/// </summary>
/// <param name="object">The object to be inspected</param>
/// <exception cref="NullException">Thrown when the object reference is not null</exception>
public void Null(object @object)
{
Assert.Null(@object);
}
/// <summary>
/// Verifies that two objects are the same instance.
/// </summary>
/// <param name="expected">The expected object instance</param>
/// <param name="actual">The actual object instance</param>
/// <exception cref="SameException">Thrown when the objects are not the same instance</exception>
public void Same(object expected, object actual)
{
Assert.Same(expected, actual);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// </summary>
/// <typeparam name="T">The type of the exception expected to be thrown</typeparam>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public T Throws<T>(Assert.ThrowsDelegate testCode)
where T : Exception
{
return Assert.Throws<T>(testCode);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// </summary>
/// <typeparam name="T">The type of the exception expected to be thrown</typeparam>
/// <param name="userMessage">The message to be shown if the test fails</param>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public T Throws<T>(string userMessage, Assert.ThrowsDelegate testCode)
where T : Exception
{
return Assert.Throws<T>(userMessage, testCode);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// </summary>
/// <param name="exceptionType">The type of the exception expected to be thrown</param>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public Exception Throws(Type exceptionType, Assert.ThrowsDelegate testCode)
{
return Assert.Throws(exceptionType, testCode);
}
/// <summary>
/// Verifies that an expression is true.
/// </summary>
/// <param name="condition">The condition to be inspected</param>
/// <exception cref="TrueException">Thrown when the condition is false</exception>
public void True(bool condition)
{
Assert.True(condition);
}
/// <summary>
/// Verifies that an expression is true.
/// </summary>
/// <param name="condition">The condition to be inspected</param>
/// <param name="userMessage">The message to be shown when the condition is false</param>
/// <exception cref="TrueException">Thrown when the condition is false</exception>
public void True(bool condition, string userMessage)
{
Assert.True(condition, userMessage);
}
}
}
| |
using System;
using System.Collections.Generic;
using Cake.Core;
using Cake.Core.Annotations;
using Cake.Core.IO;
namespace Cake.AndroidAdb
{
/// <summary>
/// Cake build aliases for Android ADB Package Manager commands
/// </summary>
[CakeAliasCategory ("Android")]
public static class PackageManagerAliases
{
static AdbTool GetAdbTool(ICakeContext context)
{
return new AdbTool(context, context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);
}
/// <summary>
/// Gets a list of packages from the target.
/// </summary>
/// <returns>The list of packages.</returns>
/// <param name="context">Context.</param>
/// <param name="includeUninstalled">If set to <c>true</c> include uninstalled packages.</param>
/// <param name="showState">Show All by default, or choose to show only enabled or disabled packages.</param>
/// <param name="showSource">Show All by default, or choose to show only System or 3rd party packages.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static List<AdbPackageListInfo> PmListPackages(this ICakeContext context, bool includeUninstalled = false, PackageListState showState = PackageListState.All, PackageSourceType showSource = PackageSourceType.All, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
return t.ListPackages(includeUninstalled, showState, showSource, settings);
}
/// <summary>
/// Gets a list of Permission Groups on the target.
/// </summary>
/// <returns>The list of permission groups.</returns>
/// <param name="context">Context.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static List<string> PmListPermissionGroups(this ICakeContext context, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
return t.ListPermissionGroups(settings);
}
/// <summary>
/// Gets a list of Permissions, grouped by Permission Group on the target
/// </summary>
/// <returns>The list of Permissions grouped by Permission Group.</returns>
/// <param name="context">Context.</param>
/// <param name="onlyDangerous">If set to <c>true</c> return only permissions marked dangerous.</param>
/// <param name="onlyUserVisible">If set to <c>true</c> return only permissions visible to the user.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static List<AdbPermissionGroupInfo> PmListPermissions(this ICakeContext context, bool onlyDangerous = false, bool onlyUserVisible = false, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
return t.ListPermissions(onlyDangerous, onlyUserVisible, settings);
}
/// <summary>
/// Gets a list of features implemented on the target.
/// </summary>
/// <returns>The list of features.</returns>
/// <param name="context">Context.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static List<string> PmListFeatures(this ICakeContext context, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
return t.ListFeatures(settings);
}
/// <summary>
/// Gets a list of libraries that exist on the target.
/// </summary>
/// <returns>The list of libraries.</returns>
/// <param name="context">Context.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static List<string> PmListLibraries(this ICakeContext context, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
return t.ListLibraries(settings);
}
/// <summary>
/// Gets the path for a given package name.
/// </summary>
/// <returns>The path to package.</returns>
/// <param name="context">Context.</param>
/// <param name="packageName">Package name.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static FilePath PmPathToPackage(this ICakeContext context, string packageName, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
return t.PathToPackage(packageName, settings);
}
/// <summary>
/// Installs an APK file from the given path on the target.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="pathOnDevice">Path of the APK to install on the target.</param>
/// <param name="forwardLock">If set to <c>true</c> install the package with a forward lock.</param>
/// <param name="reinstall">If set to <c>true</c> reinstall the package, keeping its data.</param>
/// <param name="allowTestApks">If set to <c>true</c> allow test APKs to be installed.</param>
/// <param name="installerPackageName">Installer package name.</param>
/// <param name="installOnSharedStorage">If set to <c>true</c> install on shared storage.</param>
/// <param name="installOnInternalSystemMemory">If set to <c>true</c> install on internal system memory.</param>
/// <param name="allowVersionDowngrade">If set to <c>true</c> allow version downgrade.</param>
/// <param name="grantAllManifestPermissions">If set to <c>true</c> grant all manifest permissions.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmInstall(this ICakeContext context,
FilePath pathOnDevice,
bool forwardLock = false,
bool reinstall = false,
bool allowTestApks = false,
string installerPackageName = null,
bool installOnSharedStorage = false,
bool installOnInternalSystemMemory = false,
bool allowVersionDowngrade = false,
bool grantAllManifestPermissions = false,
AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.Install(pathOnDevice, forwardLock, reinstall, allowTestApks, installerPackageName, installOnSharedStorage, installOnInternalSystemMemory, allowVersionDowngrade, grantAllManifestPermissions, settings);
}
/// <summary>
/// Uninstalls a package from the target
/// </summary>
/// <param name="context">Context.</param>
/// <param name="packageName">Package name.</param>
/// <param name="keepDataAndCache">If set to <c>true</c> keep data and cache.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmUninstall(this ICakeContext context, string packageName, bool keepDataAndCache = false, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.Uninstall(packageName, keepDataAndCache, settings);
}
/// <summary>
/// Clears all data associated with the package.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="packageName">Package name.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmClear(this ICakeContext context, string packageName, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.Clear(packageName, settings);
}
/// <summary>
/// Enables the given package or component
/// </summary>
/// <param name="context">Context.</param>
/// <param name="packageOrComponent">Package or component (written as "package/class").</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmEnable(this ICakeContext context, string packageOrComponent, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.Enable(packageOrComponent, settings);
}
/// <summary>
/// Disables the given package or component
/// </summary>
/// <param name="context">Context.</param>
/// <param name="packageOrComponent">Package or component (written as "package/class").</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmDisable(this ICakeContext context, string packageOrComponent, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.Disable(packageOrComponent, settings);
}
/// <summary>
/// Disables a user for the given package or component.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="packageOrComponent">Package or component (written as "package/class").</param>
/// <param name="forUser">For user.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmDisableUser(this ICakeContext context, string packageOrComponent, string forUser = null, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.DisableUser(packageOrComponent, forUser, settings);
}
/// <summary>
/// Grants a permission to a package.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="packageName">Package name.</param>
/// <param name="permission">Permission.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmGrant(this ICakeContext context, string packageName, string permission, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.Grant(packageName, permission, settings);
}
/// <summary>
/// Revokes a permission from a package.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="packageName">Package name.</param>
/// <param name="permission">Permission.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmRevoke(this ICakeContext context, string packageName, string permission, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.Revoke(packageName, permission, settings);
}
/// <summary>
/// Sets the default install location for the target. Note: This is only intended for debugging; using this can cause applications to break and other undesireable behavior.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="location">Location.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmSetInstallLocation(this ICakeContext context, AdbInstallLocation location, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.SetInstallLocation(location, settings);
}
/// <summary>
/// Gets the current default install location for the target.
/// </summary>
/// <returns>The get install location.</returns>
/// <param name="context">Context.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static AdbInstallLocation PmGetInstallLocation(this ICakeContext context, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
return t.GetInstallLocation(settings);
}
/// <summary>
/// Sets whether or not a permission is enforced on the target.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="permission">Permission.</param>
/// <param name="enforced">If set to <c>true</c> enforced.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmSetPermissionEnforced(this ICakeContext context, string permission, bool enforced, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.SetPermissionEnforced(permission, enforced, settings);
}
/// <summary>
/// Tries to free up space on the target by deleting caches.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="desiredFreeSpace">Desired free space to trim.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmTrimCaches(this ICakeContext context, string desiredFreeSpace, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.TrimCaches(desiredFreeSpace, settings);
}
/// <summary>
/// Creates a new user on the target.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="userName">User name.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmCreateUser(this ICakeContext context, string userName, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.CreateUser(userName, settings);
}
/// <summary>
/// Removes a user from a target.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="userId">User identifier.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static void PmRemoveUser(this ICakeContext context, string userId, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
t.RemoveUser(userId, settings);
}
/// <summary>
/// Gets the max # of users the target supports.
/// </summary>
/// <returns>The get max users.</returns>
/// <param name="context">Context.</param>
/// <param name="settings">Settings.</param>
[CakeMethodAlias]
public static int PmGetMaxUsers(this ICakeContext context, AdbToolSettings settings = null)
{
var t = GetAdbTool(context);
return t.GetMaxUsers(settings);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.IsolatedStorage
{
public class IsolatedStorageFileStream : FileStream
{
private const string BackSlash = "\\";
private const int DefaultBufferSize = 1024;
private FileStream _fs;
private IsolatedStorageFile _isf;
private string _givenPath;
private string _fullPath;
public IsolatedStorageFileStream(string path, FileMode mode)
: this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, null)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, IsolatedStorageFile isf)
: this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, isf)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access)
: this(path, mode, access, access == FileAccess.Read ? FileShare.Read : FileShare.None, DefaultBufferSize, null)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, IsolatedStorageFile isf)
: this(path, mode, access, access == FileAccess.Read ? FileShare.Read : FileShare.None, DefaultBufferSize, isf)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share)
: this(path, mode, access, share, DefaultBufferSize, null)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, IsolatedStorageFile isf)
: this(path, mode, access, share, DefaultBufferSize, isf)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
: this(path, mode, access, share, bufferSize, null)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf)
: this(path, mode, access, share, bufferSize, InitializeFileStream(path, mode, access, share, bufferSize, isf))
{
}
// On NetFX FileStream has an internal no arg constructor that we utilize to provide the facade. We don't have access
// to internals in CoreFX so we'll do the next best thing and contort ourselves into the SafeFileHandle constructor.
// (A path constructor would try and create the requested file and give us two open handles.)
//
// We only expose our own nested FileStream so the base class having a handle doesn't matter. Passing a new SafeFileHandle
// with ownsHandle: false avoids the parent class closing without our knowledge.
private IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, InitialiationData initializationData)
: base(new SafeFileHandle(initializationData.NestedStream.SafeFileHandle.DangerousGetHandle(), ownsHandle: false), access, bufferSize)
{
_isf = initializationData.StorageFile;
_givenPath = path;
_fullPath = initializationData.FullPath;
_fs = initializationData.NestedStream;
}
private struct InitialiationData
{
public FileStream NestedStream;
public IsolatedStorageFile StorageFile;
public string FullPath;
}
// If IsolatedStorageFile is null, then we default to using a file that is scoped by user, appdomain, and assembly.
private static InitialiationData InitializeFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if ((path.Length == 0) || path.Equals(BackSlash))
throw new ArgumentException(
SR.IsolatedStorage_Path);
bool createdStore = false;
if (isf == null)
{
isf = IsolatedStorageFile.GetUserStoreForDomain();
createdStore = true;
}
if (isf.Disposed)
throw new ObjectDisposedException(null, SR.IsolatedStorage_StoreNotOpen);
switch (mode)
{
case FileMode.CreateNew: // Assume new file
case FileMode.Create: // Check for New file & Unreserve
case FileMode.OpenOrCreate: // Check for new file
case FileMode.Truncate: // Unreserve old file size
case FileMode.Append: // Check for new file
case FileMode.Open: // Open existing, else exception
break;
default:
throw new ArgumentException(SR.IsolatedStorage_FileOpenMode);
}
InitialiationData data = new InitialiationData
{
FullPath = isf.GetFullPath(path),
StorageFile = isf
};
try
{
data.NestedStream = new FileStream(data.FullPath, mode, access, share, bufferSize, FileOptions.None);
}
catch (Exception e)
{
// Make an attempt to clean up the StorageFile if we created it
try
{
if (createdStore)
{
data.StorageFile?.Dispose();
}
}
catch
{
}
// Exception message might leak the IsolatedStorage path. The desktop prevented this by calling an
// internal API which made sure that the exception message was scrubbed. However since the innerException
// is never returned to the user(GetIsolatedStorageException() does not populate the innerexception
// in retail bits we leak the path only under the debugger via IsolatedStorageException._underlyingException which
// they can any way look at via IsolatedStorageFile instance as well.
throw IsolatedStorageFile.GetIsolatedStorageException(SR.IsolatedStorage_Operation_ISFS, e);
}
return data;
}
public override bool CanRead
{
get
{
return _fs.CanRead;
}
}
public override bool CanWrite
{
get
{
return _fs.CanWrite;
}
}
public override bool CanSeek
{
get
{
return _fs.CanSeek;
}
}
public override long Length
{
get
{
return _fs.Length;
}
}
public override long Position
{
get
{
return _fs.Position;
}
set
{
_fs.Position = value;
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_fs != null)
_fs.Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
public override void Flush()
{
_fs.Flush();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return _fs.FlushAsync();
}
public override void SetLength(long value)
{
_fs.SetLength(value);
}
public override int Read(byte[] buffer, int offset, int count)
{
return _fs.Read(buffer, offset, count);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, Threading.CancellationToken cancellationToken)
{
return _fs.ReadAsync(buffer, offset, count, cancellationToken);
}
public override int ReadByte()
{
return _fs.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin)
{
// Desktop implementation of IsolatedStorage ensures that in case the size is increased the new memory is zero'ed out.
// However in this implementation we simply call the FileStream.Seek APIs which have an undefined behavior.
return _fs.Seek(offset, origin);
}
public override void Write(byte[] buffer, int offset, int count)
{
_fs.Write(buffer, offset, count);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _fs.WriteAsync(buffer, offset, count, cancellationToken);
}
public override void WriteByte(byte value)
{
_fs.WriteByte(value);
}
public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
{
return _fs.BeginRead(array, offset, numBytes, userCallback, stateObject);
}
public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
{
return _fs.BeginWrite(array, offset, numBytes, userCallback, stateObject);
}
public override int EndRead(IAsyncResult asyncResult)
{
return _fs.EndRead(asyncResult);
}
public override void EndWrite(IAsyncResult asyncResult)
{
_fs.EndWrite(asyncResult);
}
[Obsolete("This property has been deprecated. Please use IsolatedStorageFileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public override IntPtr Handle
{
get { return _fs.Handle; }
}
public override void Unlock(long position, long length)
{
_fs.Unlock(position, length);
}
public override void Lock(long position, long length)
{
_fs.Lock(position, 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;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Globalization;
using System.Security;
using System.Reflection;
using System.Runtime.Versioning;
namespace System.Xml
{
internal sealed class DocumentSchemaValidator : IXmlNamespaceResolver
{
private XmlSchemaValidator _validator;
private XmlSchemaSet _schemas;
private XmlNamespaceManager _nsManager;
private XmlNameTable _nameTable;
//Attributes
private ArrayList _defaultAttributes;
private XmlValueGetter _nodeValueGetter;
private XmlSchemaInfo _attributeSchemaInfo;
//Element PSVI
private XmlSchemaInfo _schemaInfo;
//Event Handler
private ValidationEventHandler _eventHandler;
private ValidationEventHandler _internalEventHandler;
//Store nodes
private XmlNode _startNode;
private XmlNode _currentNode;
private XmlDocument _document;
//List of nodes for partial validation tree walk
private XmlNode[] _nodeSequenceToValidate;
private bool _isPartialTreeValid;
private bool _psviAugmentation;
private bool _isValid;
//To avoid SchemaNames creation
private string _nsXmlNs;
private string _nsXsi;
private string _xsiType;
private string _xsiNil;
public DocumentSchemaValidator(XmlDocument ownerDocument, XmlSchemaSet schemas, ValidationEventHandler eventHandler)
{
_schemas = schemas;
_eventHandler = eventHandler;
_document = ownerDocument;
_internalEventHandler = new ValidationEventHandler(InternalValidationCallBack);
_nameTable = _document.NameTable;
_nsManager = new XmlNamespaceManager(_nameTable);
Debug.Assert(schemas != null && schemas.Count > 0);
_nodeValueGetter = new XmlValueGetter(GetNodeValue);
_psviAugmentation = true;
//Add common strings to be compared to NameTable
_nsXmlNs = _nameTable.Add(XmlReservedNs.NsXmlNs);
_nsXsi = _nameTable.Add(XmlReservedNs.NsXsi);
_xsiType = _nameTable.Add("type");
_xsiNil = _nameTable.Add("nil");
}
public bool PsviAugmentation
{
get { return _psviAugmentation; }
set { _psviAugmentation = value; }
}
public bool Validate(XmlNode nodeToValidate)
{
XmlSchemaObject partialValidationType = null;
XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.AllowXmlAttributes;
Debug.Assert(nodeToValidate.SchemaInfo != null);
_startNode = nodeToValidate;
switch (nodeToValidate.NodeType)
{
case XmlNodeType.Document:
validationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
break;
case XmlNodeType.DocumentFragment:
break;
case XmlNodeType.Element: //Validate children of this element
IXmlSchemaInfo schemaInfo = nodeToValidate.SchemaInfo;
XmlSchemaElement schemaElement = schemaInfo.SchemaElement;
if (schemaElement != null)
{
if (!schemaElement.RefName.IsEmpty)
{ //If it is element ref,
partialValidationType = _schemas.GlobalElements[schemaElement.QualifiedName]; //Get Global element with correct Nillable, Default etc
}
else
{ //local element
partialValidationType = schemaElement;
}
//Verify that if there was xsi:type, the schemaElement returned has the correct type set
Debug.Assert(schemaElement.ElementSchemaType == schemaInfo.SchemaType);
}
else
{ //Can be an element that matched xs:any and had xsi:type
partialValidationType = schemaInfo.SchemaType;
if (partialValidationType == null)
{ //Validated against xs:any with pc= lax or skip or undeclared / not validated element
if (nodeToValidate.ParentNode.NodeType == XmlNodeType.Document)
{
//If this is the documentElement and it has not been validated at all
nodeToValidate = nodeToValidate.ParentNode;
}
else
{
partialValidationType = FindSchemaInfo(nodeToValidate as XmlElement);
if (partialValidationType == null)
{
throw new XmlSchemaValidationException(SR.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
}
}
}
}
break;
case XmlNodeType.Attribute:
if (nodeToValidate.XPNodeType == XPathNodeType.Namespace) goto default;
partialValidationType = nodeToValidate.SchemaInfo.SchemaAttribute;
if (partialValidationType == null)
{ //Validated against xs:anyAttribute with pc = lax or skip / undeclared attribute
partialValidationType = FindSchemaInfo(nodeToValidate as XmlAttribute);
if (partialValidationType == null)
{
throw new XmlSchemaValidationException(SR.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
}
}
break;
default:
throw new InvalidOperationException(SR.Format(SR.XmlDocument_ValidateInvalidNodeType, null));
}
_isValid = true;
CreateValidator(partialValidationType, validationFlags);
if (_psviAugmentation)
{
if (_schemaInfo == null)
{ //Might have created it during FindSchemaInfo
_schemaInfo = new XmlSchemaInfo();
}
_attributeSchemaInfo = new XmlSchemaInfo();
}
ValidateNode(nodeToValidate);
_validator.EndValidation();
return _isValid;
}
public IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
IDictionary<string, string> dictionary = _nsManager.GetNamespacesInScope(scope);
if (scope != XmlNamespaceScope.Local)
{
XmlNode node = _startNode;
while (node != null)
{
switch (node.NodeType)
{
case XmlNodeType.Element:
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute attr = attrs[i];
if (Ref.Equal(attr.NamespaceURI, _document.strReservedXmlns))
{
if (attr.Prefix.Length == 0)
{
// xmlns='' declaration
if (!dictionary.ContainsKey(string.Empty))
{
dictionary.Add(string.Empty, attr.Value);
}
}
else
{
// xmlns:prefix='' declaration
if (!dictionary.ContainsKey(attr.LocalName))
{
dictionary.Add(attr.LocalName, attr.Value);
}
}
}
}
}
node = node.ParentNode;
break;
case XmlNodeType.Attribute:
node = ((XmlAttribute)node).OwnerElement;
break;
default:
node = node.ParentNode;
break;
}
}
}
return dictionary;
}
public string LookupNamespace(string prefix)
{
string namespaceName = _nsManager.LookupNamespace(prefix);
if (namespaceName == null)
{
namespaceName = _startNode.GetNamespaceOfPrefixStrict(prefix);
}
return namespaceName;
}
public string LookupPrefix(string namespaceName)
{
string prefix = _nsManager.LookupPrefix(namespaceName);
if (prefix == null)
{
prefix = _startNode.GetPrefixOfNamespaceStrict(namespaceName);
}
return prefix;
}
private IXmlNamespaceResolver NamespaceResolver
{
get
{
if ((object)_startNode == (object)_document)
{
return _nsManager;
}
return this;
}
}
private void CreateValidator(XmlSchemaObject partialValidationType, XmlSchemaValidationFlags validationFlags)
{
_validator = new XmlSchemaValidator(_nameTable, _schemas, NamespaceResolver, validationFlags);
_validator.SourceUri = XmlConvert.ToUri(_document.BaseURI);
_validator.XmlResolver = null;
_validator.ValidationEventHandler += _internalEventHandler;
_validator.ValidationEventSender = this;
if (partialValidationType != null)
{
_validator.Initialize(partialValidationType);
}
else
{
_validator.Initialize();
}
}
private void ValidateNode(XmlNode node)
{
_currentNode = node;
switch (_currentNode.NodeType)
{
case XmlNodeType.Document:
XmlElement docElem = ((XmlDocument)node).DocumentElement;
if (docElem == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_InvalidXmlDocument, SR.Xdom_NoRootEle));
}
ValidateNode(docElem);
break;
case XmlNodeType.DocumentFragment:
case XmlNodeType.EntityReference:
for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling)
{
ValidateNode(child);
}
break;
case XmlNodeType.Element:
ValidateElement();
break;
case XmlNodeType.Attribute: //Top-level attribute
XmlAttribute attr = _currentNode as XmlAttribute;
_validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, _nodeValueGetter, _attributeSchemaInfo);
if (_psviAugmentation)
{
attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo);
}
break;
case XmlNodeType.Text:
_validator.ValidateText(_nodeValueGetter);
break;
case XmlNodeType.CDATA:
_validator.ValidateText(_nodeValueGetter);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(_nodeValueGetter);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
default:
throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, new string[] { _currentNode.NodeType.ToString() }));
}
}
// SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute.
// Since the resource names passed to ValidateElement method are null and the function does not expose any resources
// it is fine to suppress the SxS warning.
private void ValidateElement()
{
_nsManager.PushScope();
XmlElement elementNode = _currentNode as XmlElement;
Debug.Assert(elementNode != null);
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
//Find Xsi attributes that need to be processed before validating the element
string xsiNil = null;
string xsiType = null;
for (int i = 0; i < attributes.Count; i++)
{
attr = attributes[i];
string objectNs = attr.NamespaceURI;
string objectName = attr.LocalName;
Debug.Assert(_nameTable.Get(attr.NamespaceURI) != null);
Debug.Assert(_nameTable.Get(attr.LocalName) != null);
if (Ref.Equal(objectNs, _nsXsi))
{
if (Ref.Equal(objectName, _xsiType))
{
xsiType = attr.Value;
}
else if (Ref.Equal(objectName, _xsiNil))
{
xsiNil = attr.Value;
}
}
else if (Ref.Equal(objectNs, _nsXmlNs))
{
_nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
}
}
_validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo, xsiType, xsiNil, null, null);
ValidateAttributes(elementNode);
_validator.ValidateEndOfAttributes(_schemaInfo);
//If element has children, drill down
for (XmlNode child = elementNode.FirstChild; child != null; child = child.NextSibling)
{
ValidateNode(child);
}
//Validate end of element
_currentNode = elementNode; //Reset current Node for validation call back
_validator.ValidateEndElement(_schemaInfo);
//Get XmlName, as memberType / validity might be set now
if (_psviAugmentation)
{
elementNode.XmlName = _document.AddXmlName(elementNode.Prefix, elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo);
if (_schemaInfo.IsDefault)
{ //the element has a default value
XmlText textNode = _document.CreateTextNode(_schemaInfo.SchemaElement.ElementDecl.DefaultValueRaw);
elementNode.AppendChild(textNode);
}
}
_nsManager.PopScope(); //Pop current namespace scope
}
private void ValidateAttributes(XmlElement elementNode)
{
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
for (int i = 0; i < attributes.Count; i++)
{
attr = attributes[i];
_currentNode = attr; //For nodeValueGetter to pick up the right attribute value
if (Ref.Equal(attr.NamespaceURI, _nsXmlNs))
{ //Do not validate namespace decls
continue;
}
_validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, _nodeValueGetter, _attributeSchemaInfo);
if (_psviAugmentation)
{
attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo);
}
}
if (_psviAugmentation)
{
//Add default attributes to the attributes collection
if (_defaultAttributes == null)
{
_defaultAttributes = new ArrayList();
}
else
{
_defaultAttributes.Clear();
}
_validator.GetUnspecifiedDefaultAttributes(_defaultAttributes);
XmlSchemaAttribute schemaAttribute = null;
XmlQualifiedName attrQName;
attr = null;
for (int i = 0; i < _defaultAttributes.Count; i++)
{
schemaAttribute = _defaultAttributes[i] as XmlSchemaAttribute;
attrQName = schemaAttribute.QualifiedName;
Debug.Assert(schemaAttribute != null);
attr = _document.CreateDefaultAttribute(GetDefaultPrefix(attrQName.Namespace), attrQName.Name, attrQName.Namespace);
SetDefaultAttributeSchemaInfo(schemaAttribute);
attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo);
attr.AppendChild(_document.CreateTextNode(schemaAttribute.AttDef.DefaultValueRaw));
attributes.Append(attr);
XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute;
if (defAttr != null)
{
defAttr.SetSpecified(false);
}
}
}
}
private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute)
{
Debug.Assert(_attributeSchemaInfo != null);
_attributeSchemaInfo.Clear();
_attributeSchemaInfo.IsDefault = true;
_attributeSchemaInfo.IsNil = false;
_attributeSchemaInfo.SchemaType = schemaAttribute.AttributeSchemaType;
_attributeSchemaInfo.SchemaAttribute = schemaAttribute;
//Get memberType for default attribute
SchemaAttDef attributeDef = schemaAttribute.AttDef;
if (attributeDef.Datatype.Variety == XmlSchemaDatatypeVariety.Union)
{
XsdSimpleValue simpleValue = attributeDef.DefaultValueTyped as XsdSimpleValue;
Debug.Assert(simpleValue != null);
_attributeSchemaInfo.MemberType = simpleValue.XmlType;
}
_attributeSchemaInfo.Validity = XmlSchemaValidity.Valid;
}
private string GetDefaultPrefix(string attributeNS)
{
IDictionary<string, string> namespaceDecls = NamespaceResolver.GetNamespacesInScope(XmlNamespaceScope.All);
string defaultPrefix = null;
string defaultNS;
attributeNS = _nameTable.Add(attributeNS); //atomize ns
foreach (KeyValuePair<string, string> pair in namespaceDecls)
{
defaultNS = _nameTable.Add(pair.Value);
if (object.ReferenceEquals(defaultNS, attributeNS))
{
defaultPrefix = pair.Key;
if (defaultPrefix.Length != 0)
{ //Locate first non-empty prefix
return defaultPrefix;
}
}
}
return defaultPrefix;
}
private object GetNodeValue()
{
return _currentNode.Value;
}
//Code for finding type during partial validation
private XmlSchemaObject FindSchemaInfo(XmlElement elementToValidate)
{
_isPartialTreeValid = true;
Debug.Assert(elementToValidate.ParentNode.NodeType != XmlNodeType.Document); //Handle if it is the documentElement separately
//Create nodelist to navigate down again
XmlNode currentNode = elementToValidate;
IXmlSchemaInfo parentSchemaInfo = null;
int nodeIndex = 0;
//Check common case of parent node first
XmlNode parentNode = currentNode.ParentNode;
do
{
parentSchemaInfo = parentNode.SchemaInfo;
if (parentSchemaInfo.SchemaElement != null || parentSchemaInfo.SchemaType != null)
{
break; //Found ancestor with schemaInfo
}
CheckNodeSequenceCapacity(nodeIndex);
_nodeSequenceToValidate[nodeIndex++] = parentNode;
parentNode = parentNode.ParentNode;
} while (parentNode != null);
if (parentNode == null)
{ //Did not find any type info all the way to the root, currentNode is Document || DocumentFragment
nodeIndex = nodeIndex - 1; //Subtract the one for document and set the node to null
_nodeSequenceToValidate[nodeIndex] = null;
return GetTypeFromAncestors(elementToValidate, null, nodeIndex);
}
else
{
//Start validating down from the parent or ancestor that has schema info and shallow validate all previous siblings
//to correctly ascertain particle for current node
CheckNodeSequenceCapacity(nodeIndex);
_nodeSequenceToValidate[nodeIndex++] = parentNode;
XmlSchemaObject ancestorSchemaObject = parentSchemaInfo.SchemaElement;
if (ancestorSchemaObject == null)
{
ancestorSchemaObject = parentSchemaInfo.SchemaType;
}
return GetTypeFromAncestors(elementToValidate, ancestorSchemaObject, nodeIndex);
}
}
/*private XmlSchemaElement GetTypeFromParent(XmlElement elementToValidate, XmlSchemaComplexType parentSchemaType) {
XmlQualifiedName elementName = new XmlQualifiedName(elementToValidate.LocalName, elementToValidate.NamespaceURI);
XmlSchemaElement elem = parentSchemaType.LocalElements[elementName] as XmlSchemaElement;
if (elem == null) { //Element not found as direct child of the content model. It might be invalid at this position or it might be a substitution member
SchemaInfo compiledSchemaInfo = schemas.CompiledInfo;
XmlSchemaElement memberElem = compiledSchemaInfo.GetElement(elementName);
if (memberElem != null) {
}
}
}*/
private void CheckNodeSequenceCapacity(int currentIndex)
{
if (_nodeSequenceToValidate == null)
{ //Normally users would call Validate one level down, this allows for 4
_nodeSequenceToValidate = new XmlNode[4];
}
else if (currentIndex >= _nodeSequenceToValidate.Length - 1)
{ //reached capacity of array, Need to increase capacity to twice the initial
XmlNode[] newNodeSequence = new XmlNode[_nodeSequenceToValidate.Length * 2];
Array.Copy(_nodeSequenceToValidate, 0, newNodeSequence, 0, _nodeSequenceToValidate.Length);
_nodeSequenceToValidate = newNodeSequence;
}
}
private XmlSchemaAttribute FindSchemaInfo(XmlAttribute attributeToValidate)
{
XmlElement parentElement = attributeToValidate.OwnerElement;
XmlSchemaObject schemaObject = FindSchemaInfo(parentElement);
XmlSchemaComplexType elementSchemaType = GetComplexType(schemaObject);
if (elementSchemaType == null)
{
return null;
}
XmlQualifiedName attName = new XmlQualifiedName(attributeToValidate.LocalName, attributeToValidate.NamespaceURI);
XmlSchemaAttribute schemaAttribute = elementSchemaType.AttributeUses[attName] as XmlSchemaAttribute;
if (schemaAttribute == null)
{
XmlSchemaAnyAttribute anyAttribute = elementSchemaType.AttributeWildcard;
if (anyAttribute != null)
{
if (anyAttribute.NamespaceList.Allows(attName))
{ //Match wildcard against global attribute
schemaAttribute = _schemas.GlobalAttributes[attName] as XmlSchemaAttribute;
}
}
}
return schemaAttribute;
}
private XmlSchemaObject GetTypeFromAncestors(XmlElement elementToValidate, XmlSchemaObject ancestorType, int ancestorsCount)
{
//schemaInfo is currentNode's schemaInfo
_validator = CreateTypeFinderValidator(ancestorType);
_schemaInfo = new XmlSchemaInfo();
//start at the ancestor to start validating
int startIndex = ancestorsCount - 1;
bool ancestorHasWildCard = AncestorTypeHasWildcard(ancestorType);
for (int i = startIndex; i >= 0; i--)
{
XmlNode node = _nodeSequenceToValidate[i];
XmlElement currentElement = node as XmlElement;
ValidateSingleElement(currentElement, false, _schemaInfo);
if (!ancestorHasWildCard)
{ //store type if ancestor does not have wildcard in its content model
currentElement.XmlName = _document.AddXmlName(currentElement.Prefix, currentElement.LocalName, currentElement.NamespaceURI, _schemaInfo);
//update wildcard flag
ancestorHasWildCard = AncestorTypeHasWildcard(_schemaInfo.SchemaElement);
}
_validator.ValidateEndOfAttributes(null);
if (i > 0)
{
ValidateChildrenTillNextAncestor(node, _nodeSequenceToValidate[i - 1]);
}
else
{ //i == 0
ValidateChildrenTillNextAncestor(node, elementToValidate);
}
}
Debug.Assert(_nodeSequenceToValidate[0] == elementToValidate.ParentNode);
//validate element whose type is needed,
ValidateSingleElement(elementToValidate, false, _schemaInfo);
XmlSchemaObject schemaInfoFound = null;
if (_schemaInfo.SchemaElement != null)
{
schemaInfoFound = _schemaInfo.SchemaElement;
}
else
{
schemaInfoFound = _schemaInfo.SchemaType;
}
if (schemaInfoFound == null)
{ //Detect if the node was validated lax or skip
if (_validator.CurrentProcessContents == XmlSchemaContentProcessing.Skip)
{
if (_isPartialTreeValid)
{ //Then node assessed as skip; if there was error we turn processContents to skip as well. But this is not the same as validating as skip.
return XmlSchemaComplexType.AnyTypeSkip;
}
}
else if (_validator.CurrentProcessContents == XmlSchemaContentProcessing.Lax)
{
return XmlSchemaComplexType.AnyType;
}
}
return schemaInfoFound;
}
private bool AncestorTypeHasWildcard(XmlSchemaObject ancestorType)
{
XmlSchemaComplexType ancestorSchemaType = GetComplexType(ancestorType);
if (ancestorType != null)
{
return ancestorSchemaType.HasWildCard;
}
return false;
}
private XmlSchemaComplexType GetComplexType(XmlSchemaObject schemaObject)
{
if (schemaObject == null)
{
return null;
}
XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
XmlSchemaComplexType complexType = null;
if (schemaElement != null)
{
complexType = schemaElement.ElementSchemaType as XmlSchemaComplexType;
}
else
{
complexType = schemaObject as XmlSchemaComplexType;
}
return complexType;
}
// SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute.
// Since the resource names passed to ValidateElement method are null and the function does not expose any resources
// it is fine to suppress the warning.
private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSchemaInfo newSchemaInfo)
{
_nsManager.PushScope();
Debug.Assert(elementNode != null);
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
//Find Xsi attributes that need to be processed before validating the element
string xsiNil = null;
string xsiType = null;
for (int i = 0; i < attributes.Count; i++)
{
attr = attributes[i];
string objectNs = attr.NamespaceURI;
string objectName = attr.LocalName;
Debug.Assert(_nameTable.Get(attr.NamespaceURI) != null);
Debug.Assert(_nameTable.Get(attr.LocalName) != null);
if (Ref.Equal(objectNs, _nsXsi))
{
if (Ref.Equal(objectName, _xsiType))
{
xsiType = attr.Value;
}
else if (Ref.Equal(objectName, _xsiNil))
{
xsiNil = attr.Value;
}
}
else if (Ref.Equal(objectNs, _nsXmlNs))
{
_nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
}
}
_validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, newSchemaInfo, xsiType, xsiNil, null, null);
//Validate end of element
if (skipToEnd)
{
_validator.ValidateEndOfAttributes(newSchemaInfo);
_validator.SkipToEndElement(newSchemaInfo);
_nsManager.PopScope(); //Pop current namespace scope
}
}
private void ValidateChildrenTillNextAncestor(XmlNode parentNode, XmlNode childToStopAt)
{
XmlNode child;
for (child = parentNode.FirstChild; child != null; child = child.NextSibling)
{
if (child == childToStopAt)
{
break;
}
switch (child.NodeType)
{
case XmlNodeType.EntityReference:
ValidateChildrenTillNextAncestor(child, childToStopAt);
break;
case XmlNodeType.Element: //Flat validation, do not drill down into children
ValidateSingleElement(child as XmlElement, true, null);
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
_validator.ValidateText(child.Value);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(child.Value);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
default:
throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, new string[] { _currentNode.NodeType.ToString() }));
}
}
Debug.Assert(child == childToStopAt);
}
private XmlSchemaValidator CreateTypeFinderValidator(XmlSchemaObject partialValidationType)
{
XmlSchemaValidator findTypeValidator = new XmlSchemaValidator(_document.NameTable, _document.Schemas, _nsManager, XmlSchemaValidationFlags.None);
findTypeValidator.ValidationEventHandler += new ValidationEventHandler(TypeFinderCallBack);
if (partialValidationType != null)
{
findTypeValidator.Initialize(partialValidationType);
}
else
{ //If we walked up to the root and no schemaInfo was there, start validating from root
findTypeValidator.Initialize();
}
return findTypeValidator;
}
private void TypeFinderCallBack(object sender, ValidationEventArgs arg)
{
if (arg.Severity == XmlSeverityType.Error)
{
_isPartialTreeValid = false;
}
}
private void InternalValidationCallBack(object sender, ValidationEventArgs arg)
{
if (arg.Severity == XmlSeverityType.Error)
{
_isValid = false;
}
XmlSchemaValidationException ex = arg.Exception as XmlSchemaValidationException;
Debug.Assert(ex != null);
ex.SetSourceObject(_currentNode);
if (_eventHandler != null)
{ //Invoke user's event handler
_eventHandler(sender, arg);
}
else if (arg.Severity == XmlSeverityType.Error)
{
throw ex;
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// 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.Runtime.CompilerServices;
namespace NLog.UnitTests
{
using System;
using NLog.Common;
using System.IO;
using System.Text;
using NLog.Layouts;
using NLog.Config;
using Xunit;
#if SILVERLIGHT
using System.Xml.Linq;
#else
using System.Xml;
using System.IO.Compression;
using System.Security.Permissions;
#endif
public abstract class NLogTestBase
{
protected NLogTestBase()
{
InternalLogger.LogToConsole = false;
InternalLogger.LogToConsoleError = false;
LogManager.ThrowExceptions = false;
}
public void AssertDebugCounter(string targetName, int val)
{
Assert.Equal(val, GetDebugTarget(targetName).Counter);
}
public void AssertDebugLastMessage(string targetName, string msg)
{
Assert.Equal(msg, GetDebugLastMessage(targetName));
}
public void AssertDebugLastMessageContains(string targetName, string msg)
{
string debugLastMessage = GetDebugLastMessage(targetName);
Assert.True(debugLastMessage.Contains(msg),
string.Format("Expected to find '{0}' in last message value on '{1}', but found '{2}'", msg, targetName, debugLastMessage));
}
public string GetDebugLastMessage(string targetName)
{
return GetDebugLastMessage(targetName, LogManager.Configuration);
}
public string GetDebugLastMessage(string targetName, LoggingConfiguration configuration)
{
return GetDebugTarget(targetName, configuration).LastMessage;
}
public NLog.Targets.DebugTarget GetDebugTarget(string targetName)
{
return GetDebugTarget(targetName, LogManager.Configuration);
}
public NLog.Targets.DebugTarget GetDebugTarget(string targetName, LoggingConfiguration configuration)
{
var debugTarget = (NLog.Targets.DebugTarget)configuration.FindTargetByName(targetName);
Assert.NotNull(debugTarget);
return debugTarget;
}
public void AssertFileContentsStartsWith(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(true, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
Assert.True(encodedBuf.Length <= fi.Length);
byte[] buf = new byte[encodedBuf.Length];
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
public void AssertFileSize(string filename, long expectedSize)
{
var fi = new FileInfo(filename);
if (!fi.Exists)
{
Assert.True(true, string.Format("File \"{0}\" doesn't exist.", filename));
}
if (fi.Length != expectedSize)
{
Assert.True(true, string.Format("Filesize of \"{0}\" unequals {1}.", filename, expectedSize));
}
}
#if NET4_5
public void AssertZipFileContents(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(true, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var zip = new ZipArchive(stream, ZipArchiveMode.Read))
{
Assert.Equal(1, zip.Entries.Count);
Assert.Equal(encodedBuf.Length, zip.Entries[0].Length);
byte[] buf = new byte[(int)zip.Entries[0].Length];
using (var fs = zip.Entries[0].Open())
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
}
#endif
public void AssertFileContents(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
Assert.Equal(encodedBuf.Length, fi.Length);
byte[] buf = new byte[(int)fi.Length];
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
public void AssertFileContains(string fileName, string contentToCheck, Encoding encoding)
{
if (contentToCheck.Contains(Environment.NewLine))
Assert.True(false, "Please use only single line string to check.");
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
using (TextReader fs = new StreamReader(fileName, encoding))
{
string line;
while ((line = fs.ReadLine()) != null)
{
if (line.Contains(contentToCheck))
return;
}
}
Assert.True(false, "File doesn't contains '" + contentToCheck + "'");
}
public string StringRepeat(int times, string s)
{
StringBuilder sb = new StringBuilder(s.Length * times);
for (int i = 0; i < times; ++i)
sb.Append(s);
return sb.ToString();
}
protected void AssertLayoutRendererOutput(Layout l, string expected)
{
l.Initialize(null);
string actual = l.Render(LogEventInfo.Create(LogLevel.Info, "loggername", "message"));
l.Close();
Assert.Equal(expected, actual);
}
#if MONO || NET4_5
/// <summary>
/// Get line number of previous line.
/// </summary>
protected int GetPrevLineNumber([CallerLineNumber] int callingFileLineNumber = 0)
{
return callingFileLineNumber - 1;
}
#else
/// <summary>
/// Get line number of previous line.
/// </summary>
protected int GetPrevLineNumber()
{
//fixed value set with #line 100000
return 100001;
}
#endif
protected XmlLoggingConfiguration CreateConfigurationFromString(string configXml)
{
#if SILVERLIGHT
XElement element = XElement.Parse(configXml);
return new XmlLoggingConfiguration(element.CreateReader(), null);
#else
XmlDocument doc = new XmlDocument();
doc.LoadXml(configXml);
return new XmlLoggingConfiguration(doc.DocumentElement, Environment.CurrentDirectory);
#endif
}
protected string RunAndCaptureInternalLog(SyncAction action, LogLevel internalLogLevel)
{
var stringWriter = new StringWriter();
var oldWriter = InternalLogger.LogWriter;
var oldLevel = InternalLogger.LogLevel;
var oldIncludeTimestamp = InternalLogger.IncludeTimestamp;
try
{
InternalLogger.LogWriter = stringWriter;
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.IncludeTimestamp = false;
action();
return stringWriter.ToString();
}
finally
{
InternalLogger.LogWriter = oldWriter;
InternalLogger.LogLevel = oldLevel;
InternalLogger.IncludeTimestamp = oldIncludeTimestamp;
}
}
public delegate void SyncAction();
public class InternalLoggerScope : IDisposable
{
private readonly string logFile;
private readonly LogLevel logLevel;
private readonly bool logToConsole;
private readonly bool includeTimestamp;
private readonly bool logToConsoleError;
private readonly LogLevel globalThreshold;
private readonly bool throwExceptions;
public InternalLoggerScope()
{
this.logFile = InternalLogger.LogFile;
this.logLevel = InternalLogger.LogLevel;
this.logToConsole = InternalLogger.LogToConsole;
this.includeTimestamp = InternalLogger.IncludeTimestamp;
this.logToConsoleError = InternalLogger.LogToConsoleError;
this.globalThreshold = LogManager.GlobalThreshold;
this.throwExceptions = LogManager.ThrowExceptions;
}
public void Dispose()
{
InternalLogger.LogFile = this.logFile;
InternalLogger.LogLevel = this.logLevel;
InternalLogger.LogToConsole = this.logToConsole;
InternalLogger.IncludeTimestamp = this.includeTimestamp;
InternalLogger.LogToConsoleError = this.logToConsoleError;
LogManager.GlobalThreshold = this.globalThreshold;
LogManager.ThrowExceptions = this.throwExceptions;
}
}
}
}
| |
// 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.Xml.Xsl.XPath;
using System.Xml.Xsl.Qil;
namespace System.Xml.Xsl.Xslt
{
using T = XmlQueryTypeFactory;
// <spec>http://www.w3.org/TR/xslt20/#dt-singleton-focus</spec>
internal enum SingletonFocusType
{
// No context set
// Used to prevent bugs
None,
// Document node of the document containing the initial context node
// Used while compiling global variables and params
InitialDocumentNode,
// Initial context node for the transformation
// Used while compiling initial apply-templates
InitialContextNode,
// Context node is specified by iterator
// Used while compiling keys
Iterator,
}
internal struct SingletonFocus : IFocus
{
private XPathQilFactory _f;
private SingletonFocusType _focusType;
private QilIterator _current;
public SingletonFocus(XPathQilFactory f)
{
_f = f;
_focusType = SingletonFocusType.None;
_current = null;
}
public void SetFocus(SingletonFocusType focusType)
{
Debug.Assert(focusType != SingletonFocusType.Iterator);
_focusType = focusType;
}
public void SetFocus(QilIterator current)
{
if (current != null)
{
_focusType = SingletonFocusType.Iterator;
_current = current;
}
else
{
_focusType = SingletonFocusType.None;
_current = null;
}
}
[Conditional("DEBUG")]
private void CheckFocus()
{
Debug.Assert(_focusType != SingletonFocusType.None, "Focus is not set, call SetFocus first");
}
public QilNode GetCurrent()
{
CheckFocus();
switch (_focusType)
{
case SingletonFocusType.InitialDocumentNode: return _f.Root(_f.XmlContext());
case SingletonFocusType.InitialContextNode: return _f.XmlContext();
default:
Debug.Assert(_focusType == SingletonFocusType.Iterator && _current != null, "Unexpected singleton focus type");
return _current;
}
}
public QilNode GetPosition()
{
CheckFocus();
return _f.Double(1);
}
public QilNode GetLast()
{
CheckFocus();
return _f.Double(1);
}
}
internal struct FunctionFocus : IFocus
{
private bool _isSet;
private QilParameter _current, _position, _last;
public void StartFocus(IList<QilNode> args, XslFlags flags)
{
Debug.Assert(!IsFocusSet, "Focus was already set");
int argNum = 0;
if ((flags & XslFlags.Current) != 0)
{
_current = (QilParameter)args[argNum++];
Debug.Assert(_current.Name.NamespaceUri == XmlReservedNs.NsXslDebug && _current.Name.LocalName == "current");
}
if ((flags & XslFlags.Position) != 0)
{
_position = (QilParameter)args[argNum++];
Debug.Assert(_position.Name.NamespaceUri == XmlReservedNs.NsXslDebug && _position.Name.LocalName == "position");
}
if ((flags & XslFlags.Last) != 0)
{
_last = (QilParameter)args[argNum++];
Debug.Assert(_last.Name.NamespaceUri == XmlReservedNs.NsXslDebug && _last.Name.LocalName == "last");
}
_isSet = true;
}
public void StopFocus()
{
Debug.Assert(IsFocusSet, "Focus was not set");
_isSet = false;
_current = _position = _last = null;
}
public bool IsFocusSet
{
get { return _isSet; }
}
public QilNode GetCurrent()
{
Debug.Assert(_current != null, "Naked current() is not expected in this function");
return _current;
}
public QilNode GetPosition()
{
Debug.Assert(_position != null, "Naked position() is not expected in this function");
return _position;
}
public QilNode GetLast()
{
Debug.Assert(_last != null, "Naked last() is not expected in this function");
return _last;
}
}
internal struct LoopFocus : IFocus
{
private XPathQilFactory _f;
private QilIterator _current, _cached, _last;
public LoopFocus(XPathQilFactory f)
{
_f = f;
_current = _cached = _last = null;
}
public void SetFocus(QilIterator current)
{
_current = current;
_cached = _last = null;
}
public bool IsFocusSet
{
get { return _current != null; }
}
public QilNode GetCurrent()
{
return _current;
}
public QilNode GetPosition()
{
return _f.XsltConvert(_f.PositionOf(_current), T.DoubleX);
}
public QilNode GetLast()
{
if (_last == null)
{
// Create a let that will be fixed up later in ConstructLoop or by LastFixupVisitor
_last = _f.Let(_f.Double(0));
}
return _last;
}
public void EnsureCache()
{
if (_cached == null)
{
_cached = _f.Let(_current.Binding);
_current.Binding = _cached;
}
}
public void Sort(QilNode sortKeys)
{
if (sortKeys != null)
{
// If sorting is required, cache the input node-set to support last() within sort key expressions
EnsureCache();
// The rest of the loop content must be compiled in the context of already sorted node-set
_current = _f.For(_f.Sort(_current, sortKeys));
}
}
public QilLoop ConstructLoop(QilNode body)
{
QilLoop result;
if (_last != null)
{
// last() encountered either in the sort keys or in the body of the current loop
EnsureCache();
_last.Binding = _f.XsltConvert(_f.Length(_cached), T.DoubleX);
}
result = _f.BaseFactory.Loop(_current, body);
if (_last != null)
{
result = _f.BaseFactory.Loop(_last, result);
}
if (_cached != null)
{
result = _f.BaseFactory.Loop(_cached, result);
}
return result;
}
}
}
| |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Logging.Tracing
{
using System;
using System.Diagnostics;
using System.Globalization;
public class TraceLog :
ILog
{
readonly LogLevel _level;
readonly TraceSource _source;
public TraceLog(TraceSource source)
{
_source = source;
_level = LogLevel.FromSourceLevels(source.Switch.Level);
}
public bool IsDebugEnabled => _level >= LogLevel.Debug;
public bool IsInfoEnabled => _level >= LogLevel.Info;
public bool IsWarnEnabled => _level >= LogLevel.Warn;
public bool IsErrorEnabled => _level >= LogLevel.Error;
public bool IsFatalEnabled => _level >= LogLevel.Fatal;
public void LogFormat(LogLevel level, string format, params object[] args)
{
if (_level < level)
return;
LogInternal(level, string.Format(format, args), null);
}
/// <summary>
/// Logs a debug message.
///
/// </summary>
/// <param name="message">The message to log</param>
public void Debug(object message)
{
if (!IsDebugEnabled)
return;
Log(LogLevel.Debug, message, null);
}
/// <summary>
/// Logs a debug message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
public void Debug(object message, Exception exception)
{
if (!IsDebugEnabled)
return;
Log(LogLevel.Debug, message, exception);
}
public void Debug(LogOutputProvider messageProvider)
{
if (!IsDebugEnabled)
return;
object obj = messageProvider();
LogInternal(LogLevel.Debug, obj, null);
}
/// <summary>
/// Logs a debug message.
///
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void DebugFormat(string format, params object[] args)
{
if (!IsDebugEnabled)
return;
LogInternal(LogLevel.Debug, string.Format(CultureInfo.CurrentCulture, format, args), null);
}
/// <summary>
/// Logs a debug message.
///
/// </summary>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsDebugEnabled)
return;
LogInternal(LogLevel.Debug, string.Format(formatProvider, format, args), null);
}
/// <summary>
/// Logs an info message.
///
/// </summary>
/// <param name="message">The message to log</param>
public void Info(object message)
{
if (!IsInfoEnabled)
return;
Log(LogLevel.Info, message, null);
}
/// <summary>
/// Logs an info message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
public void Info(object message, Exception exception)
{
if (!IsInfoEnabled)
return;
Log(LogLevel.Info, message, exception);
}
public void Info(LogOutputProvider messageProvider)
{
if (!IsInfoEnabled)
return;
object obj = messageProvider();
LogInternal(LogLevel.Info, obj, null);
}
/// <summary>
/// Logs an info message.
///
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void InfoFormat(string format, params object[] args)
{
if (!IsInfoEnabled)
return;
LogInternal(LogLevel.Info, string.Format(CultureInfo.CurrentCulture, format, args), null);
}
/// <summary>
/// Logs an info message.
///
/// </summary>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsInfoEnabled)
return;
LogInternal(LogLevel.Info, string.Format(formatProvider, format, args), null);
}
/// <summary>
/// Logs a warn message.
///
/// </summary>
/// <param name="message">The message to log</param>
public void Warn(object message)
{
if (!IsWarnEnabled)
return;
Log(LogLevel.Warn, message, null);
}
/// <summary>
/// Logs a warn message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
public void Warn(object message, Exception exception)
{
if (!IsWarnEnabled)
return;
Log(LogLevel.Warn, message, exception);
}
public void Warn(LogOutputProvider messageProvider)
{
if (!IsWarnEnabled)
return;
object obj = messageProvider();
LogInternal(LogLevel.Warn, obj, null);
}
/// <summary>
/// Logs a warn message.
///
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void WarnFormat(string format, params object[] args)
{
if (!IsWarnEnabled)
return;
LogInternal(LogLevel.Warn, string.Format(CultureInfo.CurrentCulture, format, args), null);
}
/// <summary>
/// Logs a warn message.
///
/// </summary>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsWarnEnabled)
return;
LogInternal(LogLevel.Warn, string.Format(formatProvider, format, args), null);
}
/// <summary>
/// Logs an error message.
///
/// </summary>
/// <param name="message">The message to log</param>
public void Error(object message)
{
if (!IsErrorEnabled)
return;
Log(LogLevel.Error, message, null);
}
/// <summary>
/// Logs an error message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
public void Error(object message, Exception exception)
{
if (!IsErrorEnabled)
return;
Log(LogLevel.Error, message, exception);
}
public void Error(LogOutputProvider messageProvider)
{
if (!IsErrorEnabled)
return;
object obj = messageProvider();
LogInternal(LogLevel.Error, obj, null);
}
/// <summary>
/// Logs an error message.
///
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void ErrorFormat(string format, params object[] args)
{
if (!IsErrorEnabled)
return;
LogInternal(LogLevel.Error, string.Format(CultureInfo.CurrentCulture, format, args), null);
}
/// <summary>
/// Logs an error message.
///
/// </summary>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsErrorEnabled)
return;
LogInternal(LogLevel.Error, string.Format(formatProvider, format, args), null);
}
/// <summary>
/// Logs a fatal message.
///
/// </summary>
/// <param name="message">The message to log</param>
public void Fatal(object message)
{
if (!IsFatalEnabled)
return;
Log(LogLevel.Fatal, message, null);
}
/// <summary>
/// Logs a fatal message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="message">The message to log</param>
public void Fatal(object message, Exception exception)
{
if (!IsFatalEnabled)
return;
Log(LogLevel.Fatal, message, exception);
}
public void Fatal(LogOutputProvider messageProvider)
{
if (!IsFatalEnabled)
return;
object obj = messageProvider();
LogInternal(LogLevel.Fatal, obj, null);
}
/// <summary>
/// Logs a fatal message.
///
/// </summary>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void FatalFormat(string format, params object[] args)
{
if (!IsFatalEnabled)
return;
LogInternal(LogLevel.Fatal, string.Format(CultureInfo.CurrentCulture, format, args), null);
}
/// <summary>
/// Logs a fatal message.
///
/// </summary>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsFatalEnabled)
return;
LogInternal(LogLevel.Fatal, string.Format(formatProvider, format, args), null);
}
public void Log(LogLevel level, object obj)
{
if (_level < level)
return;
LogInternal(level, obj, null);
}
public void Log(LogLevel level, object obj, Exception exception)
{
if (_level < level)
return;
LogInternal(level, obj, exception);
}
public void Log(LogLevel level, LogOutputProvider messageProvider)
{
if (_level < level)
return;
object obj = messageProvider();
LogInternal(level, obj, null);
}
public void LogFormat(LogLevel level, IFormatProvider formatProvider, string format, params object[] args)
{
if (_level < level)
return;
LogInternal(level, string.Format(formatProvider, format, args), null);
}
/// <summary>
/// Logs a debug message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void DebugFormat(Exception exception, string format, params object[] args)
{
if (!IsDebugEnabled)
return;
LogInternal(LogLevel.Debug, string.Format(CultureInfo.CurrentCulture, format, args), exception);
}
/// <summary>
/// Logs a debug message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void DebugFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsDebugEnabled)
return;
LogInternal(LogLevel.Debug, string.Format(formatProvider, format, args), exception);
}
/// <summary>
/// Logs an info message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void InfoFormat(Exception exception, string format, params object[] args)
{
if (!IsInfoEnabled)
return;
LogInternal(LogLevel.Info, string.Format(CultureInfo.CurrentCulture, format, args), exception);
}
/// <summary>
/// Logs an info message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void InfoFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsInfoEnabled)
return;
LogInternal(LogLevel.Info, string.Format(formatProvider, format, args), exception);
}
/// <summary>
/// Logs a warn message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void WarnFormat(Exception exception, string format, params object[] args)
{
if (!IsWarnEnabled)
return;
LogInternal(LogLevel.Warn, string.Format(CultureInfo.CurrentCulture, format, args), exception);
}
/// <summary>
/// Logs a warn message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void WarnFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsWarnEnabled)
return;
LogInternal(LogLevel.Warn, string.Format(formatProvider, format, args), exception);
}
/// <summary>
/// Logs an error message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void ErrorFormat(Exception exception, string format, params object[] args)
{
if (!IsErrorEnabled)
return;
LogInternal(LogLevel.Error, string.Format(CultureInfo.CurrentCulture, format, args), exception);
}
/// <summary>
/// Logs an error message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void ErrorFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsErrorEnabled)
return;
LogInternal(LogLevel.Error, string.Format(formatProvider, format, args), exception);
}
/// <summary>
/// Logs a fatal message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void FatalFormat(Exception exception, string format, params object[] args)
{
if (!IsFatalEnabled)
return;
LogInternal(LogLevel.Fatal, string.Format(CultureInfo.CurrentCulture, format, args), exception);
}
/// <summary>
/// Logs a fatal message.
///
/// </summary>
/// <param name="exception">The exception to log</param>
/// <param name="formatProvider">The format provider to use</param>
/// <param name="format">Format string for the message to log</param>
/// <param name="args">Format arguments for the message to log</param>
public void FatalFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
{
if (!IsFatalEnabled)
return;
LogInternal(LogLevel.Fatal, string.Format(formatProvider, format, args), exception);
}
void LogInternal(LogLevel level, object obj, Exception exception)
{
string message = obj?.ToString() ?? "";
if (exception == null)
_source.TraceEvent(level.TraceEventType, 0, message);
else
_source.TraceData(level.TraceEventType, 0, (object)message, (object)exception);
}
}
}
| |
using System.Text;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.PatternMatching;
namespace IIS.SLSharp.Translation
{
internal abstract partial class VisitorBase
{
public StringBuilder VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, int data)
{
throw new SLSharpException("SL# does not understand anonymous methods.");
}
public StringBuilder VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression, int data)
{
throw new SLSharpException("Unsupported nonstandard language extension encountered.");
}
public StringBuilder VisitAsExpression(AsExpression asExpression, int data)
{
throw new SLSharpException("SL# does not have reflection-supported casts.");
}
public StringBuilder VisitCheckedExpression(CheckedExpression checkedExpression, int data)
{
throw new SLSharpException("SL# can only operate in unchecked context.");
}
public StringBuilder VisitLambdaExpression(LambdaExpression lambdaExpression, int data)
{
throw new SLSharpException("SL# does not understand lambda expressions.");
}
public StringBuilder VisitIsExpression(IsExpression isExpression, int data)
{
throw new SLSharpException("SL# does not have reflection.");
}
public StringBuilder VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression, int data)
{
throw new SLSharpException("SL# has no notion of NULL.");
}
public StringBuilder VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, int data)
{
throw new SLSharpException("SL# does not understand anonymous types");
}
public StringBuilder VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, int data)
{
throw new SLSharpException("SL# does not have pointers.");
}
public StringBuilder VisitSizeOfExpression(SizeOfExpression sizeOfExpression, int data)
{
throw new SLSharpException("SL# has no sizeof operator.");
}
public StringBuilder VisitStackAllocExpression(StackAllocExpression stackAllocExpression, int data)
{
throw new SLSharpException("Cannot stack-allocate memory in GLSL.");
}
public StringBuilder VisitTypeOfExpression(TypeOfExpression typeOfExpression, int data)
{
throw new SLSharpException("SL# does not have reflection.");
}
public StringBuilder VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, int data)
{
throw new SLSharpException("SL# primitives do not methods.");
}
public StringBuilder VisitQueryExpression(QueryExpression queryExpression, int data)
{
throw new SLSharpException("SL# does not understand LINQ.");
}
public StringBuilder VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause, int data)
{
throw new SLSharpException("SL# does not understand LINQ.");
}
public StringBuilder VisitQueryFromClause(QueryFromClause queryFromClause, int data)
{
throw new SLSharpException("SL# does not understand LINQ.");
}
public StringBuilder VisitQueryLetClause(QueryLetClause queryLetClause, int data)
{
throw new SLSharpException("SL# does not understand LINQ.");
}
public StringBuilder VisitQueryWhereClause(QueryWhereClause queryWhereClause, int data)
{
throw new SLSharpException("SL# does not understand LINQ.");
}
public StringBuilder VisitQueryJoinClause(QueryJoinClause queryJoinClause, int data)
{
throw new SLSharpException("SL# does not understand LINQ.");
}
public StringBuilder VisitQueryOrderClause(QueryOrderClause queryOrderClause, int data)
{
throw new SLSharpException("SL# does not understand LINQ.");
}
public StringBuilder VisitQueryOrdering(QueryOrdering queryOrdering, int data)
{
throw new SLSharpException("SL# does not understand LINQ.");
}
public StringBuilder VisitQuerySelectClause(QuerySelectClause querySelectClause, int data)
{
throw new SLSharpException("HLSL does not understand LINQ.");
}
public StringBuilder VisitQueryGroupClause(QueryGroupClause queryGroupClause, int data)
{
throw new SLSharpException("SL# does not understand LINQ.");
}
public StringBuilder VisitAttribute(Attribute attribute, int data)
{
throw new SLSharpException("SL# does not have attributes.");
}
public StringBuilder VisitAttribute(System.Attribute attribute, int data)
{
throw new SLSharpException("SL# does not have attributes.");
}
public StringBuilder VisitAttributeSection(AttributeSection attributeSection, int data)
{
throw new SLSharpException("HLSL does not have attributes.");
}
public StringBuilder VisitCheckedStatement(CheckedStatement checkedStatement, int data)
{
throw new SLSharpException("SL# can only operate in unchecked context.");
}
public StringBuilder VisitFixedStatement(FixedStatement fixedStatement, int data)
{
throw new SLSharpException("SL# does not understand the fixed keyword.");
}
public StringBuilder VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, int data)
{
throw new SLSharpException("SL# cannot jump from one case to another.");
}
public StringBuilder VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, int data)
{
throw new SLSharpException("SL# cannot jump from one case to another.");
}
public StringBuilder VisitGotoStatement(GotoStatement gotoStatement, int data)
{
throw new SLSharpException("SL# does not support goto.");
}
public StringBuilder VisitLabelStatement(LabelStatement labelStatement, int data)
{
throw new SLSharpException("SL# does not support labels.");
}
public StringBuilder VisitLockStatement(LockStatement lockStatement, int data)
{
throw new SLSharpException("SL# does not have locks.");
}
public StringBuilder VisitThrowStatement(ThrowStatement throwStatement, int data)
{
throw new SLSharpException("SL# does not have exceptions.");
}
public StringBuilder VisitTryCatchStatement(TryCatchStatement tryCatchStatement, int data)
{
throw new SLSharpException("SL# does not have exceptions.");
}
public StringBuilder VisitCatchClause(CatchClause catchClause, int data)
{
throw new SLSharpException("SL# does not have exceptions.");
}
public StringBuilder VisitUnsafeStatement(UnsafeStatement unsafeStatement, int data)
{
throw new SLSharpException("SL# does not allow unsafe code.");
}
public StringBuilder VisitUsingStatement(UsingStatement usingStatement, int data)
{
throw new SLSharpException("SL# does not have the using keyword.");
}
public StringBuilder VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement, int data)
{
throw new SLSharpException("SL# does not have iterators.");
}
public StringBuilder VisitYieldStatement(YieldStatement yieldStatement, int data)
{
throw new SLSharpException("SL# does not have iterators.");
}
public StringBuilder VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, int data)
{
throw new SLSharpException("SL# does not understand the fixed keyword.");
}
public StringBuilder VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer, int data)
{
throw new SLSharpException("SL# does not understand the fixed keyword.");
}
public StringBuilder VisitPatternPlaceholder(AstNode placeholder, Pattern pattern, int data)
{
throw new SLSharpException("SL# does not support pattern placeholders.");
}
public StringBuilder VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, int data)
{
throw new SLSharpException("SL# does not support named arguments.");
}
}
}
| |
using System.Diagnostics;
namespace Microsoft.Language.Xml.InternalSyntax
{
internal class SyntaxRewriter : SyntaxVisitor
{
public SyntaxList<TNode> VisitList<TNode>(SyntaxList<TNode> list) where TNode : GreenNode
{
SyntaxListBuilder<TNode> alternate = default(SyntaxListBuilder<TNode>);
int i = 0;
int n = list.Count;
while (i < n)
{
TNode item = list[i];
TNode visited = ((TNode)this.Visit(item));
if (item != visited && alternate.IsNull)
{
alternate = new SyntaxListBuilder<TNode>(n);
alternate.AddRange(list, 0, i);
}
if (!alternate.IsNull)
{
if (visited != null && visited.Kind != SyntaxKind.None)
{
alternate.Add(visited);
}
}
i += 1;
}
if (!alternate.IsNull)
{
return alternate.ToList();
}
return list;
}
public InternalSyntax.SeparatedSyntaxList<TNode> VisitList<TNode>(InternalSyntax.SeparatedSyntaxList<TNode> list) where TNode : GreenNode
{
InternalSyntax.SeparatedSyntaxListBuilder<TNode> alternate = default(InternalSyntax.SeparatedSyntaxListBuilder<TNode>);
int i = 0;
int itemCount = list.Count;
int separatorCount = list.SeparatorCount;
while (i < itemCount)
{
var item = list[i];
var visitedItem = this.Visit(item);
GreenNode separator = null;
GreenNode visitedSeparator = null;
if (i < separatorCount)
{
separator = list.GetSeparator(i);
var visitedSeparatorNode = this.Visit(separator);
Debug.Assert(visitedSeparatorNode is SyntaxToken.Green, "Cannot replace a separator with a non-separator");
visitedSeparator = (SyntaxToken.Green)visitedSeparatorNode;
Debug.Assert((separator == null &&
separator.Kind == SyntaxKind.None) ||
(visitedSeparator != null &&
visitedSeparator.Kind != SyntaxKind.None),
"Cannot delete a separator from a separated list. Removing an element will remove the corresponding separator.");
}
if (item != visitedItem && alternate.IsNull)
{
alternate = new InternalSyntax.SeparatedSyntaxListBuilder<TNode>(itemCount);
alternate.AddRange(list, i);
}
if (!alternate.IsNull)
{
if (visitedItem != null && visitedItem.Kind != SyntaxKind.None)
{
alternate.Add(((TNode)visitedItem));
if (visitedSeparator != null)
{
alternate.AddSeparator(visitedSeparator);
}
}
else if (i >= separatorCount && alternate.Count > 0)
{
alternate.RemoveLast(); // delete *preceding* separator
}
}
i += 1;
}
if (!alternate.IsNull)
{
return alternate.ToList();
}
return list;
}
public override GreenNode VisitXmlDocument(XmlDocumentSyntax.Green node)
{
bool anyChanges = false;
var newDeclaration = ((XmlDeclarationSyntax.Green)Visit(node.Prologue));
if (node.Prologue != newDeclaration)
{
anyChanges = true;
}
var newPrecedingMisc = VisitList<GreenNode>(node.PrecedingMisc);
if (node.PrecedingMisc != newPrecedingMisc.Node)
{
anyChanges = true;
}
var newRoot = ((XmlNodeSyntax.Green)Visit(node.Body));
if (node.Body != newRoot)
{
anyChanges = true;
}
var newFollowingMisc = VisitList<GreenNode>(node.FollowingMisc);
if (node.FollowingMisc != newFollowingMisc.Node)
{
anyChanges = true;
}
var newEof = VisitSyntaxToken(node.Eof);
if (node.Eof != newEof)
{
anyChanges = true;
}
var newSkippedTokens = ((SkippedTokensTriviaSyntax.Green)VisitSkippedTokensTrivia(node.SkippedTokens));
if (node.SkippedTokens != newSkippedTokens)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlDocumentSyntax.Green(
newDeclaration,
newPrecedingMisc.Node,
newRoot,
newFollowingMisc.Node,
newSkippedTokens,
newEof);
}
else
{
return node;
}
}
public override GreenNode VisitXmlDeclaration(XmlDeclarationSyntax.Green node)
{
bool anyChanges = false;
var newLessThanQuestionToken = ((PunctuationSyntax.Green)Visit(node.LessThanQuestionToken));
if (node.LessThanQuestionToken != newLessThanQuestionToken)
{
anyChanges = true;
}
var newXmlKeyword = ((KeywordSyntax.Green)Visit(node.XmlKeyword));
if (node.XmlKeyword != newXmlKeyword)
{
anyChanges = true;
}
var newVersion = ((XmlDeclarationOptionSyntax.Green)Visit(node.Version));
if (node.Version != newVersion)
{
anyChanges = true;
}
var newEncoding = ((XmlDeclarationOptionSyntax.Green)Visit(node.Encoding));
if (node.Encoding != newEncoding)
{
anyChanges = true;
}
var newStandalone = ((XmlDeclarationOptionSyntax.Green)Visit(node.Standalone));
if (node.Standalone != newStandalone)
{
anyChanges = true;
}
var newQuestionGreaterThanToken = ((PunctuationSyntax.Green)Visit(node.QuestionGreaterThanToken));
if (node.QuestionGreaterThanToken != newQuestionGreaterThanToken)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlDeclarationSyntax.Green(
newLessThanQuestionToken,
newXmlKeyword,
newVersion,
newEncoding,
newStandalone,
newQuestionGreaterThanToken);
}
else
{
return node;
}
}
public override GreenNode VisitXmlDeclarationOption(XmlDeclarationOptionSyntax.Green node)
{
bool anyChanges = false;
var newName = ((XmlNameTokenSyntax.Green)Visit(node.Name));
if (node.Name != newName)
{
anyChanges = true;
}
var newEquals = ((PunctuationSyntax.Green)Visit(node.Equals));
if (node.Equals != newEquals)
{
anyChanges = true;
}
var newValue = ((XmlStringSyntax.Green)Visit(node.Value));
if (node.Value != newValue)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlDeclarationOptionSyntax.Green(newName, newEquals, newValue);
}
else
{
return node;
}
}
public override GreenNode VisitXmlElement(XmlElementSyntax.Green node)
{
bool anyChanges = false;
var newStartTag = ((XmlElementStartTagSyntax.Green)Visit(node.StartTag));
if (node.StartTag != newStartTag)
{
anyChanges = true;
}
var newContent = VisitList<GreenNode>(node.Content);
if (node.Content != newContent.Node)
{
anyChanges = true;
}
var newEndTag = ((XmlElementEndTagSyntax.Green)Visit(node.EndTag));
if (node.EndTag != newEndTag)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlElementSyntax.Green(newStartTag, newContent.Node, newEndTag);
}
else
{
return node;
}
}
public override GreenNode VisitXmlText(XmlTextSyntax.Green node)
{
bool anyChanges = false;
var newTextTokens = VisitList<GreenNode>(node.TextTokens);
if (node.TextTokens != newTextTokens.Node)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlTextSyntax.Green(newTextTokens.Node);
}
else
{
return node;
}
}
public override GreenNode VisitXmlElementStartTag(XmlElementStartTagSyntax.Green node)
{
bool anyChanges = false;
var newLessThanToken = ((PunctuationSyntax.Green)Visit(node.LessThanToken));
if (node.LessThanToken != newLessThanToken)
{
anyChanges = true;
}
var newName = ((XmlNameSyntax.Green)Visit(node.NameNode));
if (node.NameNode != newName)
{
anyChanges = true;
}
var newAttributes = VisitList<GreenNode>(node.Attributes);
if (node.Attributes != newAttributes.Node)
{
anyChanges = true;
}
var newGreaterThanToken = ((PunctuationSyntax.Green)Visit(node.GreaterThanToken));
if (node.GreaterThanToken != newGreaterThanToken)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlElementStartTagSyntax.Green(newLessThanToken, newName, newAttributes.Node, newGreaterThanToken);
}
else
{
return node;
}
}
public override GreenNode VisitXmlElementEndTag(XmlElementEndTagSyntax.Green node)
{
bool anyChanges = false;
var newLessThanSlashToken = ((PunctuationSyntax.Green)Visit(node.LessThanSlashToken));
if (node.LessThanSlashToken != newLessThanSlashToken)
{
anyChanges = true;
}
var newName = ((XmlNameSyntax.Green)Visit(node.NameNode));
if (node.NameNode != newName)
{
anyChanges = true;
}
var newGreaterThanToken = ((PunctuationSyntax.Green)Visit(node.GreaterThanToken));
if (node.GreaterThanToken != newGreaterThanToken)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlElementEndTagSyntax.Green(newLessThanSlashToken, newName, newGreaterThanToken);
}
else
{
return node;
}
}
public override GreenNode VisitXmlEmptyElement(XmlEmptyElementSyntax.Green node)
{
bool anyChanges = false;
var newLessThanToken = ((PunctuationSyntax.Green)Visit(node.LessThanToken));
if (node.LessThanToken != newLessThanToken)
{
anyChanges = true;
}
var newName = ((XmlNameSyntax.Green)Visit(node.NameNode));
if (node.NameNode != newName)
{
anyChanges = true;
}
var newAttributes = VisitList<GreenNode>(node.AttributesNode);
if (node.AttributesNode != newAttributes.Node)
{
anyChanges = true;
}
var newSlashGreaterThanToken = ((PunctuationSyntax.Green)Visit(node.SlashGreaterThanToken));
if (node.SlashGreaterThanToken != newSlashGreaterThanToken)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlEmptyElementSyntax.Green(newLessThanToken, newName, newAttributes.Node, newSlashGreaterThanToken);
}
else
{
return node;
}
}
public override GreenNode VisitXmlAttribute(XmlAttributeSyntax.Green node)
{
bool anyChanges = false;
var newName = ((XmlNameSyntax.Green)Visit(node.NameNode));
if (node.NameNode != newName)
{
anyChanges = true;
}
var newEqualsToken = ((PunctuationSyntax.Green)Visit(node.Equals));
if (node.Equals != newEqualsToken)
{
anyChanges = true;
}
var newValue = ((XmlNodeSyntax.Green)Visit(node.ValueNode));
if (node.ValueNode != newValue)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlAttributeSyntax.Green(newName, newEqualsToken, newValue);
}
else
{
return node;
}
}
public override GreenNode VisitXmlString(XmlStringSyntax.Green node)
{
bool anyChanges = false;
var newStartQuoteToken = ((PunctuationSyntax.Green)Visit(node.StartQuoteToken));
if (node.StartQuoteToken != newStartQuoteToken)
{
anyChanges = true;
}
var newTextTokens = VisitList(node.TextTokens);
if (node.TextTokens != newTextTokens.Node)
{
anyChanges = true;
}
var newEndQuoteToken = ((PunctuationSyntax.Green)Visit(node.EndQuoteToken));
if (node.EndQuoteToken != newEndQuoteToken)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlStringSyntax.Green(newStartQuoteToken, newTextTokens.Node, newEndQuoteToken);
}
else
{
return node;
}
}
public override GreenNode VisitXmlName(XmlNameSyntax.Green node)
{
bool anyChanges = false;
var newPrefix = ((XmlPrefixSyntax.Green)Visit(node.Prefix));
if (node.Prefix != newPrefix)
{
anyChanges = true;
}
var newLocalName = ((XmlNameTokenSyntax.Green)Visit(node.LocalName));
if (node.LocalName != newLocalName)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlNameSyntax.Green(newPrefix, newLocalName);
}
else
{
return node;
}
}
//public override GreenNode VisitXmlPrefixName(XmlPrefixSyntax node)
//{
// bool anyChanges = false;
// var newName = ((XmlNameTokenSyntax)Visit(node.Name));
// if (node.Name != newName)
// {
// anyChanges = true;
// }
// var newColonToken = ((PunctuationSyntax)Visit(node.ColonToken));
// if (node.ColonToken != newColonToken)
// {
// anyChanges = true;
// }
// if (anyChanges)
// {
// return new XmlPrefixSyntax(newName, newColonToken);
// }
// else
// {
// return node;
// }
//}
public override GreenNode VisitXmlComment(XmlCommentSyntax.Green node)
{
bool anyChanges = false;
var newLessThanExclamationMinusMinusToken = ((PunctuationSyntax.Green)Visit(node.BeginComment));
if (node.BeginComment != newLessThanExclamationMinusMinusToken)
{
anyChanges = true;
}
var newTextTokens = VisitList<GreenNode>(node.Content);
if (node.Content != newTextTokens.Node)
{
anyChanges = true;
}
var newMinusMinusGreaterThanToken = ((PunctuationSyntax.Green)Visit(node.EndComment));
if (node.EndComment != newMinusMinusGreaterThanToken)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlCommentSyntax.Green(newLessThanExclamationMinusMinusToken, newTextTokens.Node, newMinusMinusGreaterThanToken);
}
else
{
return node;
}
}
public override GreenNode VisitXmlProcessingInstruction(XmlProcessingInstructionSyntax.Green node)
{
bool anyChanges = false;
var newLessThanQuestionToken = ((PunctuationSyntax.Green)Visit(node.LessThanQuestionToken));
if (node.LessThanQuestionToken != newLessThanQuestionToken)
{
anyChanges = true;
}
var newName = ((XmlNameTokenSyntax.Green)Visit(node.Name));
if (node.Name != newName)
{
anyChanges = true;
}
var newTextTokens = VisitList<GreenNode>(node.TextTokens);
if (node.TextTokens != newTextTokens.Node)
{
anyChanges = true;
}
var newQuestionGreaterThanToken = ((PunctuationSyntax.Green)Visit(node.QuestionGreaterThanToken));
if (node.QuestionGreaterThanToken != newQuestionGreaterThanToken)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlProcessingInstructionSyntax.Green(newLessThanQuestionToken, newName, newTextTokens.Node, newQuestionGreaterThanToken);
}
else
{
return node;
}
}
public override GreenNode VisitXmlCDataSection(XmlCDataSectionSyntax.Green node)
{
bool anyChanges = false;
var newBeginCDataToken = ((PunctuationSyntax.Green)Visit(node.BeginCData));
if (node.BeginCData != newBeginCDataToken)
{
anyChanges = true;
}
var newTextTokens = VisitList<GreenNode>(node.TextTokens);
if (node.TextTokens != newTextTokens.Node)
{
anyChanges = true;
}
var newEndCDataToken = ((PunctuationSyntax.Green)Visit(node.EndCData));
if (node.EndCData != newEndCDataToken)
{
anyChanges = true;
}
if (anyChanges)
{
return new XmlCDataSectionSyntax.Green(newBeginCDataToken, newTextTokens.Node, newEndCDataToken);
}
else
{
return node;
}
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapCompareAttrNames.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System.Collections;
using System.Globalization;
using Novell.Directory.Ldap.Utilclass;
namespace Novell.Directory.Ldap
{
/// <summary>
/// Compares Ldap entries based on attribute name.
/// An object of this class defines ordering when sorting LdapEntries,
/// usually from search results. When using this Comparator, LdapEntry objects
/// are sorted by the attribute names(s) passed in on the
/// constructor, in ascending or descending order. The object is typically
/// supplied to an implementation of the collection interfaces such as
/// java.util.TreeSet which performs sorting.
/// Comparison is performed via locale-sensitive Java String comparison,
/// which may not correspond to the Ldap ordering rules by which an Ldap server
/// would sort them.
/// </summary>
public class LdapCompareAttrNames : IComparer
{
private void InitBlock()
{
// location = Locale.getDefault();
location = CultureInfo.CurrentCulture;
collator = CultureInfo.CurrentCulture.CompareInfo;
}
/// <summary>
/// Returns the locale to be used for sorting, if a locale has been
/// specified.
/// If locale is null, a basic String.compareTo method is used for
/// collation. If non-null, a locale-specific collation is used.
/// </summary>
/// <returns>
/// The locale if one has been specified
/// </returns>
/// <summary>
/// Sets the locale to be used for sorting.
/// </summary>
/// <param name="locale">
/// The locale to be used for sorting.
/// </param>
public virtual CultureInfo Locale
{
get
{
//currently supports only English local.
return location;
}
set
{
collator = value.CompareInfo;
location = value;
}
}
private readonly string[] sortByNames; //names to to sort by.
private readonly bool[] sortAscending; //true if sorting ascending
private CultureInfo location;
private CompareInfo collator;
/// <summary>
/// Constructs an object that sorts results by a single attribute, in
/// ascending order.
/// </summary>
/// <param name="attrName">
/// Name of an attribute by which to sort.
/// </param>
public LdapCompareAttrNames(string attrName)
{
InitBlock();
sortByNames = new string[1];
sortByNames[0] = attrName;
sortAscending = new bool[1];
sortAscending[0] = true;
}
/// <summary>
/// Constructs an object that sorts results by a single attribute, in
/// either ascending or descending order.
/// </summary>
/// <param name="attrName">
/// Name of an attribute to sort by.
/// </param>
/// <param name="ascendingFlag">
/// True specifies ascending order; false specifies
/// descending order.
/// </param>
public LdapCompareAttrNames(string attrName, bool ascendingFlag)
{
InitBlock();
sortByNames = new string[1];
sortByNames[0] = attrName;
sortAscending = new bool[1];
sortAscending[0] = ascendingFlag;
}
/// <summary>
/// Constructs an object that sorts by one or more attributes, in the
/// order provided, in ascending order.
/// Note: Novell eDirectory allows sorting by one attribute only. The
/// direcctory server must also be configured to index the specified
/// attribute.
/// </summary>
/// <param name="attrNames">
/// Array of names of attributes to sort by.
/// </param>
public LdapCompareAttrNames(string[] attrNames)
{
InitBlock();
sortByNames = new string[attrNames.Length];
sortAscending = new bool[attrNames.Length];
for (var i = 0; i < attrNames.Length; i++)
{
sortByNames[i] = attrNames[i];
sortAscending[i] = true;
}
}
/// <summary>
/// Constructs an object that sorts by one or more attributes, in the
/// order provided, in either ascending or descending order for each
/// attribute.
/// Note: Novell eDirectory supports only ascending sort order (A,B,C ...)
/// and allows sorting only by one attribute. The directory server must be
/// configured to index this attribute.
/// </summary>
/// <param name="attrNames">
/// Array of names of attributes to sort by.
/// </param>
/// <param name="ascendingFlags">
/// Array of flags, one for each attrName, where
/// true specifies ascending order and false specifies
/// descending order. An LdapException is thrown if
/// the length of ascendingFlags is not greater than
/// or equal to the length of attrNames.
/// </param>
/// <exception>
/// LdapException A general exception which includes an error
/// message and an Ldap error code.
/// </exception>
public LdapCompareAttrNames(string[] attrNames, bool[] ascendingFlags)
{
InitBlock();
if (attrNames.Length != ascendingFlags.Length)
{
throw new LdapException(ExceptionMessages.UNEQUAL_LENGTHS, LdapException.INAPPROPRIATE_MATCHING, null);
//"Length of attribute Name array does not equal length of Flags array"
}
sortByNames = new string[attrNames.Length];
sortAscending = new bool[ascendingFlags.Length];
for (var i = 0; i < attrNames.Length; i++)
{
sortByNames[i] = attrNames[i];
sortAscending[i] = ascendingFlags[i];
}
}
/// <summary>
/// Compares the the attributes of the first LdapEntry to the second.
/// Only the values of the attributes named at the construction of this
/// object will be compared. Multi-valued attributes compare on the first
/// value only.
/// </summary>
/// <param name="object1">
/// Target entry for comparison.
/// </param>
/// <param name="object2">
/// Entry to be compared to.
/// </param>
/// <returns>
/// Negative value if the first entry is less than the second and
/// positive if the first is greater than the second. Zero is returned if all
/// attributes to be compared are the same.
/// </returns>
public virtual int Compare(object object1, object object2)
{
var entry1 = (LdapEntry) object1;
var entry2 = (LdapEntry) object2;
LdapAttribute one, two;
string[] first; //multivalued attributes are ignored.
string[] second; //we just use the first element
int compare, i = 0;
if (collator == null)
{
//using default locale
collator = CultureInfo.CurrentCulture.CompareInfo;
}
do
{
//while first and second are equal
one = entry1.getAttribute(sortByNames[i]);
two = entry2.getAttribute(sortByNames[i]);
if (one != null && two != null)
{
first = one.StringValueArray;
second = two.StringValueArray;
compare = collator.Compare(first[0], second[0]);
}
//We could also use the other multivalued attributes to break ties.
//one of the entries was null
else
{
if (one != null)
compare = -1;
//one is greater than two
else if (two != null)
compare = 1;
//one is lesser than two
else
compare = 0; //tie - break it with the next attribute name
}
i++;
} while (compare == 0 && i < sortByNames.Length);
if (sortAscending[i - 1])
{
// return the normal ascending comparison.
return compare;
}
// negate the comparison for a descending comparison.
return -compare;
}
/// <summary>
/// Determines if this comparator is equal to the comparator passed in.
/// This will return true if the comparator is an instance of
/// LdapCompareAttrNames and compares the same attributes names in the same
/// order.
/// </summary>
/// <returns>
/// true the comparators are equal
/// </returns>
public override bool Equals(object comparator)
{
if (!(comparator is LdapCompareAttrNames))
{
return false;
}
var comp = (LdapCompareAttrNames) comparator;
// Test to see if the attribute to compare are the same length
if (comp.sortByNames.Length != sortByNames.Length || comp.sortAscending.Length != sortAscending.Length)
{
return false;
}
// Test to see if the attribute names and sorting orders are the same.
for (var i = 0; i < sortByNames.Length; i++)
{
if (comp.sortAscending[i] != sortAscending[i])
return false;
if (!comp.sortByNames[i].ToUpper().Equals(sortByNames[i].ToUpper()))
return false;
}
return true;
}
}
}
| |
using System;
using System.Collections;
/// <summary>
/// System.Array.Sort(System.Array,System.Array,System.Int32,System.Int32,System.Collections.IComparer)
/// </summary>
public class ArrayIndexOf1
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
retVal = NegTest8() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array using default comparer ");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Mike",
"Peter",
"Tom",
"Allin"};
int[] i1 = new int[6] { 24, 30, 28, 26, 32, 23 };
string[] s2 = new string[6]{"Jack",
"Mary",
"Mike",
"Allin",
"Peter",
"Tom"};
int[] i2 = new int[6] { 24, 30, 28, 23, 26, 32 };
Array.Sort(s1, i1, 3, 3, null);
for (int i = 0; i < 6; i++)
{
if (s1[i] != s2[i])
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("002", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using comparer ");
try
{
int length = TestLibrary.Generator.GetByte(-55);
int[] i1 = new int[length];
int[] i2 = new int[length];
for (int i = 0; i < length; i++)
{
int value = TestLibrary.Generator.GetInt32(-55);
i1[i] = value;
i2[i] = value;
}
IComparer a1 = new A();
int startIdx = GetInt(0, length - 1);
int endIdx = GetInt(startIdx, length - 1);
int count = endIdx - startIdx;
Array.Sort(i1, i2, startIdx, count, a1);
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("004", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using reverse comparer ");
try
{
char[] c1 = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] d1 = new char[10] { 'a', 'e', 'd', 'c', 'b', 'f', 'g', 'h', 'i', 'j' };
int[] a1 = new int[10] { 2, 3, 4, 1, 0, 2, 12, 52, 31, 0 };
int[] b1 = new int[10] { 2, 0, 1, 4, 3, 2, 12, 52, 31, 0 };
IComparer b = new B();
Array.Sort(c1, a1, 1, 4, b);
for (int i = 0; i < 10; i++)
{
if (c1[i] != d1[i])
{
TestLibrary.TestFramework.LogError("006", "The result is not the value as expected");
retVal = false;
}
if (a1[i] != b1[i])
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Sort an int array and the items array is null ");
try
{
int length = (int) TestLibrary.Generator.GetByte(-55);
int[] i1 = new int[length];
int[] i2 = new int[length];
for (int i = 0; i < length; i++)
{
int value = TestLibrary.Generator.GetByte(-55);
i1[i] = value;
i2[i] = value;
}
int startIdx = GetInt(0, length - 2);
int endIdx = GetInt(startIdx, length - 1);
int count = endIdx - startIdx + 1;
for (int i = startIdx; i < endIdx; i++) //manually quich sort
{
for (int j = i + 1; j <= endIdx; j++)
{
if (i2[i] > i2[j])
{
int temp = i2[i];
i2[i] = i2[j];
i2[j] = temp;
}
}
}
Array.Sort(i1, null, startIdx, count, new A());
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The first argument is null reference ");
try
{
string[] s1 = null;
int[] i1 = { 1, 2, 3, 4, 5 };
Array.Sort(s1, i1, 0, 2, null);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected ");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The keys array is not one dimension ");
try
{
int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } };
int[] i2 = { 1, 2, 3, 4, 5 };
Array.Sort(i1, i2, 0, 3, null);
TestLibrary.TestFramework.LogError("103", "The RankException is not throw as expected ");
retVal = false;
}
catch (RankException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: The items array is not one dimension ");
try
{
int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } };
int[] i2 = { 1, 2, 3, 4, 5 };
Array.Sort(i2, i1, 0, 2, null);
TestLibrary.TestFramework.LogError("105", "The RankException is not throw as expected ");
retVal = false;
}
catch (RankException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4:The length of items array is not equal to the length of keys array ");
try
{
int length_array = TestLibrary.Generator.GetInt16(-55);
int length_value = TestLibrary.Generator.GetByte(-55);
string[] s1 = new string[length_array];
int[] i1 = new int[length_value];
for (int i = 0; i < length_array; i++)
{
string value = TestLibrary.Generator.GetString(-55, false, 0, 10);
s1[i] = value;
}
for (int i = 0; i < length_value; i++)
{
int value = TestLibrary.Generator.GetInt32(-55);
i1[i] = value;
}
int startIdx = GetInt(0, 255);
int count = GetInt(256, length_array - 1);
Array.Sort(s1, i1, startIdx, count, null);
TestLibrary.TestFramework.LogError("107", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: The Icomparer is null and keys array does not implement the IComparer interface ");
try
{
D d1 = new D();
D d2 = new D();
D d3 = new D();
D d4 = new D();
int[] i2 = { 1, 2, 3, 4 };
D[] d = new D[4] { d1, d2, d3, d4 };
Array.Sort(d, i2, 1, 3, null);
TestLibrary.TestFramework.LogError("109", "The InvalidOperationException is not throw as expected ");
retVal = false;
}
catch (InvalidOperationException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: The start index is less than the minimal bound of the array");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Peter",
"Mike",
"Tom",
"Allin"};
int[] i1 = new int[6] { 24, 30, 28, 26, 32, 44 };
Array.Sort(s1, i1, -1, 4, null);
TestLibrary.TestFramework.LogError("111", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7: The length is less than zero");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Peter",
"Mike",
"Tom",
"Allin"};
int[] i1 = new int[6] { 24, 30, 28, 26, 32, 44 };
Array.Sort(s1, i1, 3, -1, null);
TestLibrary.TestFramework.LogError("111", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest8:The start index is greater than the max bound of the array");
try
{
int length = TestLibrary.Generator.GetInt16(-55);
string[] s1 = new string[length];
int[] i1 = new int[length];
for (int i = 0; i < length; i++)
{
string value1 = TestLibrary.Generator.GetString(-55, false, 0, 10);
int value2 = TestLibrary.Generator.GetInt32(-55);
s1[i] = value1;
i1[i] = value2;
}
Array.Sort(s1, i1, length + 1, 0, null);
TestLibrary.TestFramework.LogError("113", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("114", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ArrayIndexOf1 test = new ArrayIndexOf1();
TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
class A : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return ((int)x).CompareTo((int)y);
}
#endregion
}
class B : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
if (((char)x).CompareTo((char)y) > 0)
return -1;
else
{
if (x == y)
{
return 0;
}
else
{
return 1;
}
}
}
#endregion
}
class C : IComparer
{
protected int c_value;
public C(int a)
{
this.c_value = a;
}
#region IComparer Members
public int Compare(object x, object y)
{
return (x as C).c_value.CompareTo((y as C).c_value);
}
#endregion
}
class D : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return 0;
}
#endregion
}
#region Help method for geting test data
private Int32 GetInt(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cocos2D
{
public delegate void CCFocusChangeDelegate(ICCFocusable prev, ICCFocusable current);
public class CCFocusManager
{
public event CCFocusChangeDelegate OnFocusChanged;
/// <summary>
/// The list of nodes that can receive focus
/// </summary>
private LinkedList<ICCFocusable> _FocusList = new LinkedList<ICCFocusable>();
/// <summary>
/// The current node with focus
/// </summary>
private LinkedListNode<ICCFocusable> _Current = null;
/// <summary>
/// Removes the given focusable node
/// </summary>
/// <param name="f"></param>
public void Remove(ICCFocusable f)
{
_FocusList.Remove(f);
}
/// <summary>
/// Adds the given node to the list of focus nodes. If the node has the focus, then it is
/// given the current focused item status. If there is already a focused item and the
/// given node has focus, the focus is disabled.
/// </summary>
/// <param name="f"></param>
public void Add(ICCFocusable f)
{
LinkedListNode<ICCFocusable> i = _FocusList.AddLast(f);
if (f.HasFocus)
{
if (_Current == null)
{
_Current = i;
}
else
{
f.HasFocus = false;
}
}
}
/// <summary>
/// When false, the focus will not traverse on the keyboard or dpad events.
/// </summary>
public bool Enabled
{
get;
set;
}
/// <summary>
/// Scroll to the next item in the focus list.
/// </summary>
public void FocusNextItem()
{
if (_Current == null && _FocusList.Count > 0)
{
_Current = _FocusList.First;
_Current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(null, _Current.Value);
}
}
else if (_Current != null)
{
ICCFocusable lostItem = _Current.Value;
// Search for the next node.
LinkedListNode<ICCFocusable> nextItem = null;
for (LinkedListNode<ICCFocusable> p = _Current.Next; p != null; p = p.Next)
{
if (p.Value.CanReceiveFocus)
{
nextItem = p;
}
}
if (nextItem != null)
{
_Current = nextItem;
}
else
{
_Current = _FocusList.First;
}
lostItem.HasFocus = false;
_Current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(lostItem, _Current.Value);
}
}
else
{
_Current = null;
}
}
/// <summary>
/// Scroll to the previous item in the focus list.
/// </summary>
public void FocusPreviousItem()
{
if (ItemWithFocus == null && _FocusList.Count > 0)
{
_Current = _FocusList.Last;
_Current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(null, _Current.Value);
}
}
else if (_Current != null)
{
ICCFocusable lostItem = _Current.Value;
LinkedListNode<ICCFocusable> nextItem = null;
for (LinkedListNode<ICCFocusable> p = _Current.Previous; p != null; p = p.Previous)
{
if (p.Value.CanReceiveFocus)
{
nextItem = p;
}
}
if (_Current.Previous != null)
{
_Current = _Current.Previous;
}
else
{
_Current = _FocusList.Last;
}
lostItem.HasFocus = false;
_Current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(lostItem, _Current.Value);
}
}
else
{
_Current = null;
}
}
/// <summary>
/// Returns the item with the current focus. This test will create a copy
/// of the master item list.
/// </summary>
public ICCFocusable ItemWithFocus
{
get
{
return (_Current != null ? _Current.Value : null);
}
}
private long m_lTimeOfLastFocus = 0L;
private bool m_bScrollingPrevious = false;
private bool m_bScrollingNext = false;
/// <summary>
/// Scrolling focus delay used to slow down automatic focus changes when the dpad is held.
/// </summary>
public static float MenuScrollDelay = 50f;
#region Singleton
private CCFocusManager()
{
CCApplication.SharedApplication.GamePadDPadUpdate += new CCGamePadDPadDelegate(SharedApplication_GamePadDPadUpdate);
}
private void SharedApplication_GamePadDPadUpdate(CCGamePadButtonStatus leftButton, CCGamePadButtonStatus upButton, CCGamePadButtonStatus rightButton, CCGamePadButtonStatus downButton, Microsoft.Xna.Framework.PlayerIndex player)
{
if (!Enabled)
{
return;
}
if (leftButton == CCGamePadButtonStatus.Released || upButton == CCGamePadButtonStatus.Released || rightButton == CCGamePadButtonStatus.Released || downButton == CCGamePadButtonStatus.Released)
{
m_bScrollingPrevious = false;
m_lTimeOfLastFocus = 0L;
}
// Left and right d-pad shuffle through the menus
else if (leftButton == CCGamePadButtonStatus.Pressed || upButton == CCGamePadButtonStatus.Pressed)
{
if (m_bScrollingPrevious)
{
TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - m_lTimeOfLastFocus);
if (ts.TotalMilliseconds > MenuScrollDelay)
{
FocusPreviousItem();
}
}
else
{
m_bScrollingPrevious = true;
m_lTimeOfLastFocus = DateTime.Now.Ticks;
}
}
else if (rightButton == CCGamePadButtonStatus.Pressed || downButton == CCGamePadButtonStatus.Pressed)
{
if (m_bScrollingNext)
{
TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - m_lTimeOfLastFocus);
if (ts.TotalMilliseconds > MenuScrollDelay)
{
FocusNextItem();
}
}
else
{
m_bScrollingNext = true;
m_lTimeOfLastFocus = DateTime.Now.Ticks;
}
}
}
private static CCFocusManager _Instance = new CCFocusManager();
public static CCFocusManager Instance
{
get
{
return (_Instance);
}
}
#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.Buffers;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SSL encapsulated over TDS transport. During SSL handshake, SSL packets are
/// transported in TDS packet type 0x12. Once SSL handshake has completed, SSL
/// packets are sent transparently.
/// </summary>
internal sealed class SslOverTdsStream : Stream
{
private readonly Stream _stream;
private int _packetBytes = 0;
private bool _encapsulate;
private const int PACKET_SIZE_WITHOUT_HEADER = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE - TdsEnums.HEADER_LEN;
private const int PRELOGIN_PACKET_TYPE = 0x12;
/// <summary>
/// Constructor
/// </summary>
/// <param name="stream">Underlying stream</param>
public SslOverTdsStream(Stream stream)
{
_stream = stream;
_encapsulate = true;
}
/// <summary>
/// Finish SSL handshake. Stop encapsulating in TDS.
/// </summary>
public void FinishHandshake()
{
_encapsulate = false;
}
/// <summary>
/// Read buffer
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="offset">Offset</param>
/// <param name="count">Byte count</param>
/// <returns>Bytes read</returns>
public override int Read(byte[] buffer, int offset, int count) =>
ReadInternal(buffer, offset, count, CancellationToken.None, async: false).GetAwaiter().GetResult();
/// <summary>
/// Write Buffer
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
public override void Write(byte[] buffer, int offset, int count)
=> WriteInternal(buffer, offset, count, CancellationToken.None, async: false).Wait();
/// <summary>
/// Write Buffer Asynchronosly
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="token"></param>
/// <returns></returns>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token)
=> WriteInternal(buffer, offset, count, token, async: true);
/// <summary>
/// Read Buffer Asynchronosly
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="token"></param>
/// <returns></returns>
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken token)
=> ReadInternal(buffer, offset, count, token, async: true);
/// <summary>
/// Read Internal is called synchronosly when async is false
/// </summary>
private async Task<int> ReadInternal(byte[] buffer, int offset, int count, CancellationToken token, bool async)
{
int readBytes = 0;
byte[] packetData = null;
byte[] readTarget = buffer;
int readOffset = offset;
if (_encapsulate)
{
packetData = ArrayPool<byte>.Shared.Rent(count < TdsEnums.HEADER_LEN ? TdsEnums.HEADER_LEN : count);
readTarget = packetData;
readOffset = 0;
if (_packetBytes == 0)
{
// Account for split packets
while (readBytes < TdsEnums.HEADER_LEN)
{
readBytes += async ?
await _stream.ReadAsync(packetData, readBytes, TdsEnums.HEADER_LEN - readBytes, token).ConfigureAwait(false) :
_stream.Read(packetData, readBytes, TdsEnums.HEADER_LEN - readBytes);
}
_packetBytes = (packetData[TdsEnums.HEADER_LEN_FIELD_OFFSET] << 8) | packetData[TdsEnums.HEADER_LEN_FIELD_OFFSET + 1];
_packetBytes -= TdsEnums.HEADER_LEN;
}
if (count > _packetBytes)
{
count = _packetBytes;
}
}
readBytes = async ?
await _stream.ReadAsync(readTarget, readOffset, count, token).ConfigureAwait(false) :
_stream.Read(readTarget, readOffset, count);
if (_encapsulate)
{
_packetBytes -= readBytes;
}
if (packetData != null)
{
Buffer.BlockCopy(packetData, 0, buffer, offset, readBytes);
ArrayPool<byte>.Shared.Return(packetData, clearArray: true);
}
return readBytes;
}
/// <summary>
/// The internal write method calls Sync APIs when Async flag is false
/// </summary>
private async Task WriteInternal(byte[] buffer, int offset, int count, CancellationToken token, bool async)
{
int currentCount = 0;
int currentOffset = offset;
while (count > 0)
{
// During the SSL negotiation phase, SSL is tunnelled over TDS packet type 0x12. After
// negotiation, the underlying socket only sees SSL frames.
//
if (_encapsulate)
{
if (count > PACKET_SIZE_WITHOUT_HEADER)
{
currentCount = PACKET_SIZE_WITHOUT_HEADER;
}
else
{
currentCount = count;
}
count -= currentCount;
// Prepend buffer data with TDS prelogin header
int combinedLength = TdsEnums.HEADER_LEN + currentCount;
byte[] combinedBuffer = ArrayPool<byte>.Shared.Rent(combinedLength);
// We can only send 4088 bytes in one packet. Header[1] is set to 1 if this is a
// partial packet (whether or not count != 0).
//
combinedBuffer[7] = 0; // touch this first for the jit bounds check
combinedBuffer[0] = PRELOGIN_PACKET_TYPE;
combinedBuffer[1] = (byte)(count > 0 ? 0 : 1);
combinedBuffer[2] = (byte)((currentCount + TdsEnums.HEADER_LEN) / 0x100);
combinedBuffer[3] = (byte)((currentCount + TdsEnums.HEADER_LEN) % 0x100);
combinedBuffer[4] = 0;
combinedBuffer[5] = 0;
combinedBuffer[6] = 0;
Array.Copy(buffer, currentOffset, combinedBuffer, TdsEnums.HEADER_LEN, (combinedLength - TdsEnums.HEADER_LEN));
if (async)
{
await _stream.WriteAsync(combinedBuffer, 0, combinedLength, token).ConfigureAwait(false);
}
else
{
_stream.Write(combinedBuffer, 0, combinedLength);
}
Array.Clear(combinedBuffer, 0, combinedLength);
ArrayPool<byte>.Shared.Return(combinedBuffer);
}
else
{
currentCount = count;
count = 0;
if (async)
{
await _stream.WriteAsync(buffer, currentOffset, currentCount, token).ConfigureAwait(false);
}
else
{
_stream.Write(buffer, currentOffset, currentCount);
}
}
if (async)
{
await _stream.FlushAsync().ConfigureAwait(false);
}
else
{
_stream.Flush();
}
currentOffset += currentCount;
}
}
/// <summary>
/// Set stream length.
/// </summary>
/// <param name="value">Length</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Flush stream
/// </summary>
public override void Flush()
{
// Can sometimes get Pipe broken errors from flushing a PipeStream.
// PipeStream.Flush() also doesn't do anything, anyway.
if (!(_stream is PipeStream))
{
_stream.Flush();
}
}
/// <summary>
/// Get/set stream position
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Seek in stream
/// </summary>
/// <param name="offset">Offset</param>
/// <param name="origin">Origin</param>
/// <returns>Position</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Check if stream can be read from
/// </summary>
public override bool CanRead
{
get { return _stream.CanRead; }
}
/// <summary>
/// Check if stream can be written to
/// </summary>
public override bool CanWrite
{
get { return _stream.CanWrite; }
}
/// <summary>
/// Check if stream can be seeked
/// </summary>
public override bool CanSeek
{
get { return false; } // Seek not supported
}
/// <summary>
/// Get stream length
/// </summary>
public override long Length
{
get
{
throw new NotSupportedException();
}
}
}
}
| |
/*
* ListControl.cs - Implementation of the
* "System.Windows.Forms.ListControl" class.
*
* Copyright (C) 2003 Free Software Foundation
*
* Contributions from Cecilio Pardo <[email protected]>,
* Brian Luft <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Reflection;
using System.Collections;
using System.Globalization;
namespace System.Windows.Forms
{
[TODO]
public abstract class ListControl : Control
{
internal object dataSource;
internal string displayMember;
internal string valueMember;
public BorderStyle BorderStyle
{
get
{
return BorderStyleInternal;
}
set
{
if(BorderStyleInternal != value)
{
BorderStyleInternal = value;
OnBorderStyleChanged(EventArgs.Empty);
}
}
}
protected virtual void OnBorderStyleChanged(EventArgs e)
{
EventHandler handler;
handler = (EventHandler)
(GetHandler(EventId.BorderStyleChanged));
if(handler != null)
{
handler(this, e);
}
}
public virtual Object DataSource
{
get
{
return this.dataSource;
}
set
{
this.dataSource = value;
}
}
public virtual String DisplayMember
{
get
{
return this.displayMember;
}
set
{
this.displayMember = value;
}
}
public virtual String ValueMember
{
get
{
return this.valueMember;
}
set
{
this.valueMember = value;
}
}
public abstract int SelectedIndex { get; set; }
[TODO]
public Object SelectedValue
{
get
{
return null;
}
set
{
}
}
public String GetItemText( Object i )
{
if ( i == null )
{
return null;
}
if ( displayMember == null || displayMember == "" )
{
return i.ToString();
}
PropertyInfo pi;
try
{
pi = i.GetType().GetProperty( displayMember );
}
catch ( AmbiguousMatchException )
{
return null;
}
if ( pi == null )
{
return null;
}
Object v = pi.GetValue( i, null );
if ( v == null )
{
return null;
}
return v.ToString();
}
public event EventHandler DataSourceChanged;
public event EventHandler DisplayMemberChanged;
public event EventHandler SelectedValueChanged;
public event EventHandler SelectedIndexChanged;
public event EventHandler ValueMemberChanged;
[TODO]
protected ListControl()
{
}
[TODO]
protected CurrencyManager DataManager
{
get
{
return null;
}
}
[TODO]
protected override bool IsInputKey( Keys k )
{
return false;
}
protected virtual void OnDataSourceChanged( EventArgs ev )
{
if(this.DataSourceChanged != null)
this.DataSourceChanged(this, ev);
}
protected virtual void OnDisplayMemberChanged( EventArgs ev )
{
if(this.DisplayMemberChanged != null)
this.DisplayMemberChanged(this, ev);
}
protected virtual void OnSelectedIndexChanged( EventArgs ev )
{
if(this.SelectedIndexChanged != null)
this.SelectedIndexChanged(this, ev);
}
protected virtual void OnSelectedValueChanged( EventArgs ev )
{
if(this.SelectedValueChanged != null)
this.SelectedValueChanged(this, ev);
}
protected virtual void OnValueMemberChanged( EventArgs ev )
{
if(this.ValueMemberChanged != null)
this.ValueMemberChanged(this, ev);
}
protected abstract void RefreshItem( int index );
[TODO]
protected virtual void SetItemCore(int index, object value)
{
throw new NotImplementedException("SetItemCore");
}
[TODO]
protected virtual void SetItemsCore(IList value)
{
throw new NotImplementedException("SetItemsCore");
}
internal int FindStringInternal(string s, IList items, int start, bool exact)
{
if (s == null || items == null || start < -1 || start > items.Count - 2)
return -1;
int pos = start;
do
{
pos++;
if (exact)
{
if (string.Compare(s, this.GetItemText(items[pos]), true) == 0)
return pos;
}
else
{
if (string.Compare(s, 0, this.GetItemText(items[pos]), 0, s.Length, true) == 0)
return pos;
}
if (pos == items.Count-1)
pos = -1;
}
while (pos != start);
return -1;
}
}; // class ListControl
}; // namespace System.Windows.Forms
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Arke.DSL.Step;
using Arke.IVR.CallObjects;
using Arke.SipEngine.Api;
using Arke.SipEngine.CallObjects;
using Arke.SipEngine.Events;
using Arke.SipEngine.FSM;
using Arke.SipEngine.Prompts;
namespace Arke.IVR.Prompts
{
public class ArkePromptPlayer : IPromptPlayer
{
private readonly ArkeCall _arkeCall;
private readonly Queue<IPrompt> _promptQueue;
private readonly ISipPromptApi _sipPromptApi;
private LanguageData _languageData;
private string _currentPlaybackId = "";
public ArkePromptPlayer(ArkeCall arkeCall, ISipPromptApi sipPromptApi)
{
_arkeCall = arkeCall;
_sipPromptApi = sipPromptApi;
_promptQueue = new Queue<IPrompt>();
_languageData = LanguageData.English;
}
public void AddPromptToQueue(IPrompt prompt)
{
_arkeCall.Logger.Debug($"Adding prompt to queue, queue size: {_promptQueue.Count}", _arkeCall.LogData);
_promptQueue.Enqueue(prompt);
}
public async Task DoStepAsync(PlayerPromptSettings settings)
{
if (settings.IsInterruptible)
{
_arkeCall.InputProcessor.StartUserInput(true);
}
AddPromptsToQueue(settings.Prompts, settings.Direction);
await _arkeCall.CallStateMachine.FireAsync(settings.IsInterruptible
? Trigger.PlayInterruptiblePrompt
: Trigger.PlayPrompt);
}
public async Task PlayRecordingToLineAsync(string recordingName, string lineId)
{
try
{
_currentPlaybackId = await _sipPromptApi.PlayRecordingToLineAsync(lineId, recordingName);
}
catch (Exception e)
{
_arkeCall.Logger.Error(e, $"Error Playing Prompt: {e.Message}");
if (_arkeCall.GetCurrentState() != State.HangUp)
await _arkeCall.CallStateMachine.FireAsync(Trigger.FinishCall);
}
}
public async Task PlayNumberToLineAsync(string number, string lineId)
{
_promptQueue.Clear();
await _arkeCall.CallStateMachine.FireAsync(Trigger.PlayPrompt);
_currentPlaybackId =
await _sipPromptApi.PlayNumberToLineAsync(lineId, number, _languageData.FolderName);
}
public void AddPromptsToQueue(List<string> prompts, Direction direction)
{
foreach (var prompt in prompts)
{
_promptQueue.Enqueue(new Prompt()
{
PromptFile = prompt,
Direction = direction
});
}
_arkeCall.Logger.Debug($"Added prompts to queue, queue size: {_promptQueue.Count}", _arkeCall.LogData);
}
public void PlayPromptTextToSpeech(string promptText)
{
throw new NotImplementedException("Asterisk Engine currently does not support TTS");
}
public async Task PlayPromptsInQueueAsync()
{
if (_arkeCall.GetCurrentState() == State.StoppingPlayback || _promptQueue.Count == 0)
return;
_arkeCall.Logger.Debug($"Playing next prompt in queue, queue size: {_promptQueue.Count}", _arkeCall.LogData);
try
{
var prompt = _promptQueue.Dequeue();
if (prompt != null)
{
switch (prompt.Direction)
{
case Direction.Incoming:
await PlayPromptToIncomingLineAsync(prompt.PromptFile).ConfigureAwait(false);
break;
case Direction.Outgoing:
await PlayPromptToOutgoingLine(prompt.PromptFile).ConfigureAwait(false);
break;
default:
await PlayPromptToBridge(prompt.PromptFile).ConfigureAwait(false);
break;
}
}
}
catch (Exception)
{
await _arkeCall.CallStateMachine.FireAsync(Trigger.FinishedPrompt);
}
}
public async Task StopPromptAsync()
{
if (_arkeCall.GetCurrentState() == State.PlayingPrompt)
throw new InvalidOperationException("Cannot stop playback of this prompt.");
await _arkeCall.CallStateMachine.FireAsync(Trigger.PromptInterrupted);
_arkeCall.Logger.Debug($"Stopping Prompt {_currentPlaybackId}", _arkeCall.LogData);
await _sipPromptApi.StopPromptAsync(_currentPlaybackId).ConfigureAwait(false);
_promptQueue.Clear();
await _arkeCall.CallStateMachine.FireAsync(Trigger.FinishedPrompt);
}
public async Task PlayPromptToBridge(string promptFile)
{
try
{
_currentPlaybackId = (await _sipPromptApi.PlayPromptToBridgeAsync(
_arkeCall.CallState.GetBridgeId(),
promptFile, _languageData.FolderName).ConfigureAwait(false));
_arkeCall.Logger.Debug($"Prompt file is: {promptFile}");
_arkeCall.Logger.Debug($"Prompt ID: {_currentPlaybackId}", _arkeCall.LogData);
}
catch (Exception ex)
{
_arkeCall.Logger.Error(ex, $"Error Playing Prompt: {ex.Message}");
if (_arkeCall.GetCurrentState() != State.HangUp)
await _arkeCall.CallStateMachine.FireAsync(Trigger.FinishCall);
}
}
public async Task PlayPromptToOutgoingLine(string promptFile)
{
try
{
_currentPlaybackId = (await _sipPromptApi.PlayPromptToLineAsync(
_arkeCall.CallState.GetOutgoingLineId(),
promptFile, _languageData.FolderName).ConfigureAwait(false));
_arkeCall.Logger.Debug($"Prompt file is: {promptFile}");
_arkeCall.Logger.Debug($"Prompt ID: {_currentPlaybackId}", _arkeCall.LogData);
}
catch (Exception ex)
{
_arkeCall.Logger.Error(ex, $"Error Playing Prompt: {ex.Message}");
if (_arkeCall.GetCurrentState() != State.HangUp)
await _arkeCall.CallStateMachine.FireAsync(Trigger.FinishCall);
}
}
public async Task PlayPromptToIncomingLineAsync(string promptFile)
{
try
{
_currentPlaybackId = (await _sipPromptApi.PlayPromptToLineAsync(
_arkeCall.CallState.GetIncomingLineId(),
promptFile, _languageData.FolderName).ConfigureAwait(false));
_arkeCall.Logger.Debug($"Prompt file is: {promptFile}");
_arkeCall.Logger.Debug($"Prompt ID: {_currentPlaybackId}", _arkeCall.LogData);
}
catch (Exception ex)
{
_arkeCall.Logger.Error(ex, $"Error Playing Prompt: {ex.Message}");
if (_arkeCall.GetCurrentState() != State.HangUp)
await _arkeCall.CallStateMachine.FireAsync(Trigger.FinishCall);
}
}
public async Task AriClient_OnPlaybackFinishedEvent(ISipApiClient sipApiClient, PromptPlaybackFinishedEvent e)
{
if (e.PlaybackId != _currentPlaybackId)
return;
if (_arkeCall.GetCurrentState() == State.StoppingPlayback)
return;
await _arkeCall.CallStateMachine.FireAsync(
_promptQueue.Count == 0 ? Trigger.FinishedPrompt : Trigger.PlayNextPrompt);
}
public void SetLanguageCode(LanguageData language)
{
_languageData = language;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Eventarc.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedEventarcClientSnippets
{
/// <summary>Snippet for GetTrigger</summary>
public void GetTriggerRequestObject()
{
// Snippet: GetTrigger(GetTriggerRequest, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
GetTriggerRequest request = new GetTriggerRequest
{
TriggerName = TriggerName.FromProjectLocationTrigger("[PROJECT]", "[LOCATION]", "[TRIGGER]"),
};
// Make the request
Trigger response = eventarcClient.GetTrigger(request);
// End snippet
}
/// <summary>Snippet for GetTriggerAsync</summary>
public async Task GetTriggerRequestObjectAsync()
{
// Snippet: GetTriggerAsync(GetTriggerRequest, CallSettings)
// Additional: GetTriggerAsync(GetTriggerRequest, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
GetTriggerRequest request = new GetTriggerRequest
{
TriggerName = TriggerName.FromProjectLocationTrigger("[PROJECT]", "[LOCATION]", "[TRIGGER]"),
};
// Make the request
Trigger response = await eventarcClient.GetTriggerAsync(request);
// End snippet
}
/// <summary>Snippet for GetTrigger</summary>
public void GetTrigger()
{
// Snippet: GetTrigger(string, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/triggers/[TRIGGER]";
// Make the request
Trigger response = eventarcClient.GetTrigger(name);
// End snippet
}
/// <summary>Snippet for GetTriggerAsync</summary>
public async Task GetTriggerAsync()
{
// Snippet: GetTriggerAsync(string, CallSettings)
// Additional: GetTriggerAsync(string, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/triggers/[TRIGGER]";
// Make the request
Trigger response = await eventarcClient.GetTriggerAsync(name);
// End snippet
}
/// <summary>Snippet for GetTrigger</summary>
public void GetTriggerResourceNames()
{
// Snippet: GetTrigger(TriggerName, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
TriggerName name = TriggerName.FromProjectLocationTrigger("[PROJECT]", "[LOCATION]", "[TRIGGER]");
// Make the request
Trigger response = eventarcClient.GetTrigger(name);
// End snippet
}
/// <summary>Snippet for GetTriggerAsync</summary>
public async Task GetTriggerResourceNamesAsync()
{
// Snippet: GetTriggerAsync(TriggerName, CallSettings)
// Additional: GetTriggerAsync(TriggerName, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
TriggerName name = TriggerName.FromProjectLocationTrigger("[PROJECT]", "[LOCATION]", "[TRIGGER]");
// Make the request
Trigger response = await eventarcClient.GetTriggerAsync(name);
// End snippet
}
/// <summary>Snippet for ListTriggers</summary>
public void ListTriggersRequestObject()
{
// Snippet: ListTriggers(ListTriggersRequest, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
ListTriggersRequest request = new ListTriggersRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
OrderBy = "",
};
// Make the request
PagedEnumerable<ListTriggersResponse, Trigger> response = eventarcClient.ListTriggers(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Trigger item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTriggersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trigger item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trigger> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trigger item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTriggersAsync</summary>
public async Task ListTriggersRequestObjectAsync()
{
// Snippet: ListTriggersAsync(ListTriggersRequest, CallSettings)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
ListTriggersRequest request = new ListTriggersRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
OrderBy = "",
};
// Make the request
PagedAsyncEnumerable<ListTriggersResponse, Trigger> response = eventarcClient.ListTriggersAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Trigger item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTriggersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trigger item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trigger> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trigger item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTriggers</summary>
public void ListTriggers()
{
// Snippet: ListTriggers(string, string, int?, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListTriggersResponse, Trigger> response = eventarcClient.ListTriggers(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Trigger item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTriggersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trigger item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trigger> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trigger item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTriggersAsync</summary>
public async Task ListTriggersAsync()
{
// Snippet: ListTriggersAsync(string, string, int?, CallSettings)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListTriggersResponse, Trigger> response = eventarcClient.ListTriggersAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Trigger item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTriggersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trigger item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trigger> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trigger item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTriggers</summary>
public void ListTriggersResourceNames()
{
// Snippet: ListTriggers(LocationName, string, int?, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListTriggersResponse, Trigger> response = eventarcClient.ListTriggers(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Trigger item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTriggersResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trigger item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trigger> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trigger item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTriggersAsync</summary>
public async Task ListTriggersResourceNamesAsync()
{
// Snippet: ListTriggersAsync(LocationName, string, int?, CallSettings)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListTriggersResponse, Trigger> response = eventarcClient.ListTriggersAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Trigger item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTriggersResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trigger item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trigger> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trigger item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CreateTrigger</summary>
public void CreateTriggerRequestObject()
{
// Snippet: CreateTrigger(CreateTriggerRequest, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
CreateTriggerRequest request = new CreateTriggerRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Trigger = new Trigger(),
TriggerId = "",
ValidateOnly = false,
};
// Make the request
Operation<Trigger, OperationMetadata> response = eventarcClient.CreateTrigger(request);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = eventarcClient.PollOnceCreateTrigger(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTriggerAsync</summary>
public async Task CreateTriggerRequestObjectAsync()
{
// Snippet: CreateTriggerAsync(CreateTriggerRequest, CallSettings)
// Additional: CreateTriggerAsync(CreateTriggerRequest, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
CreateTriggerRequest request = new CreateTriggerRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Trigger = new Trigger(),
TriggerId = "",
ValidateOnly = false,
};
// Make the request
Operation<Trigger, OperationMetadata> response = await eventarcClient.CreateTriggerAsync(request);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceCreateTriggerAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTrigger</summary>
public void CreateTrigger()
{
// Snippet: CreateTrigger(string, Trigger, string, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
Trigger trigger = new Trigger();
string triggerId = "";
// Make the request
Operation<Trigger, OperationMetadata> response = eventarcClient.CreateTrigger(parent, trigger, triggerId);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = eventarcClient.PollOnceCreateTrigger(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTriggerAsync</summary>
public async Task CreateTriggerAsync()
{
// Snippet: CreateTriggerAsync(string, Trigger, string, CallSettings)
// Additional: CreateTriggerAsync(string, Trigger, string, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
Trigger trigger = new Trigger();
string triggerId = "";
// Make the request
Operation<Trigger, OperationMetadata> response = await eventarcClient.CreateTriggerAsync(parent, trigger, triggerId);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceCreateTriggerAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTrigger</summary>
public void CreateTriggerResourceNames()
{
// Snippet: CreateTrigger(LocationName, Trigger, string, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
Trigger trigger = new Trigger();
string triggerId = "";
// Make the request
Operation<Trigger, OperationMetadata> response = eventarcClient.CreateTrigger(parent, trigger, triggerId);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = eventarcClient.PollOnceCreateTrigger(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTriggerAsync</summary>
public async Task CreateTriggerResourceNamesAsync()
{
// Snippet: CreateTriggerAsync(LocationName, Trigger, string, CallSettings)
// Additional: CreateTriggerAsync(LocationName, Trigger, string, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
Trigger trigger = new Trigger();
string triggerId = "";
// Make the request
Operation<Trigger, OperationMetadata> response = await eventarcClient.CreateTriggerAsync(parent, trigger, triggerId);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceCreateTriggerAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTrigger</summary>
public void UpdateTriggerRequestObject()
{
// Snippet: UpdateTrigger(UpdateTriggerRequest, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
UpdateTriggerRequest request = new UpdateTriggerRequest
{
Trigger = new Trigger(),
UpdateMask = new FieldMask(),
AllowMissing = false,
ValidateOnly = false,
};
// Make the request
Operation<Trigger, OperationMetadata> response = eventarcClient.UpdateTrigger(request);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = eventarcClient.PollOnceUpdateTrigger(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTriggerAsync</summary>
public async Task UpdateTriggerRequestObjectAsync()
{
// Snippet: UpdateTriggerAsync(UpdateTriggerRequest, CallSettings)
// Additional: UpdateTriggerAsync(UpdateTriggerRequest, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
UpdateTriggerRequest request = new UpdateTriggerRequest
{
Trigger = new Trigger(),
UpdateMask = new FieldMask(),
AllowMissing = false,
ValidateOnly = false,
};
// Make the request
Operation<Trigger, OperationMetadata> response = await eventarcClient.UpdateTriggerAsync(request);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceUpdateTriggerAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTrigger</summary>
public void UpdateTrigger()
{
// Snippet: UpdateTrigger(Trigger, FieldMask, bool, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
Trigger trigger = new Trigger();
FieldMask updateMask = new FieldMask();
bool allowMissing = false;
// Make the request
Operation<Trigger, OperationMetadata> response = eventarcClient.UpdateTrigger(trigger, updateMask, allowMissing);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = eventarcClient.PollOnceUpdateTrigger(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTriggerAsync</summary>
public async Task UpdateTriggerAsync()
{
// Snippet: UpdateTriggerAsync(Trigger, FieldMask, bool, CallSettings)
// Additional: UpdateTriggerAsync(Trigger, FieldMask, bool, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
Trigger trigger = new Trigger();
FieldMask updateMask = new FieldMask();
bool allowMissing = false;
// Make the request
Operation<Trigger, OperationMetadata> response = await eventarcClient.UpdateTriggerAsync(trigger, updateMask, allowMissing);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceUpdateTriggerAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTrigger</summary>
public void DeleteTriggerRequestObject()
{
// Snippet: DeleteTrigger(DeleteTriggerRequest, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
DeleteTriggerRequest request = new DeleteTriggerRequest
{
TriggerName = TriggerName.FromProjectLocationTrigger("[PROJECT]", "[LOCATION]", "[TRIGGER]"),
Etag = "",
AllowMissing = false,
ValidateOnly = false,
};
// Make the request
Operation<Trigger, OperationMetadata> response = eventarcClient.DeleteTrigger(request);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = eventarcClient.PollOnceDeleteTrigger(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTriggerAsync</summary>
public async Task DeleteTriggerRequestObjectAsync()
{
// Snippet: DeleteTriggerAsync(DeleteTriggerRequest, CallSettings)
// Additional: DeleteTriggerAsync(DeleteTriggerRequest, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
DeleteTriggerRequest request = new DeleteTriggerRequest
{
TriggerName = TriggerName.FromProjectLocationTrigger("[PROJECT]", "[LOCATION]", "[TRIGGER]"),
Etag = "",
AllowMissing = false,
ValidateOnly = false,
};
// Make the request
Operation<Trigger, OperationMetadata> response = await eventarcClient.DeleteTriggerAsync(request);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceDeleteTriggerAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTrigger</summary>
public void DeleteTrigger()
{
// Snippet: DeleteTrigger(string, bool, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/triggers/[TRIGGER]";
bool allowMissing = false;
// Make the request
Operation<Trigger, OperationMetadata> response = eventarcClient.DeleteTrigger(name, allowMissing);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = eventarcClient.PollOnceDeleteTrigger(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTriggerAsync</summary>
public async Task DeleteTriggerAsync()
{
// Snippet: DeleteTriggerAsync(string, bool, CallSettings)
// Additional: DeleteTriggerAsync(string, bool, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/triggers/[TRIGGER]";
bool allowMissing = false;
// Make the request
Operation<Trigger, OperationMetadata> response = await eventarcClient.DeleteTriggerAsync(name, allowMissing);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceDeleteTriggerAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTrigger</summary>
public void DeleteTriggerResourceNames()
{
// Snippet: DeleteTrigger(TriggerName, bool, CallSettings)
// Create client
EventarcClient eventarcClient = EventarcClient.Create();
// Initialize request argument(s)
TriggerName name = TriggerName.FromProjectLocationTrigger("[PROJECT]", "[LOCATION]", "[TRIGGER]");
bool allowMissing = false;
// Make the request
Operation<Trigger, OperationMetadata> response = eventarcClient.DeleteTrigger(name, allowMissing);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = eventarcClient.PollOnceDeleteTrigger(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTriggerAsync</summary>
public async Task DeleteTriggerResourceNamesAsync()
{
// Snippet: DeleteTriggerAsync(TriggerName, bool, CallSettings)
// Additional: DeleteTriggerAsync(TriggerName, bool, CancellationToken)
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
TriggerName name = TriggerName.FromProjectLocationTrigger("[PROJECT]", "[LOCATION]", "[TRIGGER]");
bool allowMissing = false;
// Make the request
Operation<Trigger, OperationMetadata> response = await eventarcClient.DeleteTriggerAsync(name, allowMissing);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceDeleteTriggerAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
// 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.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.PortableExecutable
{
public class ManagedPEBuilder : PEBuilder
{
public const int ManagedResourcesDataAlignment = ManagedTextSection.ManagedResourcesDataAlignment;
public const int MappedFieldDataAlignment = ManagedTextSection.MappedFieldDataAlignment;
private const int DefaultStrongNameSignatureSize = 128;
private const string TextSectionName = ".text";
private const string ResourceSectionName = ".rsrc";
private const string RelocationSectionName = ".reloc";
private readonly PEDirectoriesBuilder _peDirectoriesBuilder;
private readonly MetadataRootBuilder _metadataRootBuilder;
private readonly BlobBuilder _ilStream;
private readonly BlobBuilder _mappedFieldDataOpt;
private readonly BlobBuilder _managedResourcesOpt;
private readonly ResourceSectionBuilder _nativeResourcesOpt;
private readonly int _strongNameSignatureSize;
private readonly MethodDefinitionHandle _entryPointOpt;
private readonly DebugDirectoryBuilder _debugDirectoryBuilderOpt;
private readonly CorFlags _corFlags;
private int _lazyEntryPointAddress;
private Blob _lazyStrongNameSignature;
public ManagedPEBuilder(
PEHeaderBuilder header,
MetadataRootBuilder metadataRootBuilder,
BlobBuilder ilStream,
BlobBuilder mappedFieldData = null,
BlobBuilder managedResources = null,
ResourceSectionBuilder nativeResources = null,
DebugDirectoryBuilder debugDirectoryBuilder = null,
int strongNameSignatureSize = DefaultStrongNameSignatureSize,
MethodDefinitionHandle entryPoint = default(MethodDefinitionHandle),
CorFlags flags = CorFlags.ILOnly,
Func<IEnumerable<Blob>, BlobContentId> deterministicIdProvider = null)
: base(header, deterministicIdProvider)
{
if (header == null)
{
Throw.ArgumentNull(nameof(header));
}
if (metadataRootBuilder == null)
{
Throw.ArgumentNull(nameof(metadataRootBuilder));
}
if (ilStream == null)
{
Throw.ArgumentNull(nameof(ilStream));
}
if (strongNameSignatureSize < 0)
{
Throw.ArgumentOutOfRange(nameof(strongNameSignatureSize));
}
_metadataRootBuilder = metadataRootBuilder;
_ilStream = ilStream;
_mappedFieldDataOpt = mappedFieldData;
_managedResourcesOpt = managedResources;
_nativeResourcesOpt = nativeResources;
_strongNameSignatureSize = strongNameSignatureSize;
_entryPointOpt = entryPoint;
_debugDirectoryBuilderOpt = debugDirectoryBuilder ?? CreateDefaultDebugDirectoryBuilder();
_corFlags = flags;
_peDirectoriesBuilder = new PEDirectoriesBuilder();
}
private DebugDirectoryBuilder CreateDefaultDebugDirectoryBuilder()
{
if (IsDeterministic)
{
var builder = new DebugDirectoryBuilder();
builder.AddReproducibleEntry();
return builder;
}
return null;
}
protected override ImmutableArray<Section> CreateSections()
{
var builder = ImmutableArray.CreateBuilder<Section>(3);
builder.Add(new Section(TextSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemExecute | SectionCharacteristics.ContainsCode));
if (_nativeResourcesOpt != null)
{
builder.Add(new Section(ResourceSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData));
}
if (Header.Machine == Machine.I386 || Header.Machine == 0)
{
builder.Add(new Section(RelocationSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemDiscardable | SectionCharacteristics.ContainsInitializedData));
}
return builder.ToImmutable();
}
protected override BlobBuilder SerializeSection(string name, SectionLocation location)
{
switch (name)
{
case TextSectionName:
return SerializeTextSection(location);
case ResourceSectionName:
return SerializeResourceSection(location);
case RelocationSectionName:
return SerializeRelocationSection(location);
default:
throw new ArgumentException(SR.Format(SR.UnknownSectionName, name), nameof(name));
}
}
private BlobBuilder SerializeTextSection(SectionLocation location)
{
var sectionBuilder = new BlobBuilder();
var metadataBuilder = new BlobBuilder();
var metadataSizes = _metadataRootBuilder.Sizes;
var textSection = new ManagedTextSection(
imageCharacteristics: Header.ImageCharacteristics,
machine: Header.Machine,
ilStreamSize: _ilStream.Count,
metadataSize: metadataSizes.MetadataSize,
resourceDataSize: _managedResourcesOpt?.Count ?? 0,
strongNameSignatureSize: _strongNameSignatureSize,
debugDataSize: _debugDirectoryBuilderOpt?.Size ?? 0,
mappedFieldDataSize: _mappedFieldDataOpt?.Count ?? 0);
int methodBodyStreamRva = location.RelativeVirtualAddress + textSection.OffsetToILStream;
int mappedFieldDataStreamRva = location.RelativeVirtualAddress + textSection.CalculateOffsetToMappedFieldDataStream();
_metadataRootBuilder.Serialize(metadataBuilder, methodBodyStreamRva, mappedFieldDataStreamRva);
DirectoryEntry debugDirectoryEntry;
BlobBuilder debugTableBuilderOpt;
if (_debugDirectoryBuilderOpt != null)
{
int debugDirectoryOffset = textSection.ComputeOffsetToDebugDirectory();
debugTableBuilderOpt = new BlobBuilder(_debugDirectoryBuilderOpt.TableSize);
_debugDirectoryBuilderOpt.Serialize(debugTableBuilderOpt, location, debugDirectoryOffset);
// Only the size of the fixed part of the debug table goes here.
debugDirectoryEntry = new DirectoryEntry(
location.RelativeVirtualAddress + debugDirectoryOffset,
_debugDirectoryBuilderOpt.TableSize);
}
else
{
debugTableBuilderOpt = null;
debugDirectoryEntry = default(DirectoryEntry);
}
_lazyEntryPointAddress = textSection.GetEntryPointAddress(location.RelativeVirtualAddress);
textSection.Serialize(
sectionBuilder,
location.RelativeVirtualAddress,
_entryPointOpt.IsNil ? 0 : MetadataTokens.GetToken(_entryPointOpt),
_corFlags,
Header.ImageBase,
metadataBuilder,
_ilStream,
_mappedFieldDataOpt,
_managedResourcesOpt,
debugTableBuilderOpt,
out _lazyStrongNameSignature);
_peDirectoriesBuilder.AddressOfEntryPoint = _lazyEntryPointAddress;
_peDirectoriesBuilder.DebugTable = debugDirectoryEntry;
_peDirectoriesBuilder.ImportAddressTable = textSection.GetImportAddressTableDirectoryEntry(location.RelativeVirtualAddress);
_peDirectoriesBuilder.ImportTable = textSection.GetImportTableDirectoryEntry(location.RelativeVirtualAddress);
_peDirectoriesBuilder.CorHeaderTable = textSection.GetCorHeaderDirectoryEntry(location.RelativeVirtualAddress);
return sectionBuilder;
}
private BlobBuilder SerializeResourceSection(SectionLocation location)
{
Debug.Assert(_nativeResourcesOpt != null);
var sectionBuilder = new BlobBuilder();
_nativeResourcesOpt.Serialize(sectionBuilder, location);
_peDirectoriesBuilder.ResourceTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count);
return sectionBuilder;
}
private BlobBuilder SerializeRelocationSection(SectionLocation location)
{
var sectionBuilder = new BlobBuilder();
WriteRelocationSection(sectionBuilder, Header.Machine, _lazyEntryPointAddress);
_peDirectoriesBuilder.BaseRelocationTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count);
return sectionBuilder;
}
private static void WriteRelocationSection(BlobBuilder builder, Machine machine, int entryPointAddress)
{
Debug.Assert(builder.Count == 0);
builder.WriteUInt32((((uint)entryPointAddress + 2) / 0x1000) * 0x1000);
builder.WriteUInt32((machine == Machine.IA64) ? 14u : 12u);
uint offsetWithinPage = ((uint)entryPointAddress + 2) % 0x1000;
uint relocType = (machine == Machine.Amd64 || machine == Machine.IA64) ? 10u : 3u;
ushort s = (ushort)((relocType << 12) | offsetWithinPage);
builder.WriteUInt16(s);
if (machine == Machine.IA64)
{
builder.WriteUInt32(relocType << 12);
}
builder.WriteUInt16(0); // next chunk's RVA
}
protected internal override PEDirectoriesBuilder GetDirectories()
{
return _peDirectoriesBuilder;
}
private IEnumerable<Blob> GetContentToSign(BlobBuilder peImage)
{
// Signed content includes
// - PE header without its alignment padding
// - all sections including their alignment padding and excluding strong name signature blob
int remainingHeader = Header.ComputeSizeOfPeHeaders(GetSections().Length);
foreach (var blob in peImage.GetBlobs())
{
if (remainingHeader > 0)
{
int length = Math.Min(remainingHeader, blob.Length);
yield return new Blob(blob.Buffer, blob.Start, length);
remainingHeader -= length;
}
else if (blob.Buffer == _lazyStrongNameSignature.Buffer)
{
yield return new Blob(blob.Buffer, blob.Start, _lazyStrongNameSignature.Start - blob.Start);
yield return new Blob(blob.Buffer, _lazyStrongNameSignature.Start + _lazyStrongNameSignature.Length, blob.Length - _lazyStrongNameSignature.Length);
}
else
{
yield return new Blob(blob.Buffer, blob.Start, blob.Length);
}
}
}
public void Sign(BlobBuilder peImage, Func<IEnumerable<Blob>, byte[]> signatureProvider)
{
if (peImage == null)
{
throw new ArgumentNullException(nameof(peImage));
}
if (signatureProvider == null)
{
throw new ArgumentNullException(nameof(signatureProvider));
}
var content = GetContentToSign(peImage);
byte[] signature = signatureProvider(content);
// signature may be shorter (the rest of the reserved space is padding):
if (signature == null || signature.Length > _lazyStrongNameSignature.Length)
{
throw new InvalidOperationException(SR.SignatureProviderReturnedInvalidSignature);
}
// TODO: Native csc also calculates and fills checksum in the PE header
// Using MapFileAndCheckSum() from imagehlp.dll.
var writer = new BlobWriter(_lazyStrongNameSignature);
writer.WriteBytes(signature);
}
}
}
| |
// 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.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection
{
public class ApplicationModelConventionExtensionsTest
{
[Fact]
public void DefaultParameterModelConvention_AppliesToAllParametersInApp()
{
// Arrange
var app = new ApplicationModel();
var controllerType = typeof(HelloController);
var controllerModel = new ControllerModel(controllerType.GetTypeInfo(), Array.Empty<object>());
app.Controllers.Add(controllerModel);
var actionModel = new ActionModel(controllerType.GetMethod(nameof(HelloController.GetInfo)), Array.Empty<object>());
controllerModel.Actions.Add(actionModel);
var parameterModel = new ParameterModel(
controllerType.GetMethod(nameof(HelloController.GetInfo)).GetParameters()[0],
Array.Empty<object>());
actionModel.Parameters.Add(parameterModel);
var options = new MvcOptions();
options.Conventions.Add(new SimpleParameterConvention());
// Act
options.Conventions[0].Apply(app);
// Assert
var kvp = Assert.Single(parameterModel.Properties);
Assert.Equal("TestProperty", kvp.Key);
Assert.Equal("TestValue", kvp.Value);
}
[Fact]
public void DefaultActionModelConvention_AppliesToAllActionsInApp()
{
// Arrange
var app = new ApplicationModel();
var controllerType1 = typeof(HelloController).GetTypeInfo();
var actionMethod1 = controllerType1.GetMethod(nameof(HelloController.GetHello));
var controllerModel1 = new ControllerModel(controllerType1, Array.Empty<object>())
{
Actions =
{
new ActionModel(actionMethod1, Array.Empty<object>()),
}
};
var controllerType2 = typeof(WorldController).GetTypeInfo();
var actionMethod2 = controllerType2.GetMethod(nameof(WorldController.GetWorld));
var controllerModel2 = new ControllerModel(controllerType2, Array.Empty<object>())
{
Actions =
{
new ActionModel(actionMethod2, Array.Empty<object>()),
},
};
app.Controllers.Add(controllerModel1);
app.Controllers.Add(controllerModel2);
var options = new MvcOptions();
options.Conventions.Add(new SimpleActionConvention());
// Act
options.Conventions[0].Apply(app);
// Assert
var kvp = Assert.Single(controllerModel1.Actions[0].Properties);
Assert.Equal("TestProperty", kvp.Key);
Assert.Equal("TestValue", kvp.Value);
kvp = Assert.Single(controllerModel2.Actions[0].Properties);
Assert.Equal("TestProperty", kvp.Key);
Assert.Equal("TestValue", kvp.Value);
}
[Fact]
public void AddedParameterConvention_AppliesToAllPropertiesAndParameters()
{
// Arrange
var app = new ApplicationModel();
var controllerType1 = typeof(HelloController).GetTypeInfo();
var parameterModel1 = new ParameterModel(
controllerType1.GetMethod(nameof(HelloController.GetInfo)).GetParameters()[0],
Array.Empty<object>());
var actionMethod1 = controllerType1.GetMethod(nameof(HelloController.GetInfo));
var property1 = controllerType1.GetProperty(nameof(HelloController.Property1));
var controllerModel1 = new ControllerModel(controllerType1, Array.Empty<object>())
{
ControllerProperties =
{
new PropertyModel(property1, Array.Empty<object>()),
},
Actions =
{
new ActionModel(actionMethod1, Array.Empty<object>())
{
Parameters =
{
parameterModel1,
}
}
}
};
var controllerType2 = typeof(WorldController).GetTypeInfo();
var property2 = controllerType2.GetProperty(nameof(WorldController.Property2));
var controllerModel2 = new ControllerModel(controllerType2, Array.Empty<object>())
{
ControllerProperties =
{
new PropertyModel(property2, Array.Empty<object>()),
},
};
app.Controllers.Add(controllerModel1);
app.Controllers.Add(controllerModel2);
var options = new MvcOptions();
var convention = new SimplePropertyConvention();
options.Conventions.Add(convention);
// Act
ApplicationModelConventions.ApplyConventions(app, options.Conventions);
// Assert
var kvp = Assert.Single(controllerModel1.ControllerProperties[0].Properties);
Assert.Equal("TestProperty", kvp.Key);
Assert.Equal("TestValue", kvp.Value);
kvp = Assert.Single(controllerModel2.ControllerProperties[0].Properties);
Assert.Equal("TestProperty", kvp.Key);
Assert.Equal("TestValue", kvp.Value);
kvp = Assert.Single(controllerModel1.Actions[0].Parameters[0].Properties);
Assert.Equal("TestProperty", kvp.Key);
Assert.Equal("TestValue", kvp.Value);
}
[Fact]
public void DefaultControllerModelConvention_AppliesToAllControllers()
{
// Arrange
var options = new MvcOptions();
var app = new ApplicationModel();
app.Controllers.Add(new ControllerModel(typeof(HelloController).GetTypeInfo(), Array.Empty<object>()));
app.Controllers.Add(new ControllerModel(typeof(WorldController).GetTypeInfo(), Array.Empty<object>()));
options.Conventions.Add(new SimpleControllerConvention());
// Act
options.Conventions[0].Apply(app);
// Assert
foreach (var controller in app.Controllers)
{
var kvp = Assert.Single(controller.Properties);
Assert.Equal("TestProperty", kvp.Key);
Assert.Equal("TestValue", kvp.Value);
}
}
[Fact]
public void RemoveType_RemovesAllOfType()
{
// Arrange
var list = new List<IApplicationModelConvention>
{
new FooApplicationModelConvention(),
new BarApplicationModelConvention(),
new FooApplicationModelConvention()
};
// Act
list.RemoveType(typeof(FooApplicationModelConvention));
// Assert
var convention = Assert.Single(list);
Assert.IsType<BarApplicationModelConvention>(convention);
}
[Fact]
public void ApplicationModelConventions_CopiesControllerModelCollectionOnApply()
{
// Arrange
var applicationModel = new ApplicationModel();
applicationModel.Controllers.Add(
new ControllerModel(typeof(HelloController).GetTypeInfo(), Array.Empty<object>())
{
Application = applicationModel
});
var controllerModelConvention = new ControllerModelCollectionModifyingConvention();
var conventions = new List<IApplicationModelConvention>();
conventions.Add(controllerModelConvention);
// Act & Assert
ApplicationModelConventions.ApplyConventions(applicationModel, conventions);
}
[Fact]
public void ApplicationModelConventions_CopiesControllerModelCollectionOnApply_WhenRegisteredAsAnAttribute()
{
// Arrange
var controllerModelConvention = new ControllerModelCollectionModifyingConvention();
var applicationModel = new ApplicationModel();
applicationModel.Controllers.Add(
new ControllerModel(typeof(HelloController).GetTypeInfo(), new[] { controllerModelConvention })
{
Application = applicationModel
});
var conventions = new List<IApplicationModelConvention>();
// Act & Assert
ApplicationModelConventions.ApplyConventions(applicationModel, conventions);
}
[Fact]
public void ApplicationModelConventions_CopiesActionModelCollectionOnApply()
{
// Arrange
var controllerType = typeof(HelloController).GetTypeInfo();
var applicationModel = new ApplicationModel();
var controllerModel = new ControllerModel(controllerType, Array.Empty<object>())
{
Application = applicationModel
};
controllerModel.Actions.Add(
new ActionModel(controllerType.GetMethod(nameof(HelloController.GetHello)), Array.Empty<object>())
{
Controller = controllerModel
});
applicationModel.Controllers.Add(controllerModel);
var actionModelConvention = new ActionModelCollectionModifyingConvention();
var conventions = new List<IApplicationModelConvention>();
conventions.Add(actionModelConvention);
// Act & Assert
ApplicationModelConventions.ApplyConventions(applicationModel, conventions);
}
[Fact]
public void ApplicationModelConventions_CopiesPropertyModelCollectionOnApply()
{
// Arrange
var controllerType = typeof(HelloController).GetTypeInfo();
var applicationModel = new ApplicationModel();
var controllerModel = new ControllerModel(controllerType, Array.Empty<object>())
{
Application = applicationModel
};
controllerModel.ControllerProperties.Add(
new PropertyModel(controllerType.GetProperty(nameof(HelloController.Property1)), Array.Empty<object>())
{
Controller = controllerModel
});
applicationModel.Controllers.Add(controllerModel);
var propertyModelConvention = new ParameterModelBaseConvention();
var conventions = new List<IApplicationModelConvention>();
conventions.Add(propertyModelConvention);
// Act & Assert
ApplicationModelConventions.ApplyConventions(applicationModel, conventions);
}
[Fact]
public void ApplicationModelConventions_CopiesPropertyModelCollectionOnApply_WhenAppliedViaAttributes()
{
// Arrange
var propertyModelConvention = new ParameterModelBaseConvention();
var controllerType = typeof(HelloController).GetTypeInfo();
var applicationModel = new ApplicationModel();
var controllerModel = new ControllerModel(controllerType, Array.Empty<object>())
{
Application = applicationModel
};
controllerModel.ControllerProperties.Add(
new PropertyModel(controllerType.GetProperty(nameof(HelloController.Property1)), new[] { propertyModelConvention })
{
Controller = controllerModel
});
applicationModel.Controllers.Add(controllerModel);
var conventions = new List<IApplicationModelConvention>();
// Act & Assert
ApplicationModelConventions.ApplyConventions(applicationModel, conventions);
}
[Fact]
public void ApplicationModelConventions_CopiesParameterModelCollectionOnApply()
{
// Arrange
var controllerType = typeof(HelloController).GetTypeInfo();
var app = new ApplicationModel();
var controllerModel = new ControllerModel(controllerType, Array.Empty<object>())
{
Application = app
};
app.Controllers.Add(controllerModel);
var actionModel = new ActionModel(controllerType.GetMethod(nameof(HelloController.GetInfo)), Array.Empty<object>())
{
Controller = controllerModel
};
controllerModel.Actions.Add(actionModel);
var parameterModel = new ParameterModel(
controllerType.GetMethod(nameof(HelloController.GetInfo)).GetParameters()[0],
Array.Empty<object>())
{
Action = actionModel
};
actionModel.Parameters.Add(parameterModel);
var parameterModelConvention = new ParameterModelCollectionModifyingConvention();
var conventions = new List<IApplicationModelConvention>();
conventions.Add(parameterModelConvention);
// Act & Assert
ApplicationModelConventions.ApplyConventions(app, conventions);
}
[Fact]
public void ApplicationModelConventions_CopiesParameterModelCollectionOnApply_WhenRegisteredViaAttribute()
{
// Arrange
var parameterModelConvention = new ParameterModelCollectionModifyingConvention();
var controllerType = typeof(HelloController).GetTypeInfo();
var app = new ApplicationModel();
var controllerModel = new ControllerModel(controllerType, Array.Empty<object>())
{
Application = app
};
app.Controllers.Add(controllerModel);
var actionModel = new ActionModel(controllerType.GetMethod(nameof(HelloController.GetInfo)), Array.Empty<object>())
{
Controller = controllerModel
};
controllerModel.Actions.Add(actionModel);
var parameterModel = new ParameterModel(
controllerType.GetMethod(nameof(HelloController.GetInfo)).GetParameters()[0],
new[] { parameterModelConvention })
{
Action = actionModel
};
actionModel.Parameters.Add(parameterModel);
var conventions = new List<IApplicationModelConvention>();
// Act & Assert
ApplicationModelConventions.ApplyConventions(app, conventions);
}
[Fact]
public void GenericRemoveType_RemovesAllOfType()
{
// Arrange
var list = new List<IApplicationModelConvention>
{
new FooApplicationModelConvention(),
new BarApplicationModelConvention(),
new FooApplicationModelConvention()
};
// Act
list.RemoveType<FooApplicationModelConvention>();
// Assert
var convention = Assert.Single(list);
Assert.IsType<BarApplicationModelConvention>(convention);
}
private class FooApplicationModelConvention : IApplicationModelConvention
{
public void Apply(ApplicationModel application)
{
throw new NotImplementedException();
}
}
private class BarApplicationModelConvention : IApplicationModelConvention
{
public void Apply(ApplicationModel application)
{
throw new NotImplementedException();
}
}
private class HelloController
{
public string Property1 { get; set; }
public string GetHello()
{
return "Hello";
}
public string GetInfo(int id)
{
return "GetInfo(int id)";
}
}
private class WorldController
{
public string Property2 { get; set; }
public string GetWorld()
{
return "World!";
}
}
private class SimpleParameterConvention : IParameterModelConvention
{
public void Apply(ParameterModel parameter)
{
parameter.Properties.Add("TestProperty", "TestValue");
}
}
private class SimpleActionConvention : IActionModelConvention
{
public void Apply(ActionModel action)
{
action.Properties.Add("TestProperty", "TestValue");
}
}
private class SimplePropertyConvention : IParameterModelBaseConvention
{
public void Apply(ParameterModelBase action)
{
action.Properties.Add("TestProperty", "TestValue");
}
}
private class SimpleControllerConvention : IControllerModelConvention
{
public void Apply(ControllerModel controller)
{
controller.Properties.Add("TestProperty", "TestValue");
}
}
private class ControllerModelCollectionModifyingConvention : IControllerModelConvention
{
public void Apply(ControllerModel controller)
{
controller.Application.Controllers.Remove(controller);
}
}
private class TestApplicationModelConvention : IApplicationModelConvention
{
public void Apply(ApplicationModel application)
{
application.Controllers.RemoveAt(0);
}
}
private class ActionModelCollectionModifyingConvention : IActionModelConvention
{
public void Apply(ActionModel action)
{
action.Controller.Actions.Remove(action);
}
}
private class ParameterModelBaseConvention : IParameterModelBaseConvention
{
public void Apply(ParameterModelBase modelBase)
{
var property = (PropertyModel)modelBase;
property.Controller.ControllerProperties.Remove(property);
}
}
private class ParameterModelCollectionModifyingConvention : IParameterModelConvention
{
public void Apply(ParameterModel parameter)
{
parameter.Action.Parameters.Remove(parameter);
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations for managing Azure SQL Database secure
/// connection. Contains operations to: Create, Retrieve and Update
/// secure connection policy .
/// </summary>
internal partial class SecureConnectionPolicyOperations : IServiceOperations<SqlManagementClient>, ISecureConnectionPolicyOperations
{
/// <summary>
/// Initializes a new instance of the SecureConnectionPolicyOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SecureConnectionPolicyOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates an Azure SQL Database Server Firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the policy
/// applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// secure connection policy.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateOrUpdateDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, DatabaseSecureConnectionPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateDatabasePolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/connectionPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject databaseSecureConnectionPolicyCreateOrUpdateParametersValue = new JObject();
requestDoc = databaseSecureConnectionPolicyCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
databaseSecureConnectionPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.SecurityEnabledAccess != null)
{
propertiesValue["securityEnabledAccess"] = parameters.Properties.SecurityEnabledAccess;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns an Azure SQL Database secure connection policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the secure
/// connection policy applies.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get database secure connection request.
/// </returns>
public async Task<DatabaseSecureConnectionPolicyGetResponse> GetDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "GetDatabasePolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/connectionPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseSecureConnectionPolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseSecureConnectionPolicyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DatabaseSecureConnectionPolicy secureConnectionPolicyInstance = new DatabaseSecureConnectionPolicy();
result.SecureConnectionPolicy = secureConnectionPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DatabaseSecureConnectionPolicyProperties propertiesInstance = new DatabaseSecureConnectionPolicyProperties();
secureConnectionPolicyInstance.Properties = propertiesInstance;
JToken proxyDnsNameValue = propertiesValue["proxyDnsName"];
if (proxyDnsNameValue != null && proxyDnsNameValue.Type != JTokenType.Null)
{
string proxyDnsNameInstance = ((string)proxyDnsNameValue);
propertiesInstance.ProxyDnsName = proxyDnsNameInstance;
}
JToken proxyPortValue = propertiesValue["proxyPort"];
if (proxyPortValue != null && proxyPortValue.Type != JTokenType.Null)
{
string proxyPortInstance = ((string)proxyPortValue);
propertiesInstance.ProxyPort = proxyPortInstance;
}
JToken securityEnabledAccessValue = propertiesValue["securityEnabledAccess"];
if (securityEnabledAccessValue != null && securityEnabledAccessValue.Type != JTokenType.Null)
{
string securityEnabledAccessInstance = ((string)securityEnabledAccessValue);
propertiesInstance.SecurityEnabledAccess = securityEnabledAccessInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
secureConnectionPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
secureConnectionPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
secureConnectionPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
secureConnectionPolicyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
secureConnectionPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Cross-platform wrapper for Unity Input.
/// See OVRGamepadController for a list of the base axis and button names.
/// Depending on joystick number and platform
/// the base names will be pre-pended with "Platform:Joy #:" to look them up in the
/// Unity Input table. For instance: using an axis name of "Left_X_Axis" with GetJoystickAxis()
/// will result in looking up the axis named "Win: Joy 1: Left_X_Axis" when running on
/// Windows and "Android: Joy 1: Left_X_Axis" when running on Android.
///
/// In addition to wrapping joystick input, this class allows the assignment of up, held
/// and down events for any key, mouse button, or joystick button via the AddInputHandler()
/// method.
///
/// Currently this class relies on enumerations defined in OVRGamepadController
/// so that it remains compatible with existing Unity OVR projects. When this class
/// is included it overloads the default GPC_GetAxis() and GPC_GetButton() calls to
/// to ReadAxis() and ReadButton() in this class.
/// Ideally this class would completely replace the OVRGamepadController class. This
/// would involve changing the GPC_GetAxis() and GPC_GetButton() calls in a project
/// and removing references to OVRGamepadController in this file (and moving some of
/// the tables to InputControl).
/// </summary>
public static class OVRInputControl
{
[SerializeField]
// FIXME: this was originally settable on the behavior before this was a static class... maybe remove it.
/// <summary>
/// Set 'true' to allow keyboard input (will be set 'false' on some platforms).
/// </summary>
private static bool allowKeyControls = true;
/// <summary>
/// If true, prints information about each input event to the log.
/// </summary>
public static bool verbose = false;
public delegate void OnKeyUp(MonoBehaviour comp);
public delegate void OnKeyDown(MonoBehaviour comp);
public delegate void OnKeyHeld(MonoBehaviour comp);
/// <summary>
/// Types of devices we can handle input for.
/// </summary>
public enum DeviceType
{
None = -1,
Keyboard = 0, // a key
Mouse, // a mouse button
Gamepad, // a gamepad button
Axis, // a joystick axis (or trigger)
};
/// <summary>
/// Mouse button definitions.
/// </summary>
public enum MouseButton
{
None = -1,
Left = 0,
Right = 1,
Middle = 2,
Fourth = 4,
Fifth = 5,
};
/// <summary>
/// Holds information about a single key event.
/// </summary>
class KeyInfo
{
public DeviceType deviceType = DeviceType.None;
public string keyName = "";
public MouseButton mouseButton = MouseButton.None;
public OVRGamepadController.Button joystickButton = OVRGamepadController.Button.None;
public OVRGamepadController.Axis joystickAxis = OVRGamepadController.Axis.None;
public float threshold = 1000.0f; // threshold for triggers
public bool wasDown = false;
public OnKeyDown downHandler;
public OnKeyHeld heldHandler;
public OnKeyUp upHandler;
/// <summary>
/// Key constructor.
/// </summary>
public KeyInfo(
DeviceType inDeviceType,
string inKeyName,
OnKeyDown inDownHandler,
OnKeyHeld inHeldHandler,
OnKeyUp inUpHandler)
{
deviceType = inDeviceType;
keyName = inKeyName;
mouseButton = MouseButton.None;
joystickButton = OVRGamepadController.Button.None;
joystickAxis = OVRGamepadController.Axis.None;
threshold = 1000.0f;
wasDown = false;
downHandler = inDownHandler;
heldHandler = inHeldHandler;
upHandler = inUpHandler;
}
/// <summary>
/// Mouse button constructor.
/// </summary>
public KeyInfo(
DeviceType inDeviceType,
MouseButton inMouseButton,
OnKeyDown inDownHandler,
OnKeyHeld inHeldHandler,
OnKeyUp inUpHandler)
{
deviceType = inDeviceType;
keyName = "Mouse Button " + (int)inMouseButton;
mouseButton = inMouseButton;
joystickButton = OVRGamepadController.Button.None;
joystickAxis = OVRGamepadController.Axis.None;
threshold = 1000.0f;
wasDown = false;
downHandler = inDownHandler;
heldHandler = inHeldHandler;
upHandler = inUpHandler;
}
/// <summary>
/// Joystick button constructor.
/// </summary>
public KeyInfo(
DeviceType inDeviceType,
OVRGamepadController.Button inJoystickButton,
OnKeyDown inDownHandler,
OnKeyHeld inHeldHandler,
OnKeyUp inUpHandler)
{
deviceType = inDeviceType;
keyName = OVRGamepadController.ButtonNames[(int)inJoystickButton];
mouseButton = MouseButton.None;
joystickButton = inJoystickButton;
joystickAxis = OVRGamepadController.Axis.None;
threshold = 1000.0f;
wasDown = false;
downHandler = inDownHandler;
heldHandler = inHeldHandler;
upHandler = inUpHandler;
}
/// <summary>
/// Joystick axis constructor.
/// </summary>
public KeyInfo(
DeviceType inDeviceType,
OVRGamepadController.Axis inJoystickAxis,
OnKeyDown inDownHandler,
OnKeyHeld inHeldHandler,
OnKeyUp inUpHandler)
{
deviceType = inDeviceType;
keyName = OVRGamepadController.AxisNames[(int)inJoystickAxis];
mouseButton = MouseButton.None;
joystickButton = OVRGamepadController.Button.None;
joystickAxis = inJoystickAxis;
threshold = 0.5f;
wasDown = false;
downHandler = inDownHandler;
heldHandler = inHeldHandler;
upHandler = inUpHandler;
}
};
private static List<KeyInfo> keyInfos = new List<KeyInfo>();
private static string platformPrefix = "";
/// <summary>
/// Maps joystick input to a component.
/// </summary>
public class InputMapping
{
public InputMapping(MonoBehaviour comp, int inJoystickNumber)
{
component = comp;
joystickNumber = inJoystickNumber;
}
public MonoBehaviour component; // the component input goes to
public int joystickNumber; // the joystick that controls the object
};
/// <summary>
/// List of mappings from joystick to component.
/// </summary>
private static List<InputMapping> inputMap = new List<InputMapping>();
/// <summary>
/// Initializes the input system for OSX.
/// </summary>
private static void Init_Windows()
{
if (verbose)
Debug.Log("Initializing input for Windows.");
allowKeyControls = false;
platformPrefix = "Win:";
}
/// <summary>
/// Initializes the input system for Windows when running from the Unity editor.
/// </summary>
private static void Init_Windows_Editor()
{
if (verbose)
Debug.Log("Initializing input for Windows Editor.");
allowKeyControls = true;
platformPrefix = "Win:";
}
/// <summary>
/// Initializes the input system for Android.
/// </summary>
private static void Init_Android()
{
if (verbose)
Debug.Log("Initializing input for Android.");
allowKeyControls = true;
platformPrefix = "Android:";
}
/// <summary>
/// Initializes the input system for OSX.
/// </summary>
private static void Init_OSX()
{
if (verbose)
Debug.Log("Initializing input for OSX.");
allowKeyControls = false;
platformPrefix = "OSX:";
}
/// <summary>
/// Initializes the input system for OSX when running from the Unity editor.
/// </summary>
private static void Init_OSX_Editor()
{
if (verbose)
Debug.Log("Initializing input for OSX Editor.");
allowKeyControls = true;
platformPrefix = "OSX:";
}
/// <summary>
/// Initializes the input system for iPhone.
/// </summary>
private static void Init_iPhone()
{
if (verbose)
Debug.Log("Initializing input for iPhone.");
allowKeyControls = false;
platformPrefix = "iPhone:";
}
/// <summary>
/// Static contructor for the OVRInputControl class.
/// </summary>
static OVRInputControl()
{
#if UNITY_ANDROID && !UNITY_EDITOR
OVRGamepadController.SetReadAxisDelegate(ReadJoystickAxis);
OVRGamepadController.SetReadButtonDelegate(ReadJoystickButton);
#endif
switch (Application.platform)
{
case RuntimePlatform.WindowsPlayer:
Init_Windows();
break;
case RuntimePlatform.WindowsEditor:
Init_Windows_Editor();
break;
case RuntimePlatform.Android:
Init_Android();
break;
case RuntimePlatform.OSXPlayer:
Init_OSX();
break;
case RuntimePlatform.OSXEditor:
Init_OSX_Editor();
break;
case RuntimePlatform.IPhonePlayer:
Init_iPhone();
break;
}
string[] joystickNames = Input.GetJoystickNames();
for (int i = 0; i < joystickNames.Length; ++i)
{
if (verbose)
Debug.Log("Found joystick '" + joystickNames[i] + "'...");
}
}
/// <summary>
/// Adds a handler for key input
/// </summary>
public static void AddInputHandler(
DeviceType dt,
string keyName,
OnKeyDown onDown,
OnKeyHeld onHeld,
OnKeyUp onUp)
{
keyInfos.Add(new KeyInfo(dt, keyName, onDown, onHeld, onUp));
}
/// <summary>
/// Adds a handler for mouse button input.
/// </summary>
public static void AddInputHandler(
DeviceType dt,
MouseButton mouseButton,
OnKeyDown onDown,
OnKeyHeld onHeld,
OnKeyUp onUp)
{
keyInfos.Add(new KeyInfo(dt, mouseButton, onDown, onHeld, onUp));
}
/// <summary>
/// Adds a handler for joystick button input.
/// </summary>
public static void AddInputHandler(
DeviceType dt,
OVRGamepadController.Button joystickButton,
OnKeyDown onDown,
OnKeyHeld onHeld,
OnKeyUp onUp)
{
keyInfos.Add(new KeyInfo(dt, joystickButton, onDown, onHeld, onUp));
}
/// <summary>
/// Adds a handler for joystick axis input.
/// </summary>
public static void AddInputHandler(
DeviceType dt,
OVRGamepadController.Axis axis,
OnKeyDown onDown,
OnKeyHeld onHeld,
OnKeyUp onUp)
{
keyInfos.Add(new KeyInfo(dt, axis, onDown, onHeld, onUp));
}
/// <summary>
/// Returns the current value of the joystick axis specified by the name parameter.
/// The name should partially match the name of an axis specified in the Unity
/// Edit -> Project Settings -> Input pane, minus the Platform: Joy #: qualifiers.
/// For instance, specify "Left_X_Axis" to select the appropriate axis for the
/// current platform. This will be permuted into something like "Win:Joy 1:Left_X_Axis"
/// before it is queried.
/// </summary>
public static float GetJoystickAxis(int joystickNumber, string name)
{
// TODO: except for the joystick prefix this could be a table lookup
// with a table-per-joystick this could be a lookup.
#if UNITY_ANDROID && !UNITY_EDITOR
// on the Samsung gamepad, the left and right triggers are actually buttons
// so we map left and right triggers to the left and right shoulder buttons.
if (name == "LeftTrigger")
{
return GetJoystickButton(joystickNumber, OVRGamepadController.Button.LeftShoulder) ? 1.0f : 0.0f;
}
else if (name == "RightTrigger")
{
return GetJoystickButton(joystickNumber, OVRGamepadController.Button.RightShoulder) ? 1.0f : 0.0f;
}
#endif
string platformName = platformPrefix + "Joy " + joystickNumber + ":" + name;
return Input.GetAxis(platformName);
}
/// <summary>
/// Delegate for OVRGamepadController.
/// Returns the current value of the specified joystick axis.
/// </summary>
public static float GetJoystickAxis(int joystickNumber, OVRGamepadController.Axis axis)
{
string platformName = platformPrefix + "Joy " + joystickNumber + ":" + OVRGamepadController.AxisNames[(int)axis];
return Input.GetAxis(platformName);
}
/// <summary>
/// Delegate for OVRGamepadController.
/// This only exists for legacy compatibility with OVRGamepadController.
/// </summary>
public static float ReadJoystickAxis(OVRGamepadController.Axis axis)
{
//if (verbose)
//Debug.Log("OVRInputControl.ReadJoystickAxis");
return GetJoystickAxis(1, axis);
}
/// <summary>
/// Returns true if a joystick button is depressed.
/// The name should partially match the name of an axis specified in the Unity
/// Edit -> Project Settings -> Input pane, minus the Platform: Joy #: qualifiers.
/// For instance, specify "Button A" to select the appropriate axis for the
/// current platform. This will be permuted into something like "Win:Joy 1:Button A"
/// before it is queried.
/// </summary>
public static bool GetJoystickButton(int joystickNumber, string name)
{
// TODO: except for the joystick prefix this could be a table lookup
// with a table-per-joystick this could be a lookup.
string fullName = platformPrefix + "Joy " + joystickNumber + ":" + name;
return Input.GetButton(fullName);
}
/// <summary>
/// Delegate for OVRGamepadController.
/// Returns true if the specified joystick button is pressed.
/// </summary>
public static bool GetJoystickButton(int joystickNumber, OVRGamepadController.Button button)
{
string fullName = platformPrefix + "Joy " + joystickNumber + ":" + OVRGamepadController.ButtonNames[(int)button];
//if (verbose)
//Debug.Log("Checking button " + fullName);
return Input.GetButton(fullName);
}
/// <summary>
/// Delegate for OVRGamepadController.
/// This only exists for legacy compatibility with OVRGamepadController.
/// </summary>
public static bool ReadJoystickButton(OVRGamepadController.Button button)
{
//if (verbose)
//Debug.Log("OVRInputControl.ReadJoystickButton");
return GetJoystickButton(1, button);
}
//======================
// GetMouseButton
// Returns true if the specified mouse button is pressed.
//======================
public static bool GetMouseButton(MouseButton button)
{
return Input.GetMouseButton((int)button);
}
/// <summary>
/// Outputs debug spam for any non-zero axis.
/// This is only used for finding which axes are which with new controllers.
/// </summary>
private static void ShowAxisValues()
{
for (int i = 1; i <= 20; ++i)
{
string axisName = "Test Axis " + i;
float v = Input.GetAxis(axisName);
if (Mathf.Abs(v) > 0.2f)
{
if (verbose)
Debug.Log("Test Axis " + i + ": v = " + v);
}
}
}
/// <summary>
/// Outputs debug spam for any depressed button.
/// This is only used for finding which buttons are which with new controllers.
/// </summary>
private static void ShowButtonValues()
{
for (int i = 0; i < 6; ++i)
{
string buttonName = "Test Button " + i;
if (Input.GetButton(buttonName))
{
if (verbose)
Debug.Log("Test Button " + i + " is down.");
}
}
}
/// <summary>
/// Adds a mapping from a joystick to a behavior.
/// </summary>
public static void AddInputMapping(int joystickNumber, MonoBehaviour comp)
{
for (int i = 0; i < inputMap.Count; ++i)
{
InputMapping im = inputMap[i];
if (im.component == comp && im.joystickNumber == joystickNumber)
{
OVRDebugUtils.Assert(false, "Input mapping already exists!");
return;
}
}
inputMap.Add(new InputMapping(comp, joystickNumber));
}
/// <summary>
/// Removes a mapping from a joystick to a behavior.
/// </summary>
public static void RemoveInputMapping(int joystickNumber, MonoBehaviour comp)
{
for (int i = 0; i < inputMap.Count; ++i)
{
InputMapping im = inputMap[i];
if (im.component == comp && im.joystickNumber == joystickNumber)
{
inputMap.RemoveAt(i);
return;
}
}
}
/// <summary>
/// Removes all control mappings.
/// </summary>
public static void ClearControlMappings()
{
inputMap.Clear();
}
/// <summary>
/// Updates the state of all input mappings. This must be called from
/// a single MonoBehaviour's Update() method for input to be read.
/// </summary>
public static void Update()
{
// Enable these two lines if you have a new controller that you need to
// set up for which you do not know the axes.
//ShowAxisValues();
//ShowButtonValues();
for (int i = 0; i < inputMap.Count; ++i)
{
UpdateInputMapping(inputMap[i].joystickNumber, inputMap[i].component);
}
}
/// <summary>
/// Updates a single input mapping.
/// </summary>
private static void UpdateInputMapping(int joystickNumber, MonoBehaviour comp)
{
for (int i = 0; i < keyInfos.Count; ++i)
{
bool keyDown = false;
// query the correct device
KeyInfo keyInfo = keyInfos[i];
if (keyInfo.deviceType == DeviceType.Gamepad)
{
//if (verbose)
//Debug.Log("Checking gamepad button " + keyInfo.KeyName);
keyDown = GetJoystickButton(joystickNumber, keyInfo.joystickButton);
}
else if (keyInfo.deviceType == DeviceType.Axis)
{
float axisValue = GetJoystickAxis(joystickNumber, keyInfo.joystickAxis);
keyDown = (axisValue >= keyInfo.threshold);
}
else if (allowKeyControls)
{
if (keyInfo.deviceType == DeviceType.Mouse)
{
keyDown = GetMouseButton(keyInfo.mouseButton);
}
else if (keyInfo.deviceType == DeviceType.Keyboard)
{
keyDown = Input.GetKey(keyInfo.keyName);
}
}
// handle the event
if (!keyDown)
{
if (keyInfo.wasDown)
{
// key was just released
keyInfo.upHandler(comp);
}
}
else
{
if (!keyInfo.wasDown)
{
// key was just pressed
//if (verbose)
//Debug.Log( "Key or Button down: " + keyInfo.KeyName );
keyInfo.downHandler(comp);
}
else
{
// key is held
keyInfo.heldHandler(comp);
}
}
// update the key info
keyInfo.wasDown = keyDown;
}
}
};
| |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Microsoft.AspNetCore.Http;
using NakedFramework.Facade.Contexts;
using NakedFramework.Facade.Interface;
using NakedFramework.Facade.Translation;
using NakedFramework.Rest.Snapshot.Constants;
using NakedFramework.Rest.Snapshot.RelTypes;
using NakedFramework.Rest.Snapshot.Utility;
namespace NakedFramework.Rest.Snapshot.Representation;
[DataContract]
public class ParameterRepresentation : Representation {
protected ParameterRepresentation(IOidStrategy oidStrategy, HttpRequest req, IObjectFacade objectFacade, FieldFacadeAdapter parameter, RestControlFlags flags)
: base(oidStrategy, flags) {
SetName(parameter);
SetExtensions(req, objectFacade, parameter, flags);
SetLinks(req, objectFacade, parameter);
SetHeader(objectFacade);
}
internal string Name { get; private set; }
[DataMember(Name = JsonPropertyNames.Links)]
public LinkRepresentation[] Links { get; set; }
[DataMember(Name = JsonPropertyNames.Extensions)]
public MapRepresentation Extensions { get; set; }
private void SetHeader(IObjectFacade objectFacade) => SetEtag(objectFacade);
private void SetName(FieldFacadeAdapter parameter) => Name = parameter.Id;
private LinkRepresentation CreatePromptLink(HttpRequest req, IObjectFacade objectFacade, FieldFacadeAdapter parameter) {
var opts = new List<OptionalProperty>();
if (parameter.IsAutoCompleteEnabled) {
var arguments = new OptionalProperty(JsonPropertyNames.Arguments, MapRepresentation.Create(new OptionalProperty(JsonPropertyNames.XRoSearchTerm, MapRepresentation.Create(new OptionalProperty(JsonPropertyNames.Value, null, typeof(object))))));
var extensions = new OptionalProperty(JsonPropertyNames.Extensions, MapRepresentation.Create(new OptionalProperty(JsonPropertyNames.MinLength, parameter.AutoCompleteMinLength)));
opts.Add(arguments);
opts.Add(extensions);
}
else {
var parms = parameter.GetChoicesParameters();
var args = parms.Select(tuple => RestUtils.CreateArgumentProperty(OidStrategy, req, tuple, Flags)).ToArray();
var arguments = new OptionalProperty(JsonPropertyNames.Arguments, MapRepresentation.Create(args));
opts.Add(arguments);
}
return LinkRepresentation.Create(OidStrategy, new PromptRelType(parameter.GetHelper(OidStrategy, req, objectFacade)), Flags, opts.ToArray());
}
private void SetLinks(HttpRequest req, IObjectFacade objectFacade, FieldFacadeAdapter parameter) {
var tempLinks = new List<LinkRepresentation>();
if (parameter.IsAutoCompleteEnabled || parameter.GetChoicesParameters().Any()) {
tempLinks.Add(CreatePromptLink(req, objectFacade, parameter));
}
Links = tempLinks.ToArray();
}
private void SetExtensions(HttpRequest req, IObjectFacade objectFacade, FieldFacadeAdapter parameter, RestControlFlags flags) {
IDictionary<string, object> custom = null;
if (IsUnconditionalChoices(parameter, objectFacade)) {
custom = new Dictionary<string, object>();
(object value, string title)[] choicesArray = parameter.GetChoicesAndTitles(objectFacade, null).Select(choice => (parameter.GetChoiceValue(OidStrategy, req, choice.obj, flags), choice.title)).ToArray();
var op = choicesArray.Select(choice => new OptionalProperty(choice.title, choice.value)).ToArray();
var map = MapRepresentation.Create(op);
custom[JsonPropertyNames.CustomChoices] = map;
}
var mask = parameter.Mask;
if (!string.IsNullOrWhiteSpace(mask)) {
custom ??= new Dictionary<string, object>();
custom[JsonPropertyNames.CustomMask] = mask;
}
var multipleLines = parameter.NumberOfLines;
if (multipleLines > 1) {
custom ??= new Dictionary<string, object>();
custom[JsonPropertyNames.CustomMultipleLines] = multipleLines;
}
if (parameter.IsFindMenuEnabled != null && parameter.IsFindMenuEnabled.Value) {
custom ??= new Dictionary<string, object>();
custom[JsonPropertyNames.CustomFindMenu] = true;
}
custom = RestUtils.AddRangeExtension(parameter.AsField, custom);
Extensions = RestUtils.GetExtensions(parameter.Name(objectFacade),
parameter.Description(objectFacade),
null,
null,
null,
null,
!parameter.IsMandatory,
parameter.MaxLength,
parameter.Pattern,
null,
parameter.DataType,
parameter.PresentationHint,
parameter.RestExtension,
custom,
parameter.Specification,
parameter.ElementType,
OidStrategy,
true);
}
private static bool IsUnconditionalChoices(FieldFacadeAdapter parameter, IObjectFacade objectFacade) =>
parameter.IsChoicesEnabled(objectFacade) != Choices.NotEnabled &&
(parameter.Specification.IsParseable || parameter.Specification.IsCollection && parameter.ElementType.IsParseable) &&
!parameter.GetChoicesParameters().Any();
private static LinkRepresentation CreateDefaultLink(IOidStrategy oidStrategy, HttpRequest req, FieldFacadeAdapter parameter, IActionFacade action, IObjectFacade defaultNakedObject, string title, RestControlFlags flags) {
var helper = new UriMtHelper(oidStrategy, req, defaultNakedObject);
var relType = new DefaultRelType(action.Id, parameter.Id, helper);
return LinkRepresentation.Create(oidStrategy, relType, flags, new OptionalProperty(JsonPropertyNames.Title, title));
}
private static object CreateDefaultLinks(IOidStrategy oidStrategy, HttpRequest req, FieldFacadeAdapter parameter, IActionFacade action, IObjectFacade defaultNakedObject, string title, RestControlFlags flags) {
if (defaultNakedObject.Specification.IsCollection) {
return defaultNakedObject.ToEnumerable().Select(i => CreateDefaultLink(oidStrategy, req, parameter, action, i, i.TitleString, flags)).ToArray();
}
return CreateDefaultLink(oidStrategy, req, parameter, action, defaultNakedObject, title, flags);
}
public static ParameterRepresentation Create(IOidStrategy oidStrategy, HttpRequest req, IObjectFacade objectFacade, ParameterContextFacade parameterContext, RestControlFlags flags) {
var optionals = new List<OptionalProperty>();
var parameter = parameterContext.Parameter;
if (parameter.IsChoicesEnabled(objectFacade) != Choices.NotEnabled && !parameter.GetChoicesParameters().Any()) {
var choices = parameter.GetChoices(objectFacade, null);
var choicesArray = choices.Select(c => RestUtils.GetChoiceValue(oidStrategy, req, c, parameter, flags)).ToArray();
optionals.Add(new OptionalProperty(JsonPropertyNames.Choices, choicesArray));
}
var adapter = new FieldFacadeAdapter(parameter) { MenuId = parameterContext.MenuId };
// include default value for for non-nullable boolean so we can distinguish from nullable on client
if (parameter.DefaultTypeIsExplicit(objectFacade) || parameter.Specification.IsBoolean && !parameter.IsNullable) {
var defaultNakedObject = parameter.GetDefault(objectFacade);
if (defaultNakedObject != null) {
var title = defaultNakedObject.TitleString;
var value = RestUtils.ObjectToPredefinedType(defaultNakedObject, true);
var isValue = defaultNakedObject.Specification.IsParseable || defaultNakedObject.Specification.IsCollection && defaultNakedObject.ElementSpecification.IsParseable;
var defaultValue = isValue ? value : CreateDefaultLinks(oidStrategy, req, adapter, parameter.Action, defaultNakedObject, title, flags);
optionals.Add(new OptionalProperty(JsonPropertyNames.Default, defaultValue));
}
}
var consent = parameter.IsUsable();
if (consent.IsVetoed) {
optionals.Add(new OptionalProperty(JsonPropertyNames.DisabledReason, consent.Reason));
}
return optionals.Any()
? CreateWithOptionals<ParameterRepresentation>(new object[] { oidStrategy, req, objectFacade, adapter, flags }, optionals)
: new ParameterRepresentation(oidStrategy, req, objectFacade, adapter, flags);
}
public static ParameterRepresentation Create(IOidStrategy oidStrategy, HttpRequest req, IObjectFacade objectFacade, IAssociationFacade assoc, ActionContextFacade actionContext, RestControlFlags flags) {
var optionals = new List<OptionalProperty>();
if (assoc.IsChoicesEnabled(objectFacade) != Choices.NotEnabled && !assoc.GetChoicesParameters().Any()) {
var choices = assoc.GetChoices(objectFacade, null);
var choicesArray = choices.Select(c => RestUtils.GetChoiceValue(oidStrategy, req, c, assoc, flags)).ToArray();
optionals.Add(new OptionalProperty(JsonPropertyNames.Choices, choicesArray));
}
var adapter = new FieldFacadeAdapter(assoc);
var defaultNakedObject = assoc.GetValue(objectFacade);
if (defaultNakedObject != null) {
var title = defaultNakedObject.TitleString;
var value = RestUtils.ObjectToPredefinedType(defaultNakedObject, true);
var isValue = defaultNakedObject.Specification.IsParseable || defaultNakedObject.Specification.IsCollection && defaultNakedObject.ElementSpecification.IsParseable;
var defaultValue = isValue ? value : CreateDefaultLinks(oidStrategy, req, adapter, actionContext.Action, defaultNakedObject, title, flags);
optionals.Add(new OptionalProperty(JsonPropertyNames.Default, defaultValue));
}
return optionals.Any()
? CreateWithOptionals<ParameterRepresentation>(new object[] { oidStrategy, req, objectFacade, adapter, flags }, optionals)
: new ParameterRepresentation(oidStrategy, req, objectFacade, adapter, flags);
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] Value of GL_RESTART_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int RESTART_SUN = 0x0001;
/// <summary>
/// [GL] Value of GL_REPLACE_MIDDLE_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int REPLACE_MIDDLE_SUN = 0x0002;
/// <summary>
/// [GL] Value of GL_REPLACE_OLDEST_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int REPLACE_OLDEST_SUN = 0x0003;
/// <summary>
/// [GL] Value of GL_TRIANGLE_LIST_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int TRIANGLE_LIST_SUN = 0x81D7;
/// <summary>
/// [GL] Value of GL_REPLACEMENT_CODE_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int REPLACEMENT_CODE_SUN = 0x81D8;
/// <summary>
/// [GL] Value of GL_REPLACEMENT_CODE_ARRAY_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int REPLACEMENT_CODE_ARRAY_SUN = 0x85C0;
/// <summary>
/// [GL] Value of GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int REPLACEMENT_CODE_ARRAY_TYPE_SUN = 0x85C1;
/// <summary>
/// [GL] Value of GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int REPLACEMENT_CODE_ARRAY_STRIDE_SUN = 0x85C2;
/// <summary>
/// [GL] Value of GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int REPLACEMENT_CODE_ARRAY_POINTER_SUN = 0x85C3;
/// <summary>
/// [GL] Value of GL_R1UI_V3F_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int R1UI_V3F_SUN = 0x85C4;
/// <summary>
/// [GL] Value of GL_R1UI_C4UB_V3F_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int R1UI_C4UB_V3F_SUN = 0x85C5;
/// <summary>
/// [GL] Value of GL_R1UI_C3F_V3F_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int R1UI_C3F_V3F_SUN = 0x85C6;
/// <summary>
/// [GL] Value of GL_R1UI_N3F_V3F_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int R1UI_N3F_V3F_SUN = 0x85C7;
/// <summary>
/// [GL] Value of GL_R1UI_C4F_N3F_V3F_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int R1UI_C4F_N3F_V3F_SUN = 0x85C8;
/// <summary>
/// [GL] Value of GL_R1UI_T2F_V3F_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int R1UI_T2F_V3F_SUN = 0x85C9;
/// <summary>
/// [GL] Value of GL_R1UI_T2F_N3F_V3F_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int R1UI_T2F_N3F_V3F_SUN = 0x85CA;
/// <summary>
/// [GL] Value of GL_R1UI_T2F_C4F_N3F_V3F_SUN symbol.
/// </summary>
[RequiredByFeature("GL_SUN_triangle_list")]
public const int R1UI_T2F_C4F_N3F_V3F_SUN = 0x85CB;
/// <summary>
/// [GL] glReplacementCodeuiSUN: Binding for glReplacementCodeuiSUN.
/// </summary>
/// <param name="code">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_SUN_triangle_list")]
public static void ReplacementCodeuiSUN(uint code)
{
Debug.Assert(Delegates.pglReplacementCodeuiSUN != null, "pglReplacementCodeuiSUN not implemented");
Delegates.pglReplacementCodeuiSUN(code);
LogCommand("glReplacementCodeuiSUN", null, code );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glReplacementCodeusSUN: Binding for glReplacementCodeusSUN.
/// </summary>
/// <param name="code">
/// A <see cref="T:ushort"/>.
/// </param>
[RequiredByFeature("GL_SUN_triangle_list")]
public static void ReplacementCodeusSUN(ushort code)
{
Debug.Assert(Delegates.pglReplacementCodeusSUN != null, "pglReplacementCodeusSUN not implemented");
Delegates.pglReplacementCodeusSUN(code);
LogCommand("glReplacementCodeusSUN", null, code );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glReplacementCodeubSUN: Binding for glReplacementCodeubSUN.
/// </summary>
/// <param name="code">
/// A <see cref="T:byte"/>.
/// </param>
[RequiredByFeature("GL_SUN_triangle_list")]
public static void ReplacementCodeubSUN(byte code)
{
Debug.Assert(Delegates.pglReplacementCodeubSUN != null, "pglReplacementCodeubSUN not implemented");
Delegates.pglReplacementCodeubSUN(code);
LogCommand("glReplacementCodeubSUN", null, code );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glReplacementCodeuivSUN: Binding for glReplacementCodeuivSUN.
/// </summary>
/// <param name="code">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_SUN_triangle_list")]
public static void ReplacementCodeuiSUN(uint[] code)
{
unsafe {
fixed (uint* p_code = code)
{
Debug.Assert(Delegates.pglReplacementCodeuivSUN != null, "pglReplacementCodeuivSUN not implemented");
Delegates.pglReplacementCodeuivSUN(p_code);
LogCommand("glReplacementCodeuivSUN", null, code );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glReplacementCodeusvSUN: Binding for glReplacementCodeusvSUN.
/// </summary>
/// <param name="code">
/// A <see cref="T:ushort[]"/>.
/// </param>
[RequiredByFeature("GL_SUN_triangle_list")]
public static void ReplacementCodeusSUN(ushort[] code)
{
unsafe {
fixed (ushort* p_code = code)
{
Debug.Assert(Delegates.pglReplacementCodeusvSUN != null, "pglReplacementCodeusvSUN not implemented");
Delegates.pglReplacementCodeusvSUN(p_code);
LogCommand("glReplacementCodeusvSUN", null, code );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glReplacementCodeubvSUN: Binding for glReplacementCodeubvSUN.
/// </summary>
/// <param name="code">
/// A <see cref="T:byte[]"/>.
/// </param>
[RequiredByFeature("GL_SUN_triangle_list")]
public static void ReplacementCodeubSUN(byte[] code)
{
unsafe {
fixed (byte* p_code = code)
{
Debug.Assert(Delegates.pglReplacementCodeubvSUN != null, "pglReplacementCodeubvSUN not implemented");
Delegates.pglReplacementCodeubvSUN(p_code);
LogCommand("glReplacementCodeubvSUN", null, code );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glReplacementCodePointerSUN: Binding for glReplacementCodePointerSUN.
/// </summary>
/// <param name="type">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="stride">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="pointer">
/// A <see cref="T:IntPtr[]"/>.
/// </param>
[RequiredByFeature("GL_SUN_triangle_list")]
public static void ReplacementCodePointerSUN(int type, int stride, IntPtr[] pointer)
{
unsafe {
fixed (IntPtr* p_pointer = pointer)
{
Debug.Assert(Delegates.pglReplacementCodePointerSUN != null, "pglReplacementCodePointerSUN not implemented");
Delegates.pglReplacementCodePointerSUN(type, stride, p_pointer);
LogCommand("glReplacementCodePointerSUN", null, type, stride, pointer );
}
}
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_SUN_triangle_list")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glReplacementCodeuiSUN(uint code);
[RequiredByFeature("GL_SUN_triangle_list")]
[ThreadStatic]
internal static glReplacementCodeuiSUN pglReplacementCodeuiSUN;
[RequiredByFeature("GL_SUN_triangle_list")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glReplacementCodeusSUN(ushort code);
[RequiredByFeature("GL_SUN_triangle_list")]
[ThreadStatic]
internal static glReplacementCodeusSUN pglReplacementCodeusSUN;
[RequiredByFeature("GL_SUN_triangle_list")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glReplacementCodeubSUN(byte code);
[RequiredByFeature("GL_SUN_triangle_list")]
[ThreadStatic]
internal static glReplacementCodeubSUN pglReplacementCodeubSUN;
[RequiredByFeature("GL_SUN_triangle_list")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glReplacementCodeuivSUN(uint* code);
[RequiredByFeature("GL_SUN_triangle_list")]
[ThreadStatic]
internal static glReplacementCodeuivSUN pglReplacementCodeuivSUN;
[RequiredByFeature("GL_SUN_triangle_list")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glReplacementCodeusvSUN(ushort* code);
[RequiredByFeature("GL_SUN_triangle_list")]
[ThreadStatic]
internal static glReplacementCodeusvSUN pglReplacementCodeusvSUN;
[RequiredByFeature("GL_SUN_triangle_list")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glReplacementCodeubvSUN(byte* code);
[RequiredByFeature("GL_SUN_triangle_list")]
[ThreadStatic]
internal static glReplacementCodeubvSUN pglReplacementCodeubvSUN;
[RequiredByFeature("GL_SUN_triangle_list")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glReplacementCodePointerSUN(int type, int stride, IntPtr* pointer);
[RequiredByFeature("GL_SUN_triangle_list")]
[ThreadStatic]
internal static glReplacementCodePointerSUN pglReplacementCodePointerSUN;
}
}
}
| |
using System;
using swm = System.Windows.Media;
using sw = System.Windows;
using swmi = System.Windows.Media.Imaging;
using Eto.Drawing;
using System.Globalization;
using System.Diagnostics;
namespace Eto.Wpf.Drawing
{
/// <summary>
/// Handler for <see cref="Graphics"/>
/// </summary>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public class GraphicsHandler : WidgetHandler<swm.DrawingContext, Graphics>, Graphics.IHandler
{
swm.Visual visual;
swm.DrawingGroup group;
swm.DrawingVisual drawingVisual;
RectangleF? clipBounds;
RectangleF initialClip;
swm.PathGeometry clipPath;
sw.Rect bounds;
readonly bool disposeControl;
bool isOffset;
Bitmap image;
swm.DrawingContext baseContext;
public GraphicsHandler()
{
}
static readonly object PixelOffsetMode_Key = new object();
public PixelOffsetMode PixelOffsetMode
{
get { return Widget != null ? Widget.Properties.Get<PixelOffsetMode>(PixelOffsetMode_Key) : default(PixelOffsetMode); }
set { Widget.Properties.Set(PixelOffsetMode_Key, value); }
}
void SetOffset(bool fill)
{
var requiresOffset = !fill && PixelOffsetMode == PixelOffsetMode.None;
if (requiresOffset != isOffset)
{
RewindAll();
isOffset = requiresOffset;
ApplyAll();
}
}
public float PointsPerPixel
{
get { return 72f / 96f; }
}
protected override bool DisposeControl { get { return disposeControl; } }
public GraphicsHandler(swm.Visual visual, swm.DrawingContext context, sw.Rect bounds, RectangleF initialClip, bool shouldDispose = true)
{
disposeControl = shouldDispose;
this.visual = visual;
drawingVisual = visual as swm.DrawingVisual;
Control = context;
this.bounds = bounds;
this.initialClip = initialClip;
Control.PushClip(new swm.RectangleGeometry(bounds));
}
public bool IsRetained { get { return true; } }
public void CreateFromImage(Bitmap image)
{
this.image = image;
initialClip = new RectangleF(0, 0, image.Width, image.Height);
bounds = initialClip.ToWpf();
drawingVisual = new swm.DrawingVisual();
visual = drawingVisual;
Control = drawingVisual.RenderOpen();
Control.DrawImage(image.ControlObject as swm.ImageSource, bounds);
}
protected override void Initialize()
{
base.Initialize();
ApplyAll();
}
static readonly object DPI_Key = new object();
public double DPI
{
get
{
return Widget.Properties.Create<double>(DPI_Key, () =>
{
var presentationSource = sw.PresentationSource.FromVisual(visual);
if (presentationSource != null && presentationSource.CompositionTarget != null)
{
swm.Matrix m = presentationSource.CompositionTarget.TransformToDevice;
return m.M11;
}
return 1.0;
});
}
}
public void DrawRectangle(Pen pen, float x, float y, float width, float height)
{
SetOffset(false);
Control.DrawRectangle(null, pen.ToWpf(true), new sw.Rect(x, y, width, height));
}
public void DrawLine(Pen pen, float startx, float starty, float endx, float endy)
{
SetOffset(false);
var wpfPen = pen.ToWpf(true);
Control.DrawLine(wpfPen, new sw.Point(startx, starty), new sw.Point(endx, endy));
}
public void FillRectangle(Brush brush, float x, float y, float width, float height)
{
SetOffset(true);
var wpfBrush = brush.ToWpf(true);
Control.DrawRectangle(wpfBrush, null, new sw.Rect(x, y, width, height));
}
public void DrawEllipse(Pen pen, float x, float y, float width, float height)
{
SetOffset(false);
Control.DrawEllipse(null, pen.ToWpf(true), new sw.Point(x + width / 2.0, y + height / 2.0), width / 2.0, height / 2.0);
}
public void FillEllipse(Brush brush, float x, float y, float width, float height)
{
SetOffset(true);
Control.DrawEllipse(brush.ToWpf(true), null, new sw.Point(x + width / 2.0, y + height / 2.0), width / 2.0, height / 2.0);
}
public static swm.Geometry CreateArcDrawing(sw.Rect rect, double startDegrees, double sweepDegrees, bool closed)
{
// degrees to radians conversion
double startRadians = startDegrees * Math.PI / 180.0;
double sweepRadians = sweepDegrees * Math.PI / 180.0;
// x and y radius
double dx = rect.Width / 2;
double dy = rect.Height / 2;
// determine the start point
double xs = rect.X + dx + (Math.Cos(startRadians) * dx);
double ys = rect.Y + dy + (Math.Sin(startRadians) * dy);
// determine the end point
double xe = rect.X + dx + (Math.Cos(startRadians + sweepRadians) * dx);
double ye = rect.Y + dy + (Math.Sin(startRadians + sweepRadians) * dy);
var centerPoint = new sw.Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
// draw the arc into a stream geometry
var streamGeom = new swm.StreamGeometry();
using (var ctx = streamGeom.Open())
{
bool isLargeArc = Math.Abs(sweepDegrees) > 180;
var sweepDirection = sweepDegrees < 0 ? swm.SweepDirection.Counterclockwise : swm.SweepDirection.Clockwise;
if (closed)
{
ctx.BeginFigure(centerPoint, true, true);
ctx.LineTo(new sw.Point(xs, ys), true, true);
}
else
ctx.BeginFigure(new sw.Point(xs, ys), true, false);
ctx.ArcTo(new sw.Point(xe, ye), new sw.Size(dx, dy), 0, isLargeArc, sweepDirection, true, false);
if (closed)
ctx.LineTo(centerPoint, true, true);
}
return streamGeom;
}
public void DrawArc(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle)
{
SetOffset(false);
if (sweepAngle >= 360f)
DrawEllipse(pen, x, y, width, height);
else
{
var arc = CreateArcDrawing(new sw.Rect(x, y, width, height), startAngle, sweepAngle, false);
Control.DrawGeometry(null, pen.ToWpf(true), arc);
}
}
public void FillPie(Brush brush, float x, float y, float width, float height, float startAngle, float sweepAngle)
{
SetOffset(true);
if (sweepAngle >= 360f)
FillEllipse(brush, x, y, width, height);
else
{
var arc = CreateArcDrawing(new sw.Rect(x, y, width, height), startAngle, sweepAngle, true);
Control.DrawGeometry(brush.ToWpf(true), null, arc);
}
}
public void FillPath(Brush brush, IGraphicsPath path)
{
SetOffset(true);
Control.DrawGeometry(brush.ToWpf(true), null, path.ToWpf());
}
public void DrawPath(Pen pen, IGraphicsPath path)
{
SetOffset(false);
Control.DrawGeometry(null, pen.ToWpf(true), path.ToWpf());
}
public void DrawImage(Image image, float x, float y)
{
SetOffset(true);
var size = image.Size;
DrawImage(image, x, y, size.Width, size.Height);
}
public void DrawImage(Image image, float x, float y, float width, float height)
{
SetOffset(true);
var src = image.ToWpf((int)Math.Max(width, height));
if ((ImageInterpolation == ImageInterpolation.High || ImageInterpolation == ImageInterpolation.Default)
&& (width != src.Width || height != src.Height))
{
// better image quality by using transformed bitmap, plus it is actually faster
src = new swmi.TransformedBitmap(
src,
new swm.ScaleTransform(width / src.Width * 96 / src.DpiX, height / src.Height * 96 / src.DpiY, 0, 0)
);
}
Control.DrawImage(src, new sw.Rect(x, y, width, height));
}
public void DrawImage(Image image, RectangleF source, RectangleF destination)
{
SetOffset(true);
var src = image.ToWpf();
Control.PushClip(new swm.RectangleGeometry(destination.ToWpf()));
bool scale = source.Size != destination.Size;
bool translate = source.X > 0 || source.Y > 0;
double scalex = 1.0;
double scaley = 1.0;
if (scale)
{
scalex = (double)destination.Width / (double)source.Width;
scaley = (double)destination.Height / (double)source.Height;
Control.PushTransform(new swm.ScaleTransform(scalex, scaley));
}
if (translate)
Control.PushTransform(new swm.TranslateTransform(-source.X, -source.Y));
var rect = new sw.Rect(destination.X / scalex, destination.Y / scaley, image.Size.Width, image.Size.Height);
Control.DrawImage(src, rect);
// pop for TranslateTransform
if (translate)
Control.Pop();
// pop again for ScaleTransform
if (scale)
Control.Pop();
// pop for PushClip
Control.Pop();
}
public void DrawText(Font font, SolidBrush b, float x, float y, string text)
{
SetOffset(true);
var fontHandler = font.Handler as FontHandler;
if (fontHandler != null)
{
var brush = b.ToWpf();
var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, fontHandler.WpfTypeface, fontHandler.PixelSize, brush);
if (fontHandler.WpfTextDecorations != null)
formattedText.SetTextDecorations(fontHandler.WpfTextDecorations, 0, text.Length);
Control.DrawText(formattedText, new sw.Point(x, y));
}
}
public SizeF MeasureString(Font font, string text)
{
var result = SizeF.Empty;
var fontHandler = font.Handler as FontHandler;
if (fontHandler != null)
{
var brush = new swm.SolidColorBrush(swm.Colors.White);
var formattedText = new swm.FormattedText(text, CultureInfo.CurrentUICulture, sw.FlowDirection.LeftToRight, fontHandler.WpfTypeface, fontHandler.PixelSize, brush);
result = new SizeF((float)formattedText.WidthIncludingTrailingWhitespace, (float)formattedText.Height);
}
return result;
}
public void Flush()
{
if (Close())
{
Control = drawingVisual.RenderOpen();
}
}
bool Close()
{
if (image != null)
{
Control.Close();
var handler = (BitmapHandler)image.Handler;
var bmp = handler.Control;
var newbmp = bmp as swmi.RenderTargetBitmap;
if (newbmp == null)
{
newbmp = new swmi.RenderTargetBitmap(bmp.PixelWidth, bmp.PixelHeight, bmp.DpiX, bmp.DpiY, swm.PixelFormats.Pbgra32);
handler.SetBitmap(newbmp);
}
newbmp.Render(visual);
return true;
}
return false;
}
public bool AntiAlias
{
get
{
switch (swm.RenderOptions.GetEdgeMode((sw.DependencyObject)group ?? visual))
{
case swm.EdgeMode.Aliased:
return false;
case swm.EdgeMode.Unspecified:
return true;
default:
throw new NotSupportedException();
}
}
set
{
if (value != AntiAlias)
{
CreateGroup();
swm.RenderOptions.SetEdgeMode(group, value ? swm.EdgeMode.Unspecified : swm.EdgeMode.Aliased);
}
}
}
static readonly object ImageInterpolation_Key = new object();
public ImageInterpolation ImageInterpolation
{
get { return Widget.Properties.Get<ImageInterpolation>(ImageInterpolation_Key); }
set
{
Widget.Properties.Set(ImageInterpolation_Key, value, () => {
swm.RenderOptions.SetBitmapScalingMode(visual, value.ToWpf());
});
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
CloseGroup();
Close();
}
base.Dispose(disposing);
}
void CreateGroup()
{
CloseGroup();
if (baseContext == null)
baseContext = Control;
group = new swm.DrawingGroup();
Control = group.Open();
ApplyAll();
}
void CloseGroup()
{
if (group != null && baseContext != null)
{
RewindAll();
Control.Close();
baseContext.DrawDrawing(group);
Control = baseContext;
group = null;
ApplyAll();
}
}
TransformStack transforms;
TransformStack Transforms
{
get
{
if (transforms == null)
transforms = new TransformStack(
m => Control.PushTransform(m.ToWpfTransform()),
() => Control.Pop()
);
return transforms;
}
}
public void TranslateTransform(float offsetX, float offsetY)
{
Transforms.TranslateTransform(offsetX, offsetY);
}
public void RotateTransform(float angle)
{
Transforms.RotateTransform(angle);
}
public void ScaleTransform(float scaleX, float scaleY)
{
Transforms.ScaleTransform(scaleX, scaleY);
}
public void MultiplyTransform(IMatrix matrix)
{
Transforms.MultiplyTransform(matrix);
}
public void SaveTransform()
{
Transforms.SaveTransform();
}
public void RestoreTransform()
{
Transforms.RestoreTransform();
}
public IMatrix CurrentTransform
{
get { return transforms.Current != null ? transforms.Current.Clone() : Matrix.Create(); }
}
void RewindOffset()
{
if (isOffset)
Control.Pop();
}
void ApplyOffset()
{
if (isOffset)
Control.PushTransform(new swm.TranslateTransform(0.5, 0.5));
}
protected void RewindClip()
{
if (clipBounds != null || clipPath != null)
Control.Pop();
}
protected void ApplyClip()
{
if (clipPath != null)
{
Control.PushClip(clipPath);
}
else if (clipBounds != null)
{
Control.PushClip(new swm.RectangleGeometry(clipBounds.Value.ToWpf()));
}
}
void RewindAll()
{
RewindTransform();
RewindClip();
RewindOffset();
}
void ApplyAll()
{
ApplyOffset();
ApplyClip();
ApplyTransform();
}
void RewindTransform()
{
if (transforms != null)
transforms.PopAll();
}
void ApplyTransform()
{
if (transforms != null)
transforms.PushAll();
}
public RectangleF ClipBounds
{
get
{
var translatedClip = clipBounds ?? initialClip;
if (transforms != null && transforms.Current != null)
{
var invertedTransform = transforms.Current.Clone();
invertedTransform.Invert();
translatedClip = invertedTransform.TransformRectangle(translatedClip);
}
return translatedClip;
}
}
public void SetClip(RectangleF rectangle)
{
RewindTransform();
RewindClip();
if (transforms != null && transforms.Current != null)
clipBounds = transforms.Current.TransformRectangle(rectangle);
else
clipBounds = rectangle;
clipPath = null;
ApplyClip();
ApplyTransform();
}
public void SetClip(IGraphicsPath path)
{
RewindTransform();
RewindClip();
path = path.Clone();
if (transforms != null && transforms.Current != null)
path.Transform(transforms.Current);
clipPath = path.ToWpf(); // require a clone so changes to path don't affect current clip
clipBounds = clipPath.Bounds.ToEtoF();
ApplyClip();
ApplyTransform();
}
public void ResetClip()
{
if (clipBounds != null)
{
Control.Pop();
clipBounds = null;
clipPath = null;
}
}
public void Clear(SolidBrush brush)
{
var rect = clipBounds ?? initialClip;
if (drawingVisual != null)
{
// bitmap
Control.Close();
var newbmp = new swmi.RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, 96, 96, swm.PixelFormats.Pbgra32);
newbmp.Render(visual);
swm.Geometry maskgeometry;
if (clipPath != null)
{
maskgeometry = clipPath;
}
else
{
maskgeometry = new swm.RectangleGeometry(rect.ToWpf());
}
var boundsgeometry = new swm.RectangleGeometry(bounds);
maskgeometry = swm.Geometry.Combine(boundsgeometry, maskgeometry, swm.GeometryCombineMode.Exclude, null);
var dr = new swm.GeometryDrawing(swm.Brushes.Black, null, maskgeometry);
var db = new swm.DrawingBrush(dr);
//db.Transform = new swm.TranslateTransform (0.5, 0.5);
Control = drawingVisual.RenderOpen();
Control.PushGuidelineSet(new swm.GuidelineSet(new [] { bounds.Left, bounds.Right }, new [] { bounds.Top, bounds.Bottom }));
Control.PushOpacityMask(db);
Control.DrawImage(newbmp, bounds);
Control.Pop();
ApplyAll();
}
else
{
// drawable
if (brush == null || brush.Color.A < 1.0f)
Widget.FillRectangle(Brushes.Black, rect);
}
if (brush != null)
{
Widget.FillRectangle(brush, rect);
}
}
}
}
| |
// 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.IO;
using System.Text;
using Xunit;
namespace System.IO.Tests
{
public class BinaryWriterTests
{
protected virtual Stream CreateStream()
{
return new MemoryStream();
}
[Fact]
public void BinaryWriter_CtorAndWriteTests1()
{
// [] Smoke test to ensure that we can write with the constructed writer
using (Stream mstr = CreateStream())
using (BinaryWriter dw2 = new BinaryWriter(mstr))
using (BinaryReader dr2 = new BinaryReader(mstr))
{
dw2.Write(true);
dw2.Flush();
mstr.Position = 0;
Assert.True(dr2.ReadBoolean());
}
}
[Fact]
public void BinaryWriter_CtorAndWriteTests1_Negative()
{
// [] Should throw ArgumentNullException for null argument
Assert.Throws<ArgumentNullException>(() => new BinaryWriter(null));
// [] Can't construct a BinaryWriter on a readonly stream
using (Stream memStream = new MemoryStream(new byte[10], false))
{
Assert.Throws<ArgumentException>(() => new BinaryWriter(memStream));
}
// [] Can't construct a BinaryWriter with a closed stream
{
Stream memStream = CreateStream();
memStream.Dispose();
Assert.Throws<ArgumentException>(() => new BinaryWriter(memStream));
}
}
[Theory]
[MemberData(nameof(EncodingAndEncodingStrings))]
public void BinaryWriter_EncodingCtorAndWriteTests(Encoding encoding, string testString)
{
using (Stream memStream = CreateStream())
using (BinaryWriter writer = new BinaryWriter(memStream, encoding))
using (BinaryReader reader = new BinaryReader(memStream, encoding))
{
writer.Write(testString);
writer.Flush();
memStream.Position = 0;
Assert.Equal(testString, reader.ReadString());
}
}
public static IEnumerable<object[]> EncodingAndEncodingStrings
{
get
{
yield return new object[] { Encoding.UTF8, "This is UTF8\u00FF" };
yield return new object[] { Encoding.BigEndianUnicode, "This is BigEndianUnicode\u00FF" };
yield return new object[] { Encoding.Unicode, "This is Unicode\u00FF" };
}
}
[Fact]
public void BinaryWriter_EncodingCtorAndWriteTests_Negative()
{
// [] Check for ArgumentNullException on null stream
Assert.Throws<ArgumentNullException>(() => new BinaryReader((Stream)null, Encoding.UTF8));
// [] Check for ArgumentNullException on null encoding
Assert.Throws<ArgumentNullException>(() => new BinaryReader(CreateStream(), null));
}
[Fact]
public void BinaryWriter_SeekTests()
{
int[] iArrLargeValues = new int[] { 10000, 100000, int.MaxValue / 200, int.MaxValue / 1000, short.MaxValue, int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 };
BinaryWriter dw2 = null;
MemoryStream mstr = null;
byte[] bArr = null;
StringBuilder sb = new StringBuilder();
Int64 lReturn = 0;
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("Hello, this is my string".ToCharArray());
for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++)
{
lReturn = dw2.Seek(iArrLargeValues[iLoop], SeekOrigin.Begin);
Assert.Equal(iArrLargeValues[iLoop], lReturn);
}
dw2.Dispose();
mstr.Dispose();
// [] Seek from start of stream
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(0, SeekOrigin.Begin);
Assert.Equal(0, lReturn);
dw2.Write("lki".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("lki3456789", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seek into stream from start
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(3, SeekOrigin.Begin);
Assert.Equal(3, lReturn);
dw2.Write("lk".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("012lk56789", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seek from end of stream
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(-3, SeekOrigin.End);
Assert.Equal(7, lReturn);
dw2.Write("ll".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("0123456ll9", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seeking from current position
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
mstr.Position = 2;
lReturn = dw2.Seek(2, SeekOrigin.Current);
Assert.Equal(4, lReturn);
dw2.Write("ll".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("0123ll6789", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seeking past the end from middle
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(4, SeekOrigin.End); //This wont throw any exception now.
Assert.Equal(14, mstr.Position);
dw2.Dispose();
mstr.Dispose();
// [] Seek past the end from beginning
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(11, SeekOrigin.Begin); //This wont throw any exception now.
Assert.Equal(11, mstr.Position);
dw2.Dispose();
mstr.Dispose();
// [] Seek to the end
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(10, SeekOrigin.Begin);
Assert.Equal(10, lReturn);
dw2.Write("ll".ToCharArray());
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("0123456789ll", sb.ToString());
dw2.Dispose();
mstr.Dispose();
}
[Theory]
[InlineData(-1)]
[InlineData(-2)]
[InlineData(-10000)]
[InlineData(int.MinValue)]
public void BinaryWriter_SeekTests_NegativeOffset(int invalidValue)
{
// [] IOException if offset is negative
using (Stream memStream = CreateStream())
using (BinaryWriter writer = new BinaryWriter(memStream))
{
writer.Write("Hello, this is my string".ToCharArray());
Assert.Throws<IOException>(() => writer.Seek(invalidValue, SeekOrigin.Begin));
}
}
[Fact]
public void BinaryWriter_SeekTests_InvalidSeekOrigin()
{
// [] ArgumentException for invalid seekOrigin
using (Stream memStream = CreateStream())
using (BinaryWriter writer = new BinaryWriter(memStream))
{
writer.Write("012345789".ToCharArray());
Assert.Throws<ArgumentException>(() =>
{
writer.Seek(3, ~SeekOrigin.Begin);
});
}
}
[Fact]
public void BinaryWriter_BaseStreamTests()
{
// [] Get the base stream for MemoryStream
using (Stream ms2 = CreateStream())
using (BinaryWriter sr2 = new BinaryWriter(ms2))
{
Assert.Same(ms2, sr2.BaseStream);
}
}
[Fact]
public virtual void BinaryWriter_FlushTests()
{
// [] Check that flush updates the underlying stream
using (Stream memstr2 = CreateStream())
using (BinaryWriter bw2 = new BinaryWriter(memstr2))
{
string str = "HelloWorld";
int expectedLength = str.Length + 1; // 1 for 7-bit encoded length
bw2.Write(str);
Assert.Equal(expectedLength, memstr2.Length);
bw2.Flush();
Assert.Equal(expectedLength, memstr2.Length);
}
// [] Flushing a closed writer may throw an exception depending on the underlying stream
using (Stream memstr2 = CreateStream())
{
BinaryWriter bw2 = new BinaryWriter(memstr2);
bw2.Dispose();
bw2.Flush();
}
}
[Fact]
public void BinaryWriter_DisposeTests()
{
// Disposing multiple times should not throw an exception
using (Stream memStream = CreateStream())
using (BinaryWriter binaryWriter = new BinaryWriter(memStream))
{
binaryWriter.Dispose();
binaryWriter.Dispose();
binaryWriter.Dispose();
}
}
[Fact]
public void BinaryWriter_DisposeTests_Negative()
{
using (Stream memStream = CreateStream())
{
BinaryWriter binaryWriter = new BinaryWriter(memStream);
binaryWriter.Dispose();
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Seek(1, SeekOrigin.Begin));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new byte[2], 0, 2));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new char[2], 0, 2));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(true));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((byte)4));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new byte[] { 1, 2 }));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write('a'));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new char[] { 'a', 'b' }));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(5.3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((short)3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(33));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((Int64)42));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((sbyte)4));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write("Hello There"));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((float)4.3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((UInt16)3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((uint)4));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((ulong)5));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write("Bah"));
}
}
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class TypeParserTests : BaseTestFixture {
[Test]
public void SimpleStringReference ()
{
var module = GetCurrentModule ();
var corlib = module.TypeSystem.Corlib;
const string fullname = "System.String";
var type = TypeParser.ParseType (module, fullname);
Assert.IsNotNull (type);
Assert.AreEqual (corlib, type.Scope);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("System", type.Namespace);
Assert.AreEqual ("String", type.Name);
Assert.AreEqual (MetadataType.String, type.MetadataType);
Assert.IsFalse (type.IsValueType);
Assert.IsInstanceOf (typeof (TypeReference), type);
}
[Test]
public void SimpleInt32Reference ()
{
var module = GetCurrentModule ();
var corlib = module.TypeSystem.Corlib;
const string fullname = "System.Int32";
var type = TypeParser.ParseType (module, fullname);
Assert.IsNotNull (type);
Assert.AreEqual (corlib, type.Scope);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("System", type.Namespace);
Assert.AreEqual ("Int32", type.Name);
Assert.AreEqual (MetadataType.Int32, type.MetadataType);
Assert.IsTrue (type.IsValueType);
Assert.IsInstanceOf (typeof (TypeReference), type);
}
[Test]
public void SimpleTypeDefinition ()
{
var module = GetCurrentModule ();
const string fullname = "Mono.Cecil.Tests.TypeParserTests";
var type = TypeParser.ParseType (module, fullname);
Assert.IsNotNull (type);
Assert.AreEqual (module, type.Scope);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("Mono.Cecil.Tests", type.Namespace);
Assert.AreEqual ("TypeParserTests", type.Name);
Assert.IsInstanceOf (typeof (TypeDefinition), type);
}
[Test]
public void ByRefTypeReference ()
{
var module = GetCurrentModule ();
var corlib = module.TypeSystem.Corlib;
const string fullname = "System.String&";
var type = TypeParser.ParseType (module, fullname);
Assert.IsInstanceOf (typeof (ByReferenceType), type);
type = ((ByReferenceType) type).ElementType;
Assert.IsNotNull (type);
Assert.AreEqual (corlib, type.Scope);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("System", type.Namespace);
Assert.AreEqual ("String", type.Name);
Assert.IsInstanceOf (typeof (TypeReference), type);
}
[Test]
public void FullyQualifiedTypeReference ()
{
var module = GetCurrentModule ();
var cecil = module.AssemblyReferences.Where (reference => reference.Name == "Mono.Cecil").First ();
var fullname = "Mono.Cecil.TypeDefinition, " + cecil.FullName;
var type = TypeParser.ParseType (module, fullname);
Assert.IsNotNull (type);
Assert.AreEqual (cecil, type.Scope);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("Mono.Cecil", type.Namespace);
Assert.AreEqual ("TypeDefinition", type.Name);
Assert.IsInstanceOf (typeof (TypeReference), type);
}
[Test]
public void OpenGenericType ()
{
var module = GetCurrentModule ();
var corlib = module.TypeSystem.Corlib;
const string fullname = "System.Collections.Generic.Dictionary`2";
var type = TypeParser.ParseType (module, fullname);
Assert.IsNotNull (type);
Assert.AreEqual (corlib, type.Scope);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("System.Collections.Generic", type.Namespace);
Assert.AreEqual ("Dictionary`2", type.Name);
Assert.IsInstanceOf (typeof (TypeReference), type);
Assert.AreEqual (2, type.GenericParameters.Count);
}
public class ID {}
[Test]
public void SimpleNestedType ()
{
var module = GetCurrentModule ();
const string fullname = "Mono.Cecil.Tests.TypeParserTests+ID";
var type = TypeParser.ParseType (module, fullname);
Assert.IsNotNull (type);
Assert.AreEqual (module, type.Module);
Assert.AreEqual (module, type.Scope);
Assert.AreEqual ("", type.Namespace);
Assert.AreEqual ("ID", type.Name);
Assert.AreEqual ("Mono.Cecil.Tests.TypeParserTests/ID", type.FullName);
Assert.AreEqual (fullname, TypeParser.ToParseable (type));
}
[Test]
public void TripleNestedTypeWithScope ()
{
var module = GetCurrentModule ();
const string fullname = "Bingo.Foo`1+Bar`1+Baz`1, Bingo";
var type = TypeParser.ParseType (module, fullname);
Assert.AreEqual ("Bingo.Foo`1+Bar`1+Baz`1, Bingo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", TypeParser.ToParseable (type));
Assert.IsNotNull (type);
Assert.AreEqual ("Bingo", type.Scope.Name);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("", type.Namespace);
Assert.AreEqual ("Baz`1", type.Name);
Assert.IsInstanceOf (typeof (TypeReference), type);
Assert.AreEqual (1, type.GenericParameters.Count);
type = type.DeclaringType;
Assert.IsNotNull (type);
Assert.AreEqual ("Bingo", type.Scope.Name);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("", type.Namespace);
Assert.AreEqual ("Bar`1", type.Name);
Assert.IsInstanceOf (typeof (TypeReference), type);
Assert.AreEqual (1, type.GenericParameters.Count);
type = type.DeclaringType;
Assert.IsNotNull (type);
Assert.AreEqual ("Bingo", type.Scope.Name);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("Bingo", type.Namespace);
Assert.AreEqual ("Foo`1", type.Name);
Assert.IsInstanceOf (typeof (TypeReference), type);
Assert.AreEqual (1, type.GenericParameters.Count);
}
[Test]
public void Vector ()
{
var module = GetCurrentModule ();
const string fullname = "Bingo.Gazonk[], Bingo";
var type = TypeParser.ParseType (module, fullname);
Assert.AreEqual ("Bingo.Gazonk[], Bingo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", TypeParser.ToParseable (type));
var array = type as ArrayType;
Assert.IsNotNull (array);
Assert.AreEqual (1, array.Rank);
Assert.IsTrue (array.IsVector);
type = array.ElementType;
Assert.IsNotNull (type);
Assert.AreEqual ("Bingo", type.Scope.Name);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("Bingo", type.Namespace);
Assert.AreEqual ("Gazonk", type.Name);
Assert.IsInstanceOf (typeof (TypeReference), type);
}
[Test]
public void ThreeDimensionalArray ()
{
var module = GetCurrentModule ();
const string fullname = "Bingo.Gazonk[,,], Bingo";
var type = TypeParser.ParseType (module, fullname);
var array = type as ArrayType;
Assert.IsNotNull (array);
Assert.AreEqual (3, array.Rank);
Assert.IsFalse (array.IsVector);
type = array.ElementType;
Assert.IsNotNull (type);
Assert.AreEqual ("Bingo", type.Scope.Name);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("Bingo", type.Namespace);
Assert.AreEqual ("Gazonk", type.Name);
Assert.IsInstanceOf (typeof (TypeReference), type);
}
[Test]
public void GenericInstanceExternArguments ()
{
var module = GetCurrentModule ();
var fullname = string.Format ("System.Collections.Generic.Dictionary`2[[System.Int32, {0}],[System.String, {0}]]",
typeof (object).Assembly.FullName);
var type = TypeParser.ParseType (module, fullname);
Assert.AreEqual (fullname, TypeParser.ToParseable (type));
var instance = type as GenericInstanceType;
Assert.IsNotNull (instance);
Assert.AreEqual (2, instance.GenericArguments.Count);
Assert.AreEqual ("mscorlib", type.Scope.Name);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("System.Collections.Generic", type.Namespace);
Assert.AreEqual ("Dictionary`2", type.Name);
type = instance.ElementType;
Assert.AreEqual (2, type.GenericParameters.Count);
var argument = instance.GenericArguments [0];
Assert.AreEqual ("mscorlib", argument.Scope.Name);
Assert.AreEqual (module, argument.Module);
Assert.AreEqual ("System", argument.Namespace);
Assert.AreEqual ("Int32", argument.Name);
argument = instance.GenericArguments [1];
Assert.AreEqual ("mscorlib", argument.Scope.Name);
Assert.AreEqual (module, argument.Module);
Assert.AreEqual ("System", argument.Namespace);
Assert.AreEqual ("String", argument.Name);
}
[Test]
public void GenericInstanceMixedArguments ()
{
var module = GetCurrentModule ();
var fullname = string.Format ("System.Collections.Generic.Dictionary`2[Mono.Cecil.Tests.TypeParserTests,[System.String, {0}]]",
typeof (object).Assembly.FullName);
var type = TypeParser.ParseType (module, fullname);
var instance = type as GenericInstanceType;
Assert.IsNotNull (instance);
Assert.AreEqual (2, instance.GenericArguments.Count);
Assert.AreEqual ("mscorlib", type.Scope.Name);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("System.Collections.Generic", type.Namespace);
Assert.AreEqual ("Dictionary`2", type.Name);
type = instance.ElementType;
Assert.AreEqual (2, type.GenericParameters.Count);
var argument = instance.GenericArguments [0];
Assert.IsInstanceOf (typeof (TypeDefinition), argument);
Assert.AreEqual (module, argument.Module);
Assert.AreEqual ("Mono.Cecil.Tests", argument.Namespace);
Assert.AreEqual ("TypeParserTests", argument.Name);
argument = instance.GenericArguments [1];
Assert.AreEqual ("mscorlib", argument.Scope.Name);
Assert.AreEqual (module, argument.Module);
Assert.AreEqual ("System", argument.Namespace);
Assert.AreEqual ("String", argument.Name);
}
public class Foo<TX, TY> {
}
public class Bar {}
[Test]
public void GenericInstanceTwoNonFqArguments ()
{
var module = GetCurrentModule ();
var fullname = string.Format ("System.Collections.Generic.Dictionary`2[Mono.Cecil.Tests.TypeParserTests+Bar,Mono.Cecil.Tests.TypeParserTests+Bar], {0}", typeof (object).Assembly.FullName);
var type = TypeParser.ParseType (module, fullname);
var instance = type as GenericInstanceType;
Assert.IsNotNull (instance);
Assert.AreEqual (2, instance.GenericArguments.Count);
Assert.AreEqual ("mscorlib", type.Scope.Name);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("System.Collections.Generic", type.Namespace);
Assert.AreEqual ("Dictionary`2", type.Name);
type = instance.ElementType;
Assert.AreEqual (2, type.GenericParameters.Count);
var argument = instance.GenericArguments [0];
Assert.AreEqual (module, argument.Module);
Assert.AreEqual ("", argument.Namespace);
Assert.AreEqual ("Bar", argument.Name);
Assert.IsInstanceOf (typeof (TypeDefinition), argument);
argument = instance.GenericArguments [1];
Assert.AreEqual (module, argument.Module);
Assert.AreEqual ("", argument.Namespace);
Assert.AreEqual ("Bar", argument.Name);
Assert.IsInstanceOf (typeof (TypeDefinition), argument);
}
[Test]
public void ComplexGenericInstanceMixedArguments ()
{
var module = GetCurrentModule ();
var fullname = string.Format ("System.Collections.Generic.Dictionary`2[[System.String, {0}],Mono.Cecil.Tests.TypeParserTests+Foo`2[Mono.Cecil.Tests.TypeParserTests,[System.Int32, {0}]]]",
typeof (object).Assembly.FullName);
var type = TypeParser.ParseType (module, fullname);
var instance = type as GenericInstanceType;
Assert.IsNotNull (instance);
Assert.AreEqual (2, instance.GenericArguments.Count);
Assert.AreEqual ("mscorlib", type.Scope.Name);
Assert.AreEqual (module, type.Module);
Assert.AreEqual ("System.Collections.Generic", type.Namespace);
Assert.AreEqual ("Dictionary`2", type.Name);
type = instance.ElementType;
Assert.AreEqual (2, type.GenericParameters.Count);
var argument = instance.GenericArguments [0];
Assert.AreEqual ("mscorlib", argument.Scope.Name);
Assert.AreEqual (module, argument.Module);
Assert.AreEqual ("System", argument.Namespace);
Assert.AreEqual ("String", argument.Name);
argument = instance.GenericArguments [1];
instance = argument as GenericInstanceType;
Assert.IsNotNull (instance);
Assert.AreEqual (2, instance.GenericArguments.Count);
Assert.AreEqual (module, instance.Module);
Assert.AreEqual ("Mono.Cecil.Tests.TypeParserTests/Foo`2", instance.ElementType.FullName);
Assert.IsInstanceOf (typeof (TypeDefinition), instance.ElementType);
argument = instance.GenericArguments [0];
Assert.AreEqual (module, argument.Module);
Assert.AreEqual ("Mono.Cecil.Tests", argument.Namespace);
Assert.AreEqual ("TypeParserTests", argument.Name);
Assert.IsInstanceOf (typeof (TypeDefinition), argument);
argument = instance.GenericArguments [1];
Assert.AreEqual ("mscorlib", argument.Scope.Name);
Assert.AreEqual (module, argument.Module);
Assert.AreEqual ("System", argument.Namespace);
Assert.AreEqual ("Int32", argument.Name);
}
}
}
| |
using System;
using System.ComponentModel.Design;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace GuruComponents.Netrix.UserInterface.TypeEditors
{
/// <summary>
/// OptionCollectionEditor lets the user edit OPTION tags within a SELECT tag.
/// </summary>
/// <remarks>
/// This editor is used to support the PropertyGrid.
/// You should not use this class directly from user code as far as you don't write
/// your own PropertyGrid support.
/// <para>
/// This editor supports OPTION and OPTGROUP tags.
/// </para>
/// </remarks>
public class OptionCollectionEditor : CollectionEditor
{
Type tBase;
IHtmlEditor editor;
/// <summary>
/// Instantiates the collection editor the first time.
/// </summary>
/// <remarks>
/// This method supports the NetRix infrastructure and should not beeing used from user code.
/// </remarks>
/// <param name="type"></param>
public OptionCollectionEditor(Type type) : base(type)
{
tBase = type;
}
/// <summary>
/// This method defines the both option types for the dropdown button.
/// </summary>
/// <remarks>
/// The purpose of this method is to prepare the editor for handling to different instances.
/// This is necessary to support the HTML 4.0 SELECT tag which can handle OPTION as well as OPTGROUP
/// elements the same time.
/// </remarks>
/// <returns></returns>
protected override Type[] CreateNewItemTypes()
{
return new Type[] {
(Type) tBase.GetField("OptionElementType").GetValue("OptionElementType"),
(Type) tBase.GetField("OptGroupElementType").GetValue("OptGroupElementType")
};
}
protected override object CreateInstance(Type itemType)
{
if (itemType.BaseType.Name.EndsWith("Element"))
{
// need to pull the editor to override the default ctor behavior
IDesignerHost host = this.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host != null)
{
editor = host.GetType().GetField("editor", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(host) as IHtmlEditor;
}
return Activator.CreateInstance(itemType, editor);
}
else
{
return base.CreateInstance(itemType);
}
}
private static Stream stream = typeof(OptionCollectionEditor).Assembly.GetManifestResourceStream("GuruComponents.Netrix.UserInterface.Resources.Resx.UserInterface.CollectionEditorAddImage.ico");
/// <summary>
/// Takes the base collection form and apply some changes.
/// </summary>
/// <remarks>
/// This method uses reflection to change the internal collection editor dialog on-thy-fly.
/// </remarks>
/// <returns>The changed form is beeing returned completely.</returns>
protected override CollectionForm CreateCollectionForm()
{
CollectionForm form = base.CreateCollectionForm();
form.FormBorderStyle = FormBorderStyle.SizableToolWindow;
form.Text = "<OPTION><OPTGROUP> Editor";
Type t = form.GetType();
// Get the private variables via Reflection
FieldInfo fieldInfo;
fieldInfo = t.GetField("propertyBrowser", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
PropertyGrid propertyGrid = (PropertyGrid) fieldInfo.GetValue(form);
if (propertyGrid != null)
{
propertyGrid.ToolbarVisible = false;
propertyGrid.HelpVisible = true;
}
}
fieldInfo = t.GetField("upButton", BindingFlags.NonPublic | BindingFlags.Instance);
// we add the events here to force the underlying collection beeing reordered after each up/down step to
// allow the application to refresh the display of the element even on order steps
if (fieldInfo != null)
{
Button upButton = (Button) fieldInfo.GetValue(form);
}
fieldInfo = t.GetField("downButton", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
Button downButton = (Button) fieldInfo.GetValue(form);
}
fieldInfo = t.GetField("helpButton", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
Button removeButton = (Button) fieldInfo.GetValue(form);
removeButton.Visible = false;
}
fieldInfo = t.GetField("addButton", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
Button addButton = (Button) fieldInfo.GetValue(form);
addButton.Text = ResourceManager.GetString("OptionCollectionEditor.addButton.Text");
}
fieldInfo = t.GetField("addDownButton", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
Button addDownButton = (Button) fieldInfo.GetValue(form);
addDownButton.BackColor = SystemColors.Control;
addDownButton.ImageList = null;
// we modify the image because the original one has a terrible gray background...
addDownButton.Image = Image.FromStream(stream);
}
fieldInfo = t.GetField("addDownMenu", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
switch (fieldInfo.GetValue(form).GetType().Name)
{
case "ContextMenu":
ContextMenu addMenu = (ContextMenu) fieldInfo.GetValue(form);
if (addMenu.MenuItems.Count == 2)
{
addMenu.MenuItems[0].Text = "<OPTION>";
addMenu.MenuItems[1].Text = "<OPTGROUP>";
}
break;
# if !DOTNET20
case "ContextMenuStrip":
ContextMenuStrip ctxMenu = (ContextMenuStrip) fieldInfo.GetValue(form);
if (ctxMenu.Items.Count == 2)
{
ctxMenu.Items[0].Text = "<OPTION>";
ctxMenu.Items[1].Text = "<OPTGROUP>";
}
break;
# endif
}
}
fieldInfo = t.GetField("removeButton", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
Button removeButton = (Button) fieldInfo.GetValue(form);
removeButton.Text = ResourceManager.GetString("OptionCollectionEditor.removeButton.Text");
}
fieldInfo = t.GetField("okButton", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
Button okButton = (Button) fieldInfo.GetValue(form);
okButton.Left += okButton.Width + 3;
}
fieldInfo = t.GetField("cancelButton", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
Button cancelButton = (Button) fieldInfo.GetValue(form);
cancelButton.Left += cancelButton.Width + 3;
}
Label memberLabel = new Label();
memberLabel.Text = ResourceManager.GetString("OptionCollectionEditor.memberLabel.Text");
memberLabel.Location = new Point(10, 8);
memberLabel.Size = new Size(200, 15);
form.Controls.Add(memberLabel);
memberLabel.BringToFront();
return form;
}
/// <summary>
/// User can remove tags.
/// </summary>
/// <param name="value">The current value. Not beeing used here.</param>
/// <returns>Returns always <c>true</c> to allow instance removing.</returns>
protected override bool CanRemoveInstance(object value)
{
return true;
}
/// <summary>
/// User cannot select multiple tags at the same time.
/// </summary>
/// <returns>Returns always <c>false</c>.</returns>
protected override bool CanSelectMultipleInstances()
{
return false;
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
/*
* dk.brics.automaton
*
* Copyright (c) 2001-2009 Anders Moeller
* 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.
* 3. 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.
*/
namespace Lucene.Net.Util.Automaton
{
/// <summary>
/// <see cref="Automaton"/> state.
/// <para/>
/// @lucene.experimental
/// </summary>
public class State : IComparable<State>
{
internal bool accept;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public Transition[] TransitionsArray
{
get { return transitionsArray; }
// LUCENENET NOTE: Setter removed because it is apparently not in use outside of this class
}
private Transition[] transitionsArray;
internal int numTransitions; // LUCENENET NOTE: Made internal because we already have a public property for access
internal int number;
internal int id;
internal static int next_id;
/// <summary>
/// Constructs a new state. Initially, the new state is a reject state.
/// </summary>
public State()
{
ResetTransitions();
id = next_id++;
}
/// <summary>
/// Resets transition set.
/// </summary>
internal void ResetTransitions()
{
transitionsArray = new Transition[0];
numTransitions = 0;
}
private class TransitionsIterable : IEnumerable<Transition>
{
private readonly State outerInstance;
public TransitionsIterable(State outerInstance)
{
this.outerInstance = outerInstance;
}
public virtual IEnumerator<Transition> GetEnumerator()
{
return new IteratorAnonymousInnerClassHelper(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private class IteratorAnonymousInnerClassHelper : IEnumerator<Transition>
{
private readonly TransitionsIterable outerInstance;
private Transition current;
private int i, upTo;
public IteratorAnonymousInnerClassHelper(TransitionsIterable outerInstance)
{
this.outerInstance = outerInstance;
upTo = this.outerInstance.outerInstance.numTransitions;
i = 0;
}
public bool MoveNext()
{
if (i < upTo)
{
current = outerInstance.outerInstance.transitionsArray[i++];
return true;
}
return false;
}
public Transition Current
{
get
{
return current;
}
}
object System.Collections.IEnumerator.Current
{
get
{
return Current;
}
}
public void Reset()
{
throw new NotSupportedException();
}
public void Dispose()
{
}
}
}
/// <summary>
/// Returns the set of outgoing transitions. Subsequent changes are reflected
/// in the automaton.
/// </summary>
/// <returns> Transition set. </returns>
public virtual IEnumerable<Transition> GetTransitions()
{
return new TransitionsIterable(this);
}
public virtual int NumTransitions
{
get { return numTransitions; }
}
public virtual void SetTransitions(Transition[] transitions)
{
this.numTransitions = transitions.Length;
this.transitionsArray = transitions;
}
/// <summary>
/// Adds an outgoing transition.
/// </summary>
/// <param name="t"> Transition. </param>
public virtual void AddTransition(Transition t)
{
if (numTransitions == transitionsArray.Length)
{
Transition[] newArray = new Transition[ArrayUtil.Oversize(1 + numTransitions, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
Array.Copy(transitionsArray, 0, newArray, 0, numTransitions);
transitionsArray = newArray;
}
transitionsArray[numTransitions++] = t;
}
/// <summary>
/// Sets acceptance for this state. If <c>true</c>, this state is an accept state.
/// </summary>
public virtual bool Accept
{
set
{
this.accept = value;
}
get
{
return accept;
}
}
/// <summary>
/// Performs lookup in transitions, assuming determinism.
/// </summary>
/// <param name="c"> Codepoint to look up. </param>
/// <returns> Destination state, <c>null</c> if no matching outgoing transition. </returns>
/// <seealso cref="Step(int, ICollection{State})"/>
public virtual State Step(int c)
{
Debug.Assert(c >= 0);
for (int i = 0; i < numTransitions; i++)
{
Transition t = transitionsArray[i];
if (t.min <= c && c <= t.max)
{
return t.to;
}
}
return null;
}
/// <summary>
/// Performs lookup in transitions, allowing nondeterminism.
/// </summary>
/// <param name="c"> Codepoint to look up. </param>
/// <param name="dest"> Collection where destination states are stored. </param>
/// <seealso cref="Step(int)"/>
public virtual void Step(int c, ICollection<State> dest)
{
for (int i = 0; i < numTransitions; i++)
{
Transition t = transitionsArray[i];
if (t.min <= c && c <= t.max)
{
dest.Add(t.to);
}
}
}
/// <summary>
/// Virtually adds an epsilon transition to the target
/// <paramref name="to"/> state. this is implemented by copying all
/// transitions from <paramref name="to"/> to this state, and if
/// <paramref name="to"/> is an accept state then set accept for this state.
/// </summary>
internal virtual void AddEpsilon(State to)
{
if (to.accept)
{
accept = true;
}
foreach (Transition t in to.GetTransitions())
{
AddTransition(t);
}
}
/// <summary>
/// Downsizes transitionArray to numTransitions. </summary>
public virtual void TrimTransitionsArray()
{
if (numTransitions < transitionsArray.Length)
{
Transition[] newArray = new Transition[numTransitions];
Array.Copy(transitionsArray, 0, newArray, 0, numTransitions);
transitionsArray = newArray;
}
}
/// <summary>
/// Reduces this state. A state is "reduced" by combining overlapping
/// and adjacent edge intervals with same destination.
/// </summary>
public virtual void Reduce()
{
if (numTransitions <= 1)
{
return;
}
SortTransitions(Transition.COMPARE_BY_DEST_THEN_MIN_MAX);
State p = null;
int min = -1, max = -1;
int upto = 0;
for (int i = 0; i < numTransitions; i++)
{
Transition t = transitionsArray[i];
if (p == t.to)
{
if (t.min <= max + 1)
{
if (t.max > max)
{
max = t.max;
}
}
else
{
if (p != null)
{
transitionsArray[upto++] = new Transition(min, max, p);
}
min = t.min;
max = t.max;
}
}
else
{
if (p != null)
{
transitionsArray[upto++] = new Transition(min, max, p);
}
p = t.to;
min = t.min;
max = t.max;
}
}
if (p != null)
{
transitionsArray[upto++] = new Transition(min, max, p);
}
numTransitions = upto;
}
/// <summary>
/// Returns sorted list of outgoing transitions.
/// </summary>
/// <param name="comparer"> Comparer to sort with. </param>
/// <returns> Transition list. </returns>
/// <summary>
/// Sorts transitions array in-place. </summary>
public virtual void SortTransitions(IComparer<Transition> comparer)
{
// mergesort seems to perform better on already sorted arrays:
if (numTransitions > 1)
{
ArrayUtil.TimSort(transitionsArray, 0, numTransitions, comparer);
}
}
/// <summary>
/// Return this state's number.
/// <para/>
/// Expert: Will be useless unless <see cref="Automaton.GetNumberedStates()"/>
/// has been called first to number the states. </summary>
/// <returns> The number. </returns>
public virtual int Number
{
get
{
return number;
}
}
/// <summary>
/// Returns string describing this state. Normally invoked via
/// <see cref="Automaton.ToString()"/>.
/// </summary>
public override string ToString()
{
StringBuilder b = new StringBuilder();
b.Append("state ").Append(number);
if (accept)
{
b.Append(" [accept]");
}
else
{
b.Append(" [reject]");
}
b.Append(":\n");
foreach (Transition t in GetTransitions())
{
b.Append(" ").Append(t.ToString()).Append("\n");
}
return b.ToString();
}
/// <summary>
/// Compares this object with the specified object for order. States are
/// ordered by the time of construction.
/// </summary>
public virtual int CompareTo(State s)
{
return s.id - id;
}
public override int GetHashCode()
{
return id;
}
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Citrina
{
public enum BaseUserGroupFields
{
[EnumMember(Value = "about")]
About,
[EnumMember(Value = "action_button")]
ActionButton,
[EnumMember(Value = "activities")]
Activities,
[EnumMember(Value = "activity")]
Activity,
[EnumMember(Value = "addresses")]
Addresses,
[EnumMember(Value = "admin_level")]
AdminLevel,
[EnumMember(Value = "age_limits")]
AgeLimits,
[EnumMember(Value = "author_id")]
AuthorId,
[EnumMember(Value = "ban_info")]
BanInfo,
[EnumMember(Value = "bdate")]
Bdate,
[EnumMember(Value = "blacklisted")]
Blacklisted,
[EnumMember(Value = "blacklisted_by_me")]
BlacklistedByMe,
[EnumMember(Value = "books")]
Books,
[EnumMember(Value = "can_create_topic")]
CanCreateTopic,
[EnumMember(Value = "can_message")]
CanMessage,
[EnumMember(Value = "can_post")]
CanPost,
[EnumMember(Value = "can_see_all_posts")]
CanSeeAllPosts,
[EnumMember(Value = "can_see_audio")]
CanSeeAudio,
[EnumMember(Value = "can_send_friend_request")]
CanSendFriendRequest,
[EnumMember(Value = "can_upload_video")]
CanUploadVideo,
[EnumMember(Value = "can_write_private_message")]
CanWritePrivateMessage,
[EnumMember(Value = "career")]
Career,
[EnumMember(Value = "city")]
City,
[EnumMember(Value = "common_count")]
CommonCount,
[EnumMember(Value = "connections")]
Connections,
[EnumMember(Value = "contacts")]
Contacts,
[EnumMember(Value = "counters")]
Counters,
[EnumMember(Value = "country")]
Country,
[EnumMember(Value = "cover")]
Cover,
[EnumMember(Value = "crop_photo")]
CropPhoto,
[EnumMember(Value = "deactivated")]
Deactivated,
[EnumMember(Value = "description")]
Description,
[EnumMember(Value = "domain")]
Domain,
[EnumMember(Value = "education")]
Education,
[EnumMember(Value = "exports")]
Exports,
[EnumMember(Value = "finish_date")]
FinishDate,
[EnumMember(Value = "fixed_post")]
FixedPost,
[EnumMember(Value = "followers_count")]
FollowersCount,
[EnumMember(Value = "friend_status")]
FriendStatus,
[EnumMember(Value = "games")]
Games,
[EnumMember(Value = "has_market_app")]
HasMarketApp,
[EnumMember(Value = "has_mobile")]
HasMobile,
[EnumMember(Value = "has_photo")]
HasPhoto,
[EnumMember(Value = "home_town")]
HomeTown,
[EnumMember(Value = "id")]
Id,
[EnumMember(Value = "interests")]
Interests,
[EnumMember(Value = "is_admin")]
IsAdmin,
[EnumMember(Value = "is_closed")]
IsClosed,
[EnumMember(Value = "is_favorite")]
IsFavorite,
[EnumMember(Value = "is_friend")]
IsFriend,
[EnumMember(Value = "is_hidden_from_feed")]
IsHiddenFromFeed,
[EnumMember(Value = "is_member")]
IsMember,
[EnumMember(Value = "is_messages_blocked")]
IsMessagesBlocked,
[EnumMember(Value = "can_send_notify")]
CanSendNotify,
[EnumMember(Value = "is_subscribed")]
IsSubscribed,
[EnumMember(Value = "last_seen")]
LastSeen,
[EnumMember(Value = "links")]
Links,
[EnumMember(Value = "lists")]
Lists,
[EnumMember(Value = "maiden_name")]
MaidenName,
[EnumMember(Value = "main_album_id")]
MainAlbumId,
[EnumMember(Value = "main_section")]
MainSection,
[EnumMember(Value = "market")]
Market,
[EnumMember(Value = "member_status")]
MemberStatus,
[EnumMember(Value = "members_count")]
MembersCount,
[EnumMember(Value = "military")]
Military,
[EnumMember(Value = "movies")]
Movies,
[EnumMember(Value = "music")]
Music,
[EnumMember(Value = "name")]
Name,
[EnumMember(Value = "nickname")]
Nickname,
[EnumMember(Value = "occupation")]
Occupation,
[EnumMember(Value = "online")]
Online,
[EnumMember(Value = "online_status")]
OnlineStatus,
[EnumMember(Value = "personal")]
Personal,
[EnumMember(Value = "phone")]
Phone,
[EnumMember(Value = "photo_100")]
Photo100,
[EnumMember(Value = "photo_200")]
Photo200,
[EnumMember(Value = "photo_200_orig")]
Photo200Orig,
[EnumMember(Value = "photo_400_orig")]
Photo400Orig,
[EnumMember(Value = "photo_50")]
Photo50,
[EnumMember(Value = "photo_id")]
PhotoId,
[EnumMember(Value = "photo_max")]
PhotoMax,
[EnumMember(Value = "photo_max_orig")]
PhotoMaxOrig,
[EnumMember(Value = "quotes")]
Quotes,
[EnumMember(Value = "relation")]
Relation,
[EnumMember(Value = "relatives")]
Relatives,
[EnumMember(Value = "schools")]
Schools,
[EnumMember(Value = "screen_name")]
ScreenName,
[EnumMember(Value = "sex")]
Sex,
[EnumMember(Value = "site")]
Site,
[EnumMember(Value = "start_date")]
StartDate,
[EnumMember(Value = "status")]
Status,
[EnumMember(Value = "timezone")]
Timezone,
[EnumMember(Value = "trending")]
Trending,
[EnumMember(Value = "tv")]
Tv,
[EnumMember(Value = "type")]
Type,
[EnumMember(Value = "universities")]
Universities,
[EnumMember(Value = "verified")]
Verified,
[EnumMember(Value = "wall_comments")]
WallComments,
[EnumMember(Value = "wiki_page")]
WikiPage,
[EnumMember(Value = "vk_admin_status")]
VkAdminStatus,
}
}
| |
/*
Copyright 2008 The 'A Concurrent Hashtable' development team
(http://www.codeplex.com/CH/People/ProjectPeople.aspx)
This library is licensed under the GNU Library General Public License (LGPL). You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at http://www.codeplex.com/CH/license.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace Orvid.Concurrent.Threading
{
/// <summary>
/// Tiny spin lock that allows multiple readers simultanously and 1 writer exclusively
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public struct TinyReaderWriterLock
{
#if !SILVERLIGHT
[NonSerialized]
#endif
Int32 _Bits;
const int ReadersInRegionOffset = 0;
const int ReadersInRegionsMask = 255;
const int ReadersWaitingOffset = 8;
const int ReadersWaitingMask = 255;
const int WriterInRegionOffset = 16;
const int WritersWaitingOffset = 17;
const int WritersWaitingMask = 15;
const int BiasOffset = 21;
const int BiasMask = 3;
enum Bias { None = 0, Readers = 1, Writers = 2 };
struct Data
{
public int _ReadersInRegion;
public int _ReadersWaiting;
public bool _WriterInRegion;
public int _WritersWaiting;
public Bias _Bias;
public Int32 _OldBits;
}
void GetData(out Data data)
{
Int32 bits = _Bits;
data._ReadersInRegion = bits & ReadersInRegionsMask ;
data._ReadersWaiting = (bits >> ReadersWaitingOffset) & ReadersWaitingMask;
data._WriterInRegion = ((bits >> WriterInRegionOffset) & 1) != 0;
data._WritersWaiting = (bits >> WritersWaitingOffset) & WritersWaitingMask;
data._Bias = (Bias)((bits >> BiasOffset) & BiasMask);
data._OldBits = bits;
}
bool SetData(ref Data data)
{
Int32 bits ;
bits =
data._ReadersInRegion
| (data._ReadersWaiting << ReadersWaitingOffset)
| ((data._WriterInRegion ? 1 : 0) << WriterInRegionOffset)
| (data._WritersWaiting << WritersWaitingOffset)
| ((int)data._Bias << BiasOffset);
return Interlocked.CompareExchange(ref _Bits, bits, data._OldBits) == data._OldBits;
}
/// <summary>
/// Release a reader lock
/// </summary>
public void ReleaseForReading()
{
//try shortcut first.
if (Interlocked.CompareExchange(ref _Bits, 0, 1) == 1)
return;
Data data;
do
{
GetData(out data);
#if DEBUG
if (data._ReadersInRegion == 0)
throw new InvalidOperationException("Mismatching Lock/Release for reading.");
//if (data._WriterInRegion)
// throw new InvalidOperationException("Unexpected writer in region.");
#endif
--data._ReadersInRegion;
if (data._ReadersInRegion == 0 && data._ReadersWaiting == 0)
data._Bias = data._WritersWaiting != 0 ? Bias.Writers : Bias.None;
}
while (!SetData(ref data));
}
/// <summary>
/// Release a writer lock
/// </summary>
public void ReleaseForWriting()
{
//try shortcut first.
if (Interlocked.CompareExchange(ref _Bits, 0, 1 << WriterInRegionOffset) == 1 << WriterInRegionOffset)
return;
Data data;
do
{
GetData(out data);
#if DEBUG
if (!data._WriterInRegion)
throw new InvalidOperationException("Mismatching Lock/Release for writing.");
//if (data._ReadersInRegion != 0)
// throw new InvalidOperationException("Unexpected reader in region.");
#endif
data._WriterInRegion = false;
if (data._WritersWaiting == 0)
data._Bias = data._ReadersWaiting != 0 ? Bias.Readers : Bias.None;
}
while (!SetData(ref data));
}
/// <summary>
/// Aquire a reader lock. Wait until lock is aquired.
/// </summary>
public void LockForReading()
{ LockForReading(true); }
/// <summary>
/// Aquire a reader lock.
/// </summary>
/// <param name="wait">True if to wait until lock aquired, False to return immediately.</param>
/// <returns>Boolean indicating if lock was successfuly aquired.</returns>
public bool LockForReading(bool wait)
{
//try shortcut first.
if (Interlocked.CompareExchange(ref _Bits, 1, 0) == 0)
return true;
bool waitingRegistered = false;
try
{
while (true)
{
bool retry = false;
Data data;
GetData(out data);
if (data._Bias != Bias.Writers)
{
if (data._ReadersInRegion < ReadersInRegionsMask && !data._WriterInRegion)
{
if (waitingRegistered)
{
data._Bias = Bias.Readers;
--data._ReadersWaiting;
++data._ReadersInRegion;
if (SetData(ref data))
{
waitingRegistered = false;
return true;
}
else
retry = true;
}
else if (data._WritersWaiting == 0)
{
data._Bias = Bias.Readers;
++data._ReadersInRegion;
if (SetData(ref data))
return true;
else
retry = true;
}
}
//sleep
}
else
{
if (!waitingRegistered && data._ReadersWaiting < ReadersWaitingMask && wait)
{
++data._ReadersWaiting;
if (SetData(ref data))
{
waitingRegistered = true;
//sleep
}
else
retry = true;
}
//sleep
}
if (!retry)
{
if (!wait)
return false;
System.Threading.Thread.Sleep(0);
}
}
}
finally
{
if (waitingRegistered)
{
//Thread aborted?
Data data;
do
{
GetData(out data);
--data._ReadersWaiting;
if (data._ReadersInRegion == 0 && data._ReadersWaiting == 0)
data._Bias = data._WritersWaiting != 0 ? Bias.Writers : Bias.None;
}
while (!SetData(ref data));
}
}
}
/// <summary>
/// Aquire a writer lock. Wait until lock is aquired.
/// </summary>
public void LockForWriting()
{ LockForWriting(true); }
/// <summary>
/// Aquire a writer lock.
/// </summary>
/// <param name="wait">True if to wait until lock aquired, False to return immediately.</param>
/// <returns>Boolean indicating if lock was successfuly aquired.</returns>
public bool LockForWriting(bool wait)
{
//try shortcut first.
if (Interlocked.CompareExchange(ref _Bits, 1 << WriterInRegionOffset, 0) == 0)
return true;
bool waitingRegistered = false;
try
{
while (true)
{
bool retry = false;
Data data;
GetData(out data);
if (data._Bias != Bias.Readers)
{
if (data._ReadersInRegion == 0 && !data._WriterInRegion)
{
if (waitingRegistered)
{
data._Bias = Bias.Writers;
--data._WritersWaiting;
data._WriterInRegion = true;
if (SetData(ref data))
{
waitingRegistered = false;
return true;
}
else
retry = true;
}
else if (data._ReadersWaiting == 0)
{
data._Bias = Bias.Writers;
data._WriterInRegion = true;
if (SetData(ref data))
return true;
else
retry = true;
}
}
//sleep
}
else
{
if (!waitingRegistered && data._WritersWaiting < WritersWaitingMask && wait)
{
++data._WritersWaiting;
if (SetData(ref data))
{
waitingRegistered = true;
//sleep
}
else
retry = true;
}
//sleep
}
if (!retry)
{
if (!wait)
return false;
System.Threading.Thread.Sleep(0);
}
}
}
finally
{
if (waitingRegistered)
{
//Thread aborted?
Data data;
do
{
GetData(out data);
--data._WritersWaiting;
if (!data._WriterInRegion && data._WritersWaiting == 0)
data._Bias = data._ReadersWaiting != 0 ? Bias.Readers : Bias.None;
}
while (!SetData(ref data));
}
}
}
}
}
| |
// 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 RoundToNearestIntegerDouble()
{
var test = new SimpleUnaryOpTest__RoundToNearestIntegerDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local 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__RoundToNearestIntegerDouble
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector256<Double> _clsVar;
private Vector256<Double> _fld;
private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable;
static SimpleUnaryOpTest__RoundToNearestIntegerDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__RoundToNearestIntegerDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.RoundToNearestInteger(
Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.RoundToNearestInteger(
Avx.LoadVector256((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.RoundToNearestInteger(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNearestInteger), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNearestInteger), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNearestInteger), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.RoundToNearestInteger(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr);
var result = Avx.RoundToNearestInteger(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Double*)(_dataTable.inArrayPtr));
var result = Avx.RoundToNearestInteger(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr));
var result = Avx.RoundToNearestInteger(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__RoundToNearestIntegerDouble();
var result = Avx.RoundToNearestInteger(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.RoundToNearestInteger(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[0], MidpointRounding.AwayFromZero)))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[i], MidpointRounding.AwayFromZero)))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.RoundToNearestInteger)}<Double>(Vector256<Double>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Drawing2D
{
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Drawing.Internal;
/**
* Represent a LinearGradient brush object
*/
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush"]/*' />
/// <devdoc>
/// <para>
/// Encapsulates a <see cref='System.Drawing.Brush'/> with a linear gradient.
/// </para>
/// </devdoc>
public sealed class LinearGradientBrush : Brush
{
private bool _interpolationColorsWasSet;
/**
* Create a new rectangle gradient brush object
*/
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.LinearGradientBrush"]/*' />
/// <devdoc>
/// Initializes a new instance of the <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> class with the specified points and
/// colors.
/// </devdoc>
public LinearGradientBrush(PointF point1, PointF point2,
Color color1, Color color2)
{
IntPtr brush = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrush(new GPPOINTF(point1),
new GPPOINTF(point2),
color1.ToArgb(),
color2.ToArgb(),
(int)WrapMode.Tile,
out brush);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeBrushInternal(brush);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.LinearGradientBrush1"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> class with the
/// specified points and colors.
/// </para>
/// </devdoc>
public LinearGradientBrush(Point point1, Point point2,
Color color1, Color color2)
{
IntPtr brush = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushI(new GPPOINT(point1),
new GPPOINT(point2),
color1.ToArgb(),
color2.ToArgb(),
(int)WrapMode.Tile,
out brush);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeBrushInternal(brush);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.LinearGradientBrush2"]/*' />
/// <devdoc>
/// <para>
/// Encapsulates a new instance of the <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> class with
/// the specified points, colors, and orientation.
/// </para>
/// </devdoc>
public LinearGradientBrush(RectangleF rect, Color color1, Color color2,
LinearGradientMode linearGradientMode)
{
//validate the LinearGradientMode enum
//valid values are 0x0 to 0x3
if (!ClientUtils.IsEnumValid(linearGradientMode, unchecked((int)linearGradientMode), (int)LinearGradientMode.Horizontal, (int)LinearGradientMode.BackwardDiagonal))
{
throw new InvalidEnumArgumentException("linearGradientMode", unchecked((int)linearGradientMode), typeof(LinearGradientMode));
}
//validate the rect
if (rect.Width == 0.0 || rect.Height == 0.0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
IntPtr brush = IntPtr.Zero;
GPRECTF gprectf = new GPRECTF(rect);
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRect(ref gprectf,
color1.ToArgb(),
color2.ToArgb(),
unchecked((int)linearGradientMode),
(int)WrapMode.Tile,
out brush);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeBrushInternal(brush);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.LinearGradientBrush3"]/*' />
/// <devdoc>
/// <para>
/// Encapsulates a new instance of the <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> class with the
/// specified points, colors, and orientation.
/// </para>
/// </devdoc>
public LinearGradientBrush(Rectangle rect, Color color1, Color color2,
LinearGradientMode linearGradientMode)
{
//validate the LinearGradientMode enum
//valid values are 0x0 to 0x3
if (!ClientUtils.IsEnumValid(linearGradientMode, unchecked((int)linearGradientMode), (int)LinearGradientMode.Horizontal, (int)LinearGradientMode.BackwardDiagonal))
{
throw new InvalidEnumArgumentException("linearGradientMode", unchecked((int)linearGradientMode), typeof(LinearGradientMode));
}
//validate the rect
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
IntPtr brush = IntPtr.Zero;
GPRECT gpRect = new GPRECT(rect);
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectI(ref gpRect,
color1.ToArgb(),
color2.ToArgb(),
unchecked((int)linearGradientMode),
(int)WrapMode.Tile,
out brush);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeBrushInternal(brush);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.LinearGradientBrush4"]/*' />
/// <devdoc>
/// <para>
/// Encapsulates a new instance of the <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> class with the
/// specified points, colors, and orientation.
/// </para>
/// </devdoc>
public LinearGradientBrush(RectangleF rect, Color color1, Color color2,
float angle)
: this(rect, color1, color2, angle, false)
{ }
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.LinearGradientBrush5"]/*' />
/// <devdoc>
/// <para>
/// Encapsulates a new instance of the <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> class with the
/// specified points, colors, and orientation.
/// </para>
/// </devdoc>
public LinearGradientBrush(RectangleF rect, Color color1, Color color2,
float angle, bool isAngleScaleable)
{
IntPtr brush = IntPtr.Zero;
//validate the rect
if (rect.Width == 0.0 || rect.Height == 0.0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
GPRECTF gprectf = new GPRECTF(rect);
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngle(ref gprectf,
color1.ToArgb(),
color2.ToArgb(),
angle,
isAngleScaleable,
(int)WrapMode.Tile,
out brush);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeBrushInternal(brush);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.LinearGradientBrush6"]/*' />
/// <devdoc>
/// <para>
/// Encapsulates a new instance of the <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> class with the
/// specified points, colors, and orientation.
/// </para>
/// </devdoc>
public LinearGradientBrush(Rectangle rect, Color color1, Color color2,
float angle)
: this(rect, color1, color2, angle, false)
{
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.LinearGradientBrush7"]/*' />
/// <devdoc>
/// <para>
/// Encapsulates a new instance of the <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> class with the
/// specified points, colors, and orientation.
/// </para>
/// </devdoc>
public LinearGradientBrush(Rectangle rect, Color color1, Color color2,
float angle, bool isAngleScaleable)
{
IntPtr brush = IntPtr.Zero;
//validate the rect
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
GPRECT gprect = new GPRECT(rect);
int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngleI(ref gprect,
color1.ToArgb(),
color2.ToArgb(),
angle,
isAngleScaleable,
(int)WrapMode.Tile,
out brush);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeBrushInternal(brush);
}
/// <devdoc>
/// Constructor to initialized this object to be owned by GDI+.
/// </devdoc>
internal LinearGradientBrush(IntPtr nativeBrush)
{
Debug.Assert(nativeBrush != IntPtr.Zero, "Initializing native brush with null.");
SetNativeBrushInternal(nativeBrush);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.Clone"]/*' />
/// <devdoc>
/// Creates an exact copy of this <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/>.
/// </devdoc>
public override object Clone()
{
IntPtr cloneBrush = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out cloneBrush);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return new LinearGradientBrush(cloneBrush);
}
/**
* Get/set colors
*/
private void _SetLinearColors(Color color1, Color color2)
{
int status = SafeNativeMethods.Gdip.GdipSetLineColors(new HandleRef(this, NativeBrush),
color1.ToArgb(),
color2.ToArgb());
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
private Color[] _GetLinearColors()
{
int[] colors =
new int[]
{
0,
0
};
int status = SafeNativeMethods.Gdip.GdipGetLineColors(new HandleRef(this, NativeBrush), colors);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
Color[] lineColor = new Color[2];
lineColor[0] = Color.FromArgb(colors[0]);
lineColor[1] = Color.FromArgb(colors[1]);
return lineColor;
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.LinearColors"]/*' />
/// <devdoc>
/// Gets or sets the starting and ending colors of the
/// gradient.
/// </devdoc>
public Color[] LinearColors
{
get { return _GetLinearColors(); }
set { _SetLinearColors(value[0], value[1]); }
}
/**
* Get source rectangle
*/
private RectangleF _GetRectangle()
{
GPRECTF rect = new GPRECTF();
int status = SafeNativeMethods.Gdip.GdipGetLineRect(new HandleRef(this, NativeBrush), ref rect);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return rect.ToRectangleF();
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.Rectangle"]/*' />
/// <devdoc>
/// <para>
/// Gets a rectangular region that defines the
/// starting and ending points of the gradient.
/// </para>
/// </devdoc>
public RectangleF Rectangle
{
get { return _GetRectangle(); }
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.GammaCorrection"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether
/// gamma correction is enabled for this <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/>.
/// </para>
/// </devdoc>
public bool GammaCorrection
{
get
{
bool useGammaCorrection;
int status = SafeNativeMethods.Gdip.GdipGetLineGammaCorrection(new HandleRef(this, NativeBrush),
out useGammaCorrection);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return useGammaCorrection;
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetLineGammaCorrection(new HandleRef(this, NativeBrush),
value);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
/**
* Get/set blend factors
*
* @notes If the blendFactors.Length = 1, then it's treated
* as the falloff parameter. Otherwise, it's the array
* of blend factors.
*/
private Blend _GetBlend()
{
// VSWHidbey 518309 - interpolation colors and blends don't get along. Just getting
// the Blend when InterpolationColors was set puts the Brush into an unusable state afterwards.
// so to avoid that (mostly the problem of having Blend pop up in the debugger window and cause this problem)
// we just bail here.
//
if (_interpolationColorsWasSet)
{
return null;
}
Blend blend;
// Figure out the size of blend factor array
int retval = 0;
int status = SafeNativeMethods.Gdip.GdipGetLineBlendCount(new HandleRef(this, NativeBrush), out retval);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
if (retval <= 0)
{
return null;
}
// Allocate temporary native memory buffer
int count = retval;
IntPtr factors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
factors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
// Retrieve horizontal blend factors
status = SafeNativeMethods.Gdip.GdipGetLineBlend(new HandleRef(this, NativeBrush), factors, positions, count);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
// Return the result in a managed array
blend = new Blend(count);
Marshal.Copy(factors, blend.Factors, 0, count);
Marshal.Copy(positions, blend.Positions, 0, count);
}
finally
{
if (factors != IntPtr.Zero)
{
Marshal.FreeHGlobal(factors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
return blend;
}
private void _SetBlend(Blend blend)
{
// Allocate temporary native memory buffer
// and copy input blend factors into it.
int count = blend.Factors.Length;
IntPtr factors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
factors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
Marshal.Copy(blend.Factors, 0, factors, count);
Marshal.Copy(blend.Positions, 0, positions, count);
// Set blend factors
int status = SafeNativeMethods.Gdip.GdipSetLineBlend(new HandleRef(this, NativeBrush), new HandleRef(null, factors), new HandleRef(null, positions), count);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
finally
{
if (factors != IntPtr.Zero)
{
Marshal.FreeHGlobal(factors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.Blend"]/*' />
/// <devdoc>
/// Gets or sets a <see cref='System.Drawing.Drawing2D.Blend'/> that specifies
/// positions and factors that define a custom falloff for the gradient.
/// </devdoc>
public Blend Blend
{
get { return _GetBlend(); }
set { _SetBlend(value); }
}
/*
* SigmaBlend & LinearBlend not yet implemented
*/
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.SetSigmaBellShape"]/*' />
/// <devdoc>
/// Creates a gradient falloff based on a
/// bell-shaped curve.
/// </devdoc>
public void SetSigmaBellShape(float focus)
{
SetSigmaBellShape(focus, (float)1.0);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.SetSigmaBellShape1"]/*' />
/// <devdoc>
/// Creates a gradient falloff based on a
/// bell-shaped curve.
/// </devdoc>
public void SetSigmaBellShape(float focus, float scale)
{
int status = SafeNativeMethods.Gdip.GdipSetLineSigmaBlend(new HandleRef(this, NativeBrush), focus, scale);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.SetBlendTriangularShape"]/*' />
/// <devdoc>
/// <para>
/// Creates a triangular gradient.
/// </para>
/// </devdoc>
public void SetBlendTriangularShape(float focus)
{
SetBlendTriangularShape(focus, (float)1.0);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.SetBlendTriangularShape1"]/*' />
/// <devdoc>
/// <para>
/// Creates a triangular gradient.
/// </para>
/// </devdoc>
public void SetBlendTriangularShape(float focus, float scale)
{
int status = SafeNativeMethods.Gdip.GdipSetLineLinearBlend(new HandleRef(this, NativeBrush), focus, scale);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/*
* Preset Color Blend
*/
private ColorBlend _GetInterpolationColors()
{
ColorBlend blend;
if (!_interpolationColorsWasSet)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsColorBlendNotSet), ""));
}
// Figure out the size of blend factor array
int retval = 0;
int status = SafeNativeMethods.Gdip.GdipGetLinePresetBlendCount(new HandleRef(this, NativeBrush), out retval);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
// Allocate temporary native memory buffer
int count = retval;
IntPtr colors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
colors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
// Retrieve horizontal blend factors
status = SafeNativeMethods.Gdip.GdipGetLinePresetBlend(new HandleRef(this, NativeBrush), colors, positions, count);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
// Return the result in a managed array
blend = new ColorBlend(count);
int[] argb = new int[count];
Marshal.Copy(colors, argb, 0, count);
Marshal.Copy(positions, blend.Positions, 0, count);
// copy ARGB values into Color array of ColorBlend
blend.Colors = new Color[argb.Length];
for (int i = 0; i < argb.Length; i++)
{
blend.Colors[i] = Color.FromArgb(argb[i]);
}
}
finally
{
if (colors != IntPtr.Zero)
{
Marshal.FreeHGlobal(colors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
return blend;
}
private void _SetInterpolationColors(ColorBlend blend)
{
_interpolationColorsWasSet = true;
// Validate the ColorBlend object.
if (blend == null)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject), ""));
}
else if (blend.Colors.Length < 2)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsLength)));
}
else if (blend.Colors.Length != blend.Positions.Length)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsLengthsDiffer)));
}
else if (blend.Positions[0] != 0.0f)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsInvalidStartPosition)));
}
else if (blend.Positions[blend.Positions.Length - 1] != 1.0f)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
SR.Format(SR.InterpolationColorsInvalidEndPosition)));
}
// Allocate temporary native memory buffer
// and copy input blend factors into it.
int count = blend.Colors.Length;
IntPtr colors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
colors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
int[] argbs = new int[count];
for (int i = 0; i < count; i++)
{
argbs[i] = blend.Colors[i].ToArgb();
}
Marshal.Copy(argbs, 0, colors, count);
Marshal.Copy(blend.Positions, 0, positions, count);
// Set blend factors
int status = SafeNativeMethods.Gdip.GdipSetLinePresetBlend(new HandleRef(this, NativeBrush), new HandleRef(null, colors), new HandleRef(null, positions), count);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
finally
{
if (colors != IntPtr.Zero)
{
Marshal.FreeHGlobal(colors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.InterpolationColors"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a <see cref='System.Drawing.Drawing2D.ColorBlend'/> that defines a multi-color linear
/// gradient.
/// </para>
/// </devdoc>
public ColorBlend InterpolationColors
{
get { return _GetInterpolationColors(); }
set { _SetInterpolationColors(value); }
}
/**
* Set/get brush wrapping mode
*/
private void _SetWrapMode(WrapMode wrapMode)
{
int status = SafeNativeMethods.Gdip.GdipSetLineWrapMode(new HandleRef(this, NativeBrush), unchecked((int)wrapMode));
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
private WrapMode _GetWrapMode()
{
int mode = 0;
int status = SafeNativeMethods.Gdip.GdipGetLineWrapMode(new HandleRef(this, NativeBrush), out mode);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return (WrapMode)mode;
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.WrapMode"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a <see cref='System.Drawing.Drawing2D.WrapMode'/> that indicates the wrap mode for this <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/>.
/// </para>
/// </devdoc>
public WrapMode WrapMode
{
get
{
return _GetWrapMode();
}
set
{
//validate the WrapMode enum
//valid values are 0x0 to 0x4
if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)WrapMode.Tile, (int)WrapMode.Clamp))
{
throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(WrapMode));
}
_SetWrapMode(value);
}
}
/**
* Set/get brush transform
*/
private void _SetTransform(Matrix matrix)
{
if (matrix == null)
throw new ArgumentNullException("matrix");
int status = SafeNativeMethods.Gdip.GdipSetLineTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.nativeMatrix));
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
private Matrix _GetTransform()
{
Matrix matrix = new Matrix();
// NOTE: new Matrix() will throw an exception if matrix == null.
int status = SafeNativeMethods.Gdip.GdipGetLineTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.nativeMatrix));
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return matrix;
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.Transform"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a <see cref='System.Drawing.Drawing2D.Matrix'/> that defines a local geometrical transform for
/// this <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/>.
/// </para>
/// </devdoc>
public Matrix Transform
{
get { return _GetTransform(); }
set { _SetTransform(value); }
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.ResetTransform"]/*' />
/// <devdoc>
/// Resets the <see cref='System.Drawing.Drawing2D.LinearGradientBrush.Transform'/> property to identity.
/// </devdoc>
public void ResetTransform()
{
int status = SafeNativeMethods.Gdip.GdipResetLineTransform(new HandleRef(this, NativeBrush));
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.MultiplyTransform"]/*' />
/// <devdoc>
/// <para>
/// Multiplies the <see cref='System.Drawing.Drawing2D.Matrix'/> that represents the local geometrical
/// transform of this <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> by the specified <see cref='System.Drawing.Drawing2D.Matrix'/> by prepending the specified <see cref='System.Drawing.Drawing2D.Matrix'/>.
/// </para>
/// </devdoc>
public void MultiplyTransform(Matrix matrix)
{
MultiplyTransform(matrix, MatrixOrder.Prepend);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.MultiplyTransform1"]/*' />
/// <devdoc>
/// <para>
/// Multiplies the <see cref='System.Drawing.Drawing2D.Matrix'/> that represents the local geometrical
/// transform of this <see cref='System.Drawing.Drawing2D.LinearGradientBrush'/> by the specified <see cref='System.Drawing.Drawing2D.Matrix'/> in the specified order.
/// </para>
/// </devdoc>
public void MultiplyTransform(Matrix matrix, MatrixOrder order)
{
if (matrix == null)
{
throw new ArgumentNullException("matrix");
}
int status = SafeNativeMethods.Gdip.GdipMultiplyLineTransform(new HandleRef(this, NativeBrush),
new HandleRef(matrix, matrix.nativeMatrix),
order);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.TranslateTransform"]/*' />
/// <devdoc>
/// Translates the local geometrical transform
/// by the specified dimmensions. This method prepends the translation to the
/// transform.
/// </devdoc>
public void TranslateTransform(float dx, float dy)
{ TranslateTransform(dx, dy, MatrixOrder.Prepend); }
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.TranslateTransform1"]/*' />
/// <devdoc>
/// Translates the local geometrical transform
/// by the specified dimmensions in the specified order.
/// </devdoc>
public void TranslateTransform(float dx, float dy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipTranslateLineTransform(new HandleRef(this, NativeBrush),
dx,
dy,
order);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.ScaleTransform"]/*' />
/// <devdoc>
/// Scales the local geometric transform by the
/// specified amounts. This method prepends the scaling matrix to the transform.
/// </devdoc>
public void ScaleTransform(float sx, float sy)
{ ScaleTransform(sx, sy, MatrixOrder.Prepend); }
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.ScaleTransform1"]/*' />
/// <devdoc>
/// <para>
/// Scales the local geometric transform by the
/// specified amounts in the specified order.
/// </para>
/// </devdoc>
public void ScaleTransform(float sx, float sy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipScaleLineTransform(new HandleRef(this, NativeBrush),
sx,
sy,
order);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.RotateTransform"]/*' />
/// <devdoc>
/// Rotates the local geometric transform by the
/// specified amount. This method prepends the rotation to the transform.
/// </devdoc>
public void RotateTransform(float angle)
{ RotateTransform(angle, MatrixOrder.Prepend); }
/// <include file='doc\LinearGradientBrush.uex' path='docs/doc[@for="LinearGradientBrush.RotateTransform1"]/*' />
/// <devdoc>
/// <para>
/// Rotates the local geometric transform by the specified
/// amount in the specified order.
/// </para>
/// </devdoc>
public void RotateTransform(float angle, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipRotateLineTransform(new HandleRef(this, NativeBrush),
angle,
order);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
}
| |
using Discord;
using NLog;
using System;
namespace NikoBot.Services.Database
{
public class GreetService
{
private static Logger _log;
public static string AddGreet(IGuild guild, IMessageChannel channel, string message)
{
try
{
_log = LogManager.GetCurrentClassLogger();
var database = new Database("nikobot");
var str = string.Format("UPDATE guildconfig SET ChannelGreetMsg = '{1}', GreetMsg = '{2}' WHERE GuildId = '{0}'", guild.Id, channel.Id, message);
var tableName = database.FireCommand(str);
/*
while (tableName.Read())
{
var Raid = (string)tableName["raid"];
result.Add(Raid);
}*/
database.CloseConnection();
_log.Warn("\nLog ativado com sucesso no servidor {0} !\n", guild.Name.ToString());
return null;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
public static string CheckLogger(IGuild guild)
{
try
{
string msg = "";
var database = new Database("nikobot");
var str = string.Format("SELECT ChannelGreetMsg FROM guildconfig WHERE GuildId = '{0}'", guild.Id);
var tableName = database.FireCommand(str);
while (tableName.Read())
{
msg = Convert.ToString(tableName[0]);
}
database.CloseConnection();
tableName.Close();
return msg;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
public static string Checkmsg(IGuild guild)
{
try
{
string msg = "";
var database = new Database("nikobot");
var str = string.Format("SELECT GreetMsg FROM guildconfig WHERE GuildId = '{0}'", guild.Id);
var tableName = database.FireCommand(str);
while (tableName.Read())
{
msg = Convert.ToString(tableName[0]);
}
database.CloseConnection();
return msg;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
public static string DelGreet(IGuild guild)
{
try
{
_log = LogManager.GetCurrentClassLogger();
var database = new Database("nikobot");
var str = string.Format("UPDATE guildconfig SET ChannelGreetMsg = '{1}' WHERE GuildId = '{0}'", guild.Id, DBNull.Value);
var tableName = database.FireCommand(str);
/*
while (tableName.Read())
{
var Raid = (string)tableName["raid"];
result.Add(Raid);
}*/
database.CloseConnection();
_log.Warn("\nLog desativado com sucesso no servidor {0} !\n", guild.Name.ToString());
return null;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
public static string AddGuild(IGuild guild)
{
try
{
_log = LogManager.GetCurrentClassLogger();
var database = new Database("nikobot");
var str = string.Format("INSERT INTO guildconfig (GuildId) VALUES ('{0}')", guild.Id);
var tableName = database.FireCommand(str);
/*
while (tableName.Read())
{
var Raid = (string)tableName["raid"];
result.Add(Raid);
}*/
database.CloseConnection();
_log.Error("Row added with success for guild {0} !\n", guild.Name.ToString());
return null;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
public static string RemoveGuild(IGuild guild)
{
try
{
_log = LogManager.GetCurrentClassLogger();
var database = new Database("nikobot");
var str = string.Format("DELETE FROM guildconfig WHERE GuildId = '{0}'", guild.Id);
var tableName = database.FireCommand(str);
/*
while (tableName.Read())
{
var Raid = (string)tableName["raid"];
result.Add(Raid);
}*/
database.CloseConnection();
_log.Warn("Row deleted with success for guild {0} !\n", guild.Name.ToString());
return null;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
public static string AddLeft(IGuild guild, IMessageChannel channel, string message)
{
try
{
_log = LogManager.GetCurrentClassLogger();
var database = new Database("nikobot");
var str = string.Format("UPDATE guildconfig SET ChannelByeMsg = '{1}', ByeMsg = '{2}' WHERE GuildId = '{0}'", guild.Id, channel.Id, message);
var tableName = database.FireCommand(str);
/*
while (tableName.Read())
{
var Raid = (string)tableName["raid"];
result.Add(Raid);
}*/
database.CloseConnection();
_log.Warn("\nLog ativado com sucesso no servidor {0} !\n", guild.Name.ToString());
return null;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
public static string CheckLeftCh(IGuild guild)
{
try
{
string msg = "";
var database = new Database("nikobot");
var str = string.Format("SELECT ChannelByeMsg FROM guildconfig WHERE GuildId = '{0}'", guild.Id);
var tableName = database.FireCommand(str);
while (tableName.Read())
{
msg = Convert.ToString(tableName[0]);
}
database.CloseConnection();
return msg;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
public static string DelLeftCh(IGuild guild)
{
try
{
_log = LogManager.GetCurrentClassLogger();
var database = new Database("nikobot");
var str = string.Format("UPDATE guildconfig SET ChannelByeMsg = '{1}' WHERE GuildId = '{0}'", guild.Id, DBNull.Value);
var tableName = database.FireCommand(str);
/*
while (tableName.Read())
{
var Raid = (string)tableName["raid"];
result.Add(Raid);
}*/
database.CloseConnection();
_log.Warn("\nLog desativado com sucesso no servidor {0} !\n", guild.Name.ToString());
return null;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
public static string CheckLeftMsg(IGuild guild)
{
try
{
string msg = "";
var database = new Database("nikobot");
var str = string.Format("SELECT ByeMsg FROM guildconfig WHERE GuildId = '{0}'", guild.Id);
var tableName = database.FireCommand(str);
while (tableName.Read())
{
msg = Convert.ToString(tableName[0]);
}
database.CloseConnection();
return msg;
}
catch (Exception e)
{
Console.Write(e);
return null;
}
}
}
}
| |
using System;
using System.IO;
using Htc.Vita.Core.Log;
using Htc.Vita.Core.Net;
namespace Htc.Vita.Core.TestService
{
internal class LoggerImpl : Logger
{
private readonly string _path;
public LoggerImpl(string name) : base(name)
{
_path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
_path = Path.Combine(_path, "HTC", "Vita", "Logs");
if (!Directory.Exists(_path))
{
Directory.CreateDirectory(_path);
}
_path = Path.Combine(_path, WebUserAgent.GetModuleInstanceName() + ".log");
}
protected override void OnDebug(string tag, string message)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
File.AppendAllText(_path, "[" + Name + "][Debug][" + tag + "] " + message + Environment.NewLine);
}
protected override void OnDebug(string tag, string message, Exception exception)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
if (exception == null)
{
File.AppendAllText(_path, "[" + Name + "][Debug][" + tag + "] " + message + Environment.NewLine);
}
else
{
File.AppendAllText(_path, "[" + Name + "][Debug][" + tag + "] " + message + ", " + exception.StackTrace + Environment.NewLine);
}
}
protected override void OnError(string tag, string message)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
File.AppendAllText(_path, "[" + Name + "][Error][" + tag + "] " + message + Environment.NewLine);
}
protected override void OnError(string tag, string message, Exception exception)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
if (exception == null)
{
File.AppendAllText(_path, "[" + Name + "][Error][" + tag + "] " + message + Environment.NewLine);
}
else
{
File.AppendAllText(_path, "[" + Name + "][Error][" + tag + "] " + message + ", " + exception.StackTrace + Environment.NewLine);
}
}
protected override void OnFatal(string tag, string message)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
File.AppendAllText(_path, "[" + Name + "][Fatal][" + tag + "] " + message + Environment.NewLine);
}
protected override void OnFatal(string tag, string message, Exception exception)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
if (exception == null)
{
File.AppendAllText(_path, "[" + Name + "][Fatal][" + tag + "] " + message + Environment.NewLine);
}
else
{
File.AppendAllText(_path, "[" + Name + "][Fatal][" + tag + "] " + message + ", " + exception.StackTrace + Environment.NewLine);
}
}
protected override void OnInfo(string tag, string message)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
File.AppendAllText(_path, "[" + Name + "][Info][" + tag + "] " + message + Environment.NewLine);
}
protected override void OnInfo(string tag, string message, Exception exception)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
if (exception == null)
{
File.AppendAllText(_path, "[" + Name + "][Info][" + tag + "] " + message + Environment.NewLine);
}
else
{
File.AppendAllText(_path, "[" + Name + "][Info][" + tag + "] " + message + ", " + exception.StackTrace + Environment.NewLine);
}
}
protected override void OnShutdown()
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
File.AppendAllText(_path, "Shutdown the logger ..." + Environment.NewLine);
}
protected override void OnTrace(string tag, string message)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
File.AppendAllText(_path, "[" + Name + "][Trace][" + tag + "] " + message + Environment.NewLine);
}
protected override void OnTrace(string tag, string message, Exception exception)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
if (exception == null)
{
File.AppendAllText(_path, "[" + Name + "][Trace][" + tag + "] " + message + Environment.NewLine);
}
else
{
File.AppendAllText(_path, "[" + Name + "][Trace][" + tag + "] " + message + ", " + exception.StackTrace + Environment.NewLine);
}
}
protected override void OnWarn(string tag, string message)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
File.AppendAllText(_path, "[" + Name + "][Warn][" + tag + "] " + message + Environment.NewLine);
}
protected override void OnWarn(string tag, string message, Exception exception)
{
if (string.IsNullOrWhiteSpace(_path))
{
return;
}
if (exception == null)
{
File.AppendAllText(_path, "[" + Name + "][Warn][" + tag + "] " + message + Environment.NewLine);
}
else
{
File.AppendAllText(_path, "[" + Name + "][Warn][" + tag + "] " + message + ", " + exception.StackTrace + Environment.NewLine);
}
}
}
}
| |
// 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.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using MahApps.Metro.ValueBoxes;
namespace MahApps.Metro.Controls
{
/// <summary>
/// enumeration for the different transition types
/// </summary>
public enum TransitionType
{
/// <summary>
/// Use the VisualState DefaultTransition
/// </summary>
Default,
/// <summary>
/// Use the VisualState Normal
/// </summary>
Normal,
/// <summary>
/// Use the VisualState UpTransition
/// </summary>
Up,
/// <summary>
/// Use the VisualState DownTransition
/// </summary>
Down,
/// <summary>
/// Use the VisualState RightTransition
/// </summary>
Right,
/// <summary>
/// Use the VisualState RightReplaceTransition
/// </summary>
RightReplace,
/// <summary>
/// Use the VisualState LeftTransition
/// </summary>
Left,
/// <summary>
/// Use the VisualState LeftReplaceTransition
/// </summary>
LeftReplace,
/// <summary>
/// Use a custom VisualState, the name must be set using CustomVisualStatesName property
/// </summary>
Custom
}
/// <summary>
/// A ContentControl that animates content as it loads and unloads.
/// </summary>
[TemplatePart(Name = PreviousContentPresentationSitePartName, Type = typeof(ContentPresenter))]
[TemplatePart(Name = CurrentContentPresentationSitePartName, Type = typeof(ContentPresenter))]
public class TransitioningContentControl : ContentControl
{
internal const string PresentationGroup = "PresentationStates";
internal const string HiddenState = "Hidden";
internal const string PreviousContentPresentationSitePartName = "PreviousContentPresentationSite";
internal const string CurrentContentPresentationSitePartName = "CurrentContentPresentationSite";
private ContentPresenter? currentContentPresentationSite;
private ContentPresenter? previousContentPresentationSite;
private bool allowIsTransitioningPropertyWrite;
private Storyboard? currentTransition;
public event RoutedEventHandler? TransitionCompleted;
public const TransitionType DefaultTransitionState = TransitionType.Default;
public static readonly DependencyProperty IsTransitioningProperty
= DependencyProperty.Register(nameof(IsTransitioning),
typeof(bool),
typeof(TransitioningContentControl),
new PropertyMetadata(BooleanBoxes.FalseBox, OnIsTransitioningPropertyChanged));
/// <summary>
/// Gets whether if the content is transitioning.
/// </summary>
public bool IsTransitioning
{
get => (bool)this.GetValue(IsTransitioningProperty);
private set
{
this.allowIsTransitioningPropertyWrite = true;
try
{
this.SetValue(IsTransitioningProperty, BooleanBoxes.Box(value));
}
finally
{
this.allowIsTransitioningPropertyWrite = false;
}
}
}
public static readonly DependencyProperty TransitionProperty
= DependencyProperty.Register(nameof(Transition),
typeof(TransitionType),
typeof(TransitioningContentControl),
new FrameworkPropertyMetadata(TransitionType.Default, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.Inherits, OnTransitionPropertyChanged));
/// <summary>
/// Gets or sets the transition type.
/// </summary>
public TransitionType Transition
{
get => (TransitionType)this.GetValue(TransitionProperty);
set => this.SetValue(TransitionProperty, value);
}
public static readonly DependencyProperty RestartTransitionOnContentChangeProperty
= DependencyProperty.Register(nameof(RestartTransitionOnContentChange),
typeof(bool),
typeof(TransitioningContentControl),
new PropertyMetadata(BooleanBoxes.FalseBox, OnRestartTransitionOnContentChangePropertyChanged));
/// <summary>
/// Gets or sets whether if the transition should restart after the content change.
/// </summary>
public bool RestartTransitionOnContentChange
{
get => (bool)this.GetValue(RestartTransitionOnContentChangeProperty);
set => this.SetValue(RestartTransitionOnContentChangeProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty CustomVisualStatesProperty
= DependencyProperty.Register(nameof(CustomVisualStates),
typeof(ObservableCollection<VisualState>),
typeof(TransitioningContentControl),
new PropertyMetadata(null));
/// <summary>
/// Gets or sets customized visual states to use as transition.
/// </summary>
public ObservableCollection<VisualState>? CustomVisualStates
{
get => (ObservableCollection<VisualState>?)this.GetValue(CustomVisualStatesProperty);
set => this.SetValue(CustomVisualStatesProperty, value);
}
public static readonly DependencyProperty CustomVisualStatesNameProperty
= DependencyProperty.Register(nameof(CustomVisualStatesName),
typeof(string),
typeof(TransitioningContentControl),
new PropertyMetadata("CustomTransition"));
/// <summary>
/// Gets or sets the name of a custom transition visual state.
/// </summary>
public string CustomVisualStatesName
{
get => (string)this.GetValue(CustomVisualStatesNameProperty);
set => this.SetValue(CustomVisualStatesNameProperty, value);
}
internal Storyboard? CurrentTransition
{
get => this.currentTransition;
set
{
// decouple event
if (this.currentTransition != null)
{
this.currentTransition.Completed -= this.OnTransitionCompleted;
}
this.currentTransition = value;
if (this.currentTransition != null)
{
this.currentTransition.Completed += this.OnTransitionCompleted;
}
}
}
private static void OnIsTransitioningPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var source = (TransitioningContentControl)d;
if (!source.allowIsTransitioningPropertyWrite)
{
source.IsTransitioning = (bool)e.OldValue;
throw new InvalidOperationException();
}
}
private static void OnTransitionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var source = (TransitioningContentControl)d;
var oldTransition = (TransitionType)e.OldValue;
var newTransition = (TransitionType)e.NewValue;
if (source.IsTransitioning)
{
source.AbortTransition();
}
// find new transition
var newStoryboard = source.GetStoryboard(newTransition);
// unable to find the transition.
if (newStoryboard is null)
{
// could be during initialization of xaml that presentationgroups was not yet defined
if (VisualStates.TryGetVisualStateGroup(source, PresentationGroup) is null)
{
// will delay check
source.CurrentTransition = null;
}
else
{
// revert to old value
source.SetValue(TransitionProperty, oldTransition);
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Temporary removed exception message", newTransition));
}
}
else
{
source.CurrentTransition = newStoryboard;
}
}
private static void OnRestartTransitionOnContentChangePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TransitioningContentControl)d).OnRestartTransitionOnContentChangeChanged((bool)e.OldValue, (bool)e.NewValue);
}
protected virtual void OnRestartTransitionOnContentChangeChanged(bool oldValue, bool newValue)
{
}
public TransitioningContentControl()
{
this.CustomVisualStates = new ObservableCollection<VisualState>();
this.DefaultStyleKey = typeof(TransitioningContentControl);
}
public override void OnApplyTemplate()
{
if (this.IsTransitioning)
{
this.AbortTransition();
}
if (this.CustomVisualStates != null && this.CustomVisualStates.Any())
{
var presentationGroup = VisualStates.TryGetVisualStateGroup(this, PresentationGroup);
if (presentationGroup != null)
{
foreach (var state in this.CustomVisualStates)
{
presentationGroup.States.Add(state);
}
}
}
base.OnApplyTemplate();
this.previousContentPresentationSite = this.GetTemplateChild(PreviousContentPresentationSitePartName) as ContentPresenter;
this.currentContentPresentationSite = this.GetTemplateChild(CurrentContentPresentationSitePartName) as ContentPresenter;
// hookup currenttransition
var transition = this.GetStoryboard(this.Transition);
this.CurrentTransition = transition;
if (transition is null)
{
var invalidTransition = this.Transition;
// revert to default
this.Transition = DefaultTransitionState;
throw new MahAppsException($"'{invalidTransition}' transition could not be found!");
}
VisualStateManager.GoToState(this, HiddenState, false);
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
if (oldContent != newContent)
{
this.StartTransition(oldContent, newContent);
}
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "newContent", Justification = "Should be used in the future.")]
private void StartTransition(object oldContent, object newContent)
{
// both presenters must be available, otherwise a transition is useless.
if (this.currentContentPresentationSite != null && this.previousContentPresentationSite != null)
{
if (this.RestartTransitionOnContentChange
&& this.CurrentTransition is not null)
{
this.CurrentTransition.Completed -= this.OnTransitionCompleted;
}
this.currentContentPresentationSite.SetCurrentValue(ContentPresenter.ContentProperty, newContent);
this.previousContentPresentationSite.SetCurrentValue(ContentPresenter.ContentProperty, oldContent);
// and start a new transition
if (!this.IsTransitioning || this.RestartTransitionOnContentChange)
{
if (this.RestartTransitionOnContentChange
&& this.CurrentTransition is not null)
{
this.CurrentTransition.Completed += this.OnTransitionCompleted;
}
this.IsTransitioning = true;
VisualStateManager.GoToState(this, HiddenState, false);
VisualStateManager.GoToState(this, this.GetTransitionName(this.Transition), true);
}
}
}
/// <summary>
/// Reload the current transition if the content is the same.
/// </summary>
public void ReloadTransition()
{
// both presenters must be available, otherwise a transition is useless.
if (this.currentContentPresentationSite != null && this.previousContentPresentationSite != null)
{
if (this.RestartTransitionOnContentChange
&& this.CurrentTransition is not null)
{
this.CurrentTransition.Completed -= this.OnTransitionCompleted;
}
if (!this.IsTransitioning || this.RestartTransitionOnContentChange)
{
if (this.RestartTransitionOnContentChange
&& this.CurrentTransition is not null)
{
this.CurrentTransition.Completed += this.OnTransitionCompleted;
}
this.IsTransitioning = true;
VisualStateManager.GoToState(this, HiddenState, false);
VisualStateManager.GoToState(this, this.GetTransitionName(this.Transition), true);
}
}
}
private void OnTransitionCompleted(object? sender, EventArgs e)
{
this.AbortTransition();
var clockGroup = sender as ClockGroup;
if (clockGroup is null || clockGroup.CurrentState == ClockState.Stopped)
{
this.TransitionCompleted?.Invoke(this, new RoutedEventArgs());
}
}
public void AbortTransition()
{
// go to normal state and release our hold on the old content.
VisualStateManager.GoToState(this, HiddenState, false);
this.IsTransitioning = false;
this.previousContentPresentationSite?.SetCurrentValue(ContentPresenter.ContentProperty, null);
}
private Storyboard? GetStoryboard(TransitionType newTransition)
{
var presentationGroup = VisualStates.TryGetVisualStateGroup(this, PresentationGroup);
if (presentationGroup != null)
{
var transitionName = this.GetTransitionName(newTransition);
return presentationGroup.States
.OfType<VisualState>()
.Where(state => state.Name == transitionName)
.Select(state => state.Storyboard)
.FirstOrDefault();
}
return null;
}
private string GetTransitionName(TransitionType transition)
{
return transition switch
{
TransitionType.Default => "DefaultTransition",
TransitionType.Normal => "Normal",
TransitionType.Up => "UpTransition",
TransitionType.Down => "DownTransition",
TransitionType.Right => "RightTransition",
TransitionType.RightReplace => "RightReplaceTransition",
TransitionType.Left => "LeftTransition",
TransitionType.LeftReplace => "LeftReplaceTransition",
TransitionType.Custom => this.CustomVisualStatesName,
_ => "DefaultTransition"
};
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml
{
using System;
using System.Globalization;
using System.IO;
using System.Collections.Generic;
using System.Xml.Schema;
using System.Diagnostics;
/// <summary>
/// This writer wraps an XmlRawWriter and inserts additional lexical information into the resulting
/// Xml 1.0 document:
/// 1. CData sections
/// 2. DocType declaration
///
/// It also performs well-formed document checks if standalone="yes" and/or a doc-type-decl is output.
/// </summary>
internal class QueryOutputWriter : XmlRawWriter
{
private readonly XmlRawWriter _wrapped;
private bool _inCDataSection;
private readonly Dictionary<XmlQualifiedName, int> _lookupCDataElems;
private readonly BitStack _bitsCData;
private readonly XmlQualifiedName _qnameCData;
private bool _outputDocType;
private readonly bool _checkWellFormedDoc;
private bool _hasDocElem;
private bool _inAttr;
private readonly string _systemId, _publicId;
private int _depth;
public QueryOutputWriter(XmlRawWriter writer, XmlWriterSettings settings)
{
_wrapped = writer;
_systemId = settings.DocTypeSystem;
_publicId = settings.DocTypePublic;
if (settings.OutputMethod == XmlOutputMethod.Xml)
{
// Xml output method shouldn't output doc-type-decl if system ID is not defined (even if public ID is)
// Only check for well-formed document if output method is xml
if (_systemId != null)
{
_outputDocType = true;
_checkWellFormedDoc = true;
}
// Check for well-formed document if standalone="yes" in an auto-generated xml declaration
if (settings.AutoXmlDeclaration && settings.Standalone == XmlStandalone.Yes)
_checkWellFormedDoc = true;
if (settings.CDataSectionElements.Count > 0)
{
_bitsCData = new BitStack();
_lookupCDataElems = new Dictionary<XmlQualifiedName, int>();
_qnameCData = new XmlQualifiedName();
// Add each element name to the lookup table
foreach (XmlQualifiedName name in settings.CDataSectionElements)
{
_lookupCDataElems[name] = 0;
}
_bitsCData.PushBit(false);
}
}
else if (settings.OutputMethod == XmlOutputMethod.Html)
{
// Html output method should output doc-type-decl if system ID or public ID is defined
if (_systemId != null || _publicId != null)
_outputDocType = true;
}
}
//-----------------------------------------------
// XmlWriter interface
//-----------------------------------------------
/// <summary>
/// Get and set the namespace resolver that's used by this RawWriter to resolve prefixes.
/// </summary>
internal override IXmlNamespaceResolver NamespaceResolver
{
get
{
return this.resolver;
}
set
{
this.resolver = value;
_wrapped.NamespaceResolver = value;
}
}
/// <summary>
/// Write the xml declaration. This must be the first call.
/// </summary>
internal override void WriteXmlDeclaration(XmlStandalone standalone)
{
_wrapped.WriteXmlDeclaration(standalone);
}
internal override void WriteXmlDeclaration(string xmldecl)
{
_wrapped.WriteXmlDeclaration(xmldecl);
}
/// <summary>
/// Return settings provided to factory.
/// </summary>
public override XmlWriterSettings Settings
{
get
{
XmlWriterSettings settings = _wrapped.Settings;
settings.ReadOnly = false;
settings.DocTypeSystem = _systemId;
settings.DocTypePublic = _publicId;
settings.ReadOnly = true;
return settings;
}
}
/// <summary>
/// Suppress this explicit call to WriteDocType if information was provided by XmlWriterSettings.
/// </summary>
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
if (_publicId == null && _systemId == null)
{
Debug.Assert(!_outputDocType);
_wrapped.WriteDocType(name, pubid, sysid, subset);
}
}
/// <summary>
/// Check well-formedness, possibly output doc-type-decl, and determine whether this element is a
/// CData section element.
/// </summary>
public override void WriteStartElement(string prefix, string localName, string ns)
{
EndCDataSection();
if (_checkWellFormedDoc)
{
// Don't allow multiple document elements
if (_depth == 0 && _hasDocElem)
throw new XmlException(SR.Xml_NoMultipleRoots, string.Empty);
_depth++;
_hasDocElem = true;
}
// Output doc-type declaration immediately before first element is output
if (_outputDocType)
{
_wrapped.WriteDocType(
prefix.Length != 0 ? prefix + ":" + localName : localName,
_publicId,
_systemId,
null);
_outputDocType = false;
}
_wrapped.WriteStartElement(prefix, localName, ns);
if (_lookupCDataElems != null)
{
// Determine whether this element is a CData section element
_qnameCData.Init(localName, ns);
_bitsCData.PushBit(_lookupCDataElems.ContainsKey(_qnameCData));
}
}
internal override void WriteEndElement(string prefix, string localName, string ns)
{
EndCDataSection();
_wrapped.WriteEndElement(prefix, localName, ns);
if (_checkWellFormedDoc)
_depth--;
if (_lookupCDataElems != null)
_bitsCData.PopBit();
}
internal override void WriteFullEndElement(string prefix, string localName, string ns)
{
EndCDataSection();
_wrapped.WriteFullEndElement(prefix, localName, ns);
if (_checkWellFormedDoc)
_depth--;
if (_lookupCDataElems != null)
_bitsCData.PopBit();
}
internal override void StartElementContent()
{
_wrapped.StartElementContent();
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
_inAttr = true;
_wrapped.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
_inAttr = false;
_wrapped.WriteEndAttribute();
}
internal override void WriteNamespaceDeclaration(string prefix, string ns)
{
_wrapped.WriteNamespaceDeclaration(prefix, ns);
}
internal override bool SupportsNamespaceDeclarationInChunks
{
get
{
return _wrapped.SupportsNamespaceDeclarationInChunks;
}
}
internal override void WriteStartNamespaceDeclaration(string prefix)
{
_wrapped.WriteStartNamespaceDeclaration(prefix);
}
internal override void WriteEndNamespaceDeclaration()
{
_wrapped.WriteEndNamespaceDeclaration();
}
public override void WriteCData(string text)
{
_wrapped.WriteCData(text);
}
public override void WriteComment(string text)
{
EndCDataSection();
_wrapped.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
EndCDataSection();
_wrapped.WriteProcessingInstruction(name, text);
}
public override void WriteWhitespace(string ws)
{
if (!_inAttr && (_inCDataSection || StartCDataSection()))
_wrapped.WriteCData(ws);
else
_wrapped.WriteWhitespace(ws);
}
public override void WriteString(string text)
{
if (!_inAttr && (_inCDataSection || StartCDataSection()))
_wrapped.WriteCData(text);
else
_wrapped.WriteString(text);
}
public override void WriteChars(char[] buffer, int index, int count)
{
if (!_inAttr && (_inCDataSection || StartCDataSection()))
_wrapped.WriteCData(new string(buffer, index, count));
else
_wrapped.WriteChars(buffer, index, count);
}
public override void WriteEntityRef(string name)
{
EndCDataSection();
_wrapped.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch)
{
EndCDataSection();
_wrapped.WriteCharEntity(ch);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
EndCDataSection();
_wrapped.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
if (!_inAttr && (_inCDataSection || StartCDataSection()))
_wrapped.WriteCData(new string(buffer, index, count));
else
_wrapped.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
if (!_inAttr && (_inCDataSection || StartCDataSection()))
_wrapped.WriteCData(data);
else
_wrapped.WriteRaw(data);
}
public override void Close()
{
_wrapped.Close();
if (_checkWellFormedDoc && !_hasDocElem)
{
// Need at least one document element
throw new XmlException(SR.Xml_NoRoot, string.Empty);
}
}
public override void Flush()
{
_wrapped.Flush();
}
//-----------------------------------------------
// Helper methods
//-----------------------------------------------
/// <summary>
/// Write CData text if element is a CData element. Return true if text should be written
/// within a CData section.
/// </summary>
private bool StartCDataSection()
{
Debug.Assert(!_inCDataSection);
if (_lookupCDataElems != null && _bitsCData.PeekBit())
{
_inCDataSection = true;
return true;
}
return false;
}
/// <summary>
/// No longer write CData text.
/// </summary>
private void EndCDataSection()
{
_inCDataSection = false;
}
}
}
| |
// 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 System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Test.ModuleCore;
using System.IO;
using System.Reflection;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeBuilderTests : XLinqTestCase
{
public partial class NamespacehandlingSaveOptions : XLinqTestCase
{
private string _mode;
private Type _type;
public override void Init()
{
_mode = Params[0] as string;
_type = Params[1] as Type;
}
#region helpers
private void DumpMethodInfo(MethodInfo mi)
{
TestLog.WriteLineIgnore("Method with the params found: " + mi.Name);
foreach (var pi in mi.GetParameters())
{
TestLog.WriteLineIgnore(" name: " + pi.Name + " Type: " + pi.ParameterType);
}
}
private string SaveXElement(object elem, SaveOptions so)
{
string retVal = null;
switch (_mode)
{
case "Save":
using (StringWriter sw = new StringWriter())
{
if (_type.Name == "XElement")
{
(elem as XElement).Save(sw, so);
}
else if (_type.Name == "XDocument")
{
(elem as XDocument).Save(sw, so);
}
retVal = sw.ToString();
}
break;
case "ToString":
if (_type.Name == "XElement")
{
retVal = (elem as XElement).ToString(so);
}
else if (_type.Name == "XDocument")
{
retVal = (elem as XDocument).ToString(so);
}
break;
default:
TestLog.Compare(false, "TEST FAILED: wrong mode");
break;
}
return retVal;
}
private string AppendXmlDecl(string xml)
{
return _mode == "Save" ? @"<?xml version='1.0' encoding='utf-16'?>" + xml : xml;
}
private object Parse(string xml)
{
object o = null;
if (_type.Name == "XElement")
{
o = XElement.Parse(xml);
}
else if (_type.Name == "XDocument")
{
o = XDocument.Parse(xml);
}
return o;
}
#endregion
//[Variation(Desc = "1 level down", Priority = 0, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></p:A>" })]
//[Variation(Desc = "1 level down II.", Priority = 0, Params = new object[] { "<A><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></A>" })] // start at not root node
//[Variation(Desc = "2 levels down", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></p:A>" })]
//[Variation(Desc = "2 levels down II.", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><C xmlns:p='nsp'/></B></p:A>" })]
//[Variation(Desc = "2 levels down III.", Priority = 1, Params = new object[] { "<A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></A>" })]
//[Variation(Desc = "Siblings", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'/><C xmlns:p='nsp'/><p:C xmlns:p='nsp'/></A>" })]
//[Variation(Desc = "Children", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'><C xmlns:p='nsp'><p:C xmlns:p='nsp'/></C></p:B></A>" })]
//[Variation(Desc = "Xml namespace I.", Priority = 3, Params = new object[] { "<A xmlns:xml='http://www.w3.org/XML/1998/namespace'/>" })]
//[Variation(Desc = "Xml namespace II.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })]
//[Variation(Desc = "Xml namespace III.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:xml='http://www.w3.org/XML/1998/namespace' xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })]
//[Variation(Desc = "Default namespaces", Priority = 1, Params = new object[] { "<A xmlns='nsp'><p:B xmlns:p='nsp'><C xmlns='nsp' /></p:B></A>" })]
//[Variation(Desc = "Not used NS declarations", Priority = 2, Params = new object[] { "<A xmlns='nsp' xmlns:u='not-used'><p:B xmlns:p='nsp'><C xmlns:u='not-used' xmlns='nsp' /></p:B></A>" })]
//[Variation(Desc = "SameNS, different prefix", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><B xmlns:q='nsp'><p:C xmlns:p='nsp'/></B></p:A>" })]
public void testFromTheRootNodeSimple()
{
string xml = CurrentChild.Params[0] as string;
Object elemObj = Parse(xml);
// Write using XmlWriter in duplicate namespace decl. removal mode
string removedByWriter = SaveXElement(elemObj, SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting);
XElement elem = (elemObj is XDocument) ? (elemObj as XDocument).Root : elemObj as XElement;
// Remove the namespace decl. duplicates from the Xlinq tree
(from a in elem.DescendantsAndSelf().Attributes()
where a.IsNamespaceDeclaration && ((a.Name.LocalName == "xml" && (string)a == XNamespace.Xml.NamespaceName) ||
(from parentDecls in a.Parent.Ancestors().Attributes(a.Name)
where parentDecls.IsNamespaceDeclaration && (string)parentDecls == (string)a
select parentDecls).Any()
)
select a).ToList().Remove();
// Write XElement using XmlWriter without omiting
string removedByManual = SaveXElement(elemObj, SaveOptions.DisableFormatting);
ReaderDiff.Compare(removedByWriter, removedByManual);
}
//[Variation(Desc = "Default ns parent autogenerated", Priority = 1)]
public void testFromTheRootNodeTricky()
{
object e = new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute("xmlns", "nsp")));
if (_type == typeof(XDocument))
{
XDocument d = new XDocument();
d.Add(e);
e = d;
}
string act = SaveXElement(e, SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting);
string exp = AppendXmlDecl("<A xmlns='nsp'><B/></A>");
ReaderDiff.Compare(act, exp);
}
//[Variation(Desc = "Conflicts: NS redefinition", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D xmlns:p='nsp'/></p:C></p:B></p:A>",
// "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D/></p:C></p:B></p:A>" })]
//[Variation(Desc = "Conflicts: NS redefinition, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
// "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D/></C></B></A>" })]
//[Variation(Desc = "Conflicts: NS redefinition, default NS II.", Priority = 2, Params = new object[] { "<A xmlns=''><B xmlns='ns-other'><C xmlns=''><D xmlns=''/></C></B></A>",
// "<A><B xmlns='ns-other'><C xmlns=''><D/></C></B></A>" })]
//[Variation(Desc = "Conflicts: NS undeclaration, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
// "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D/></C></B></A>" })]
public void testConflicts()
{
object e1 = Parse(CurrentChild.Params[0] as string);
TestLog.WriteLineIgnore(SaveXElement(e1, SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting));
ReaderDiff.Compare(SaveXElement(e1, SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl(CurrentChild.Params[1] as string));
}
//[Variation(Desc = "Not from root", Priority = 1)]
public void testFromChildNode1()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute("xmlns", "nsp"))));
ReaderDiff.Compare(SaveXElement(e.Element("{nsp}A"), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:A xmlns:p1='nsp'><B xmlns='nsp'/></p1:A>"));
}
//[Variation(Desc = "Not from root II.", Priority = 1)]
public void testFromChildNode2()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"))));
ReaderDiff.Compare(SaveXElement(e.Element("{nsp}A"), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:A xmlns:p1='nsp'><p1:B/></p1:A>"));
}
//[Variation(Desc = "Not from root III.", Priority = 2)]
public void testFromChildNode3()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"))));
ReaderDiff.Compare(SaveXElement(e.Descendants("{nsp}B").FirstOrDefault(), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:B xmlns:p1='nsp'/>"));
}
//[Variation(Desc = "Not from root IV.", Priority = 2)]
public void testFromChildNode4()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B")));
ReaderDiff.Compare(SaveXElement(e.Descendants("{nsp}B").FirstOrDefault(), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:B xmlns:p1='nsp'/>"));
}
}
}
}
}
| |
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace StockTraderRI.ChartControls
{
public class LineChartPanel : Panel
{
protected override void OnInitialized(System.EventArgs e)
{
base.OnInitialized(e);
_childrenPositions = new ObservableCollection<Point>();
}
private static void OnValuesChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
LineChartPanel v = sender as LineChartPanel;
if (v == null)
return;
ItemCollection oldItems = args.OldValue as ItemCollection;
ItemCollection newItems = args.NewValue as ItemCollection;
if (oldItems != null)
((INotifyCollectionChanged)oldItems).CollectionChanged -= new NotifyCollectionChangedEventHandler(v.LineChartPanel_CollectionChanged);
if(args.Property == LineChartPanel.XValuesProperty)
{
if (GetXValues(v)!= null)
GetXValues(v).CollectionChanged += new NotifyCollectionChangedEventHandler(v.LineChartPanel_CollectionChanged);
}
else if(args.Property == LineChartPanel.YValuesProperty)
{
if(GetYValues(v)!=null)
GetYValues(v).CollectionChanged += new NotifyCollectionChangedEventHandler(v.LineChartPanel_CollectionChanged);
}
v.InvalidateArrange();
v.InvalidateVisual();
}
private void LineChartPanel_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
InvalidateArrange();
InvalidateVisual();
}
protected override void OnRender(DrawingContext dc)
{
if (dc == null)
{
throw new ArgumentNullException("dc");
}
base.OnRender(dc);
if (_childrenPositions.Count == 0)
return;
if (!IsSmoothOutline)
{
dc.DrawGeometry(AreaBrush, LinePen, CreateLineCurveGeometry());
}
else
{
dc.DrawGeometry(AreaBrush, LinePen, CreateAreaCurveGeometry());
}
}
private PathGeometry CreateLineCurveGeometry()
{
PathGeometry pathGeometry = new PathGeometry();
PathFigure pathFigure = new PathFigure();
pathGeometry.Figures.Add(pathFigure);
pathFigure.StartPoint = (Point)GeometryOperation.ComputeIntersectionPoint((FrameworkElement)InternalChildren[0], (FrameworkElement)InternalChildren[1]);
PolyLineSegment pls = new PolyLineSegment();
for(int i=1; i < InternalChildren.Count; i++)
pls.Points.Add(GeometryOperation.ComputeIntersectionPoint((FrameworkElement)InternalChildren[i],
((FrameworkElement)InternalChildren[i-1])));
pathFigure.Segments.Add(pls);
if(AreaBrush!=null)
{
pathFigure.Segments.Add(new LineSegment(new Point(_childrenPositions[_childrenPositions.Count - 1].X, GetHorizontalAxis(this)), false));
pathFigure.Segments.Add(new LineSegment(new Point(_childrenPositions[0].X, GetHorizontalAxis(this)), false));
}
return pathGeometry;
}
private PathGeometry CreateAreaCurveGeometry()
{
PathGeometry pathGeometry = new PathGeometry();
PathFigure pathFigure = new PathFigure();
pathGeometry.Figures.Add(pathFigure);
Point[] catmullRomPoints = new Point[_childrenPositions.Count];
_childrenPositions.CopyTo(catmullRomPoints, 0);
Point[] bezierPoints = GeometryOperation.CatmullRom(catmullRomPoints);
pathFigure.StartPoint = bezierPoints[0];
PolyBezierSegment pbs = new PolyBezierSegment();
for (int i = 1; i < bezierPoints.GetLength(0); i++)
pbs.Points.Add(bezierPoints[i]);
pathFigure.Segments.Add(pbs);
if (AreaBrush != null)
{
pathFigure.Segments.Add(new LineSegment(new Point(_childrenPositions[_childrenPositions.Count - 1].X, GetHorizontalAxis(this)), false));
pathFigure.Segments.Add(new LineSegment(new Point(_childrenPositions[0].X, GetHorizontalAxis(this)), false));
}
return pathGeometry;
}
protected override Size MeasureOverride(Size availableSize)
{
for (int i = 0; i < InternalChildren.Count; i++)
{
InternalChildren[i].Measure(availableSize);
}
return base.MeasureOverride(availableSize);
}
protected override Size ArrangeOverride(Size finalSize)
{
int count = Math.Min(XValues.Count, YValues.Count);
_childrenPositions.Clear();
for (int i = 0; i < count; i++)
{
double x = (i + 1 >= XValues.Count) ? XValues[i] : XValues[i] + XValues[i + 1];
Point position = new Point(x / 2, YValues[i]);
_childrenPositions.Add(position);
Rect r = new Rect(position.X - InternalChildren[i].DesiredSize.Width / 2,
position.Y - InternalChildren[i].DesiredSize.Height / 2
, InternalChildren[i].DesiredSize.Width, InternalChildren[i].DesiredSize.Height);
InternalChildren[i].Arrange(r);
}
return finalSize;
}
public bool IsSmoothOutline
{
get { return (bool)GetValue(IsSmoothOutlineProperty); }
set { SetValue(IsSmoothOutlineProperty, value); }
}
// Using a DependencyProperty as the backing store for IsSmoothOutline. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsSmoothOutlineProperty =
DependencyProperty.Register("IsSmoothOutline", typeof(bool), typeof(LineChartPanel), new UIPropertyMetadata(false));
public Pen LinePen
{
get { return (Pen)GetValue(LinePenProperty); }
set { SetValue(LinePenProperty, value); }
}
// Using a DependencyProperty as the backing store for LinePen. This enables animation, styling, binding, etc...
public static readonly DependencyProperty LinePenProperty =
DependencyProperty.Register("LinePen", typeof(Pen), typeof(LineChartPanel), new UIPropertyMetadata(null));
public Brush AreaBrush
{
get { return (Brush)GetValue(AreaBrushProperty); }
set { SetValue(AreaBrushProperty, value); }
}
// Using a DependencyProperty as the backing store for AreaBrush. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AreaBrushProperty =
DependencyProperty.Register("AreaBrush", typeof(Brush), typeof(LineChartPanel), new UIPropertyMetadata(null));
private ObservableCollection<double> XValues
{
get { return (ObservableCollection<double>)GetXValues(this); }
set { SetXValues(this, value); }
}
public static ObservableCollection<double> GetXValues(DependencyObject obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
return (ObservableCollection<double>)obj.GetValue(XValuesProperty);
}
public static void SetXValues(DependencyObject obj, ObservableCollection<double> value)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
obj.SetValue(XValuesProperty, value);
}
// Using a DependencyProperty as the backing store for XValues. This enables animation, styling, binding, etc...
public static readonly DependencyProperty XValuesProperty =
DependencyProperty.RegisterAttached("XValues", typeof(ObservableCollection<double>), typeof(LineChartPanel), new UIPropertyMetadata(null, new PropertyChangedCallback(OnValuesChanged)));
private ObservableCollection<double> YValues
{
get { return (ObservableCollection<double>)GetYValues(this); }
set { SetYValues(this, value); }
}
public static ObservableCollection<double> GetYValues(DependencyObject obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
return (ObservableCollection<double>)obj.GetValue(YValuesProperty);
}
public static void SetYValues(DependencyObject obj, ObservableCollection<double> value)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
obj.SetValue(YValuesProperty, value);
}
// Using a DependencyProperty as the backing store for YValues. This enables animation, styling, binding, etc...
public static readonly DependencyProperty YValuesProperty =
DependencyProperty.RegisterAttached("YValues", typeof(ObservableCollection<double>), typeof(LineChartPanel), new UIPropertyMetadata(null, new PropertyChangedCallback(OnValuesChanged)));
public static double GetHorizontalAxis(DependencyObject obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
return (double)obj.GetValue(HorizontalAxisProperty);
}
public static void SetHorizontalAxis(DependencyObject obj, double value)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
obj.SetValue(HorizontalAxisProperty, value);
}
// Using a DependencyProperty as the backing store for HorizontalAxis. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HorizontalAxisProperty =
DependencyProperty.RegisterAttached("HorizontalAxis", typeof(double), typeof(LineChartPanel), new UIPropertyMetadata(0.0));
private ObservableCollection<Point> _childrenPositions;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.